Skip to content

Commit

Permalink
Add support for code element
Browse files Browse the repository at this point in the history
  • Loading branch information
roman-danilov committed Dec 9, 2019
1 parent 72bb7e7 commit 9b21b29
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 3 deletions.
4 changes: 3 additions & 1 deletion html2docx/html2docx.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> N
elif tag == "br":
if self.r:
self.r.add_break()
elif tag == "code":
self.init_run([("name", "Mono")])
elif tag in ["em", "i"]:
self.init_run([("italic", True)])
elif tag in ["h1", "h2", "h3", "h4", "h5", "h6"]:
Expand Down Expand Up @@ -191,7 +193,7 @@ def handle_data(self, data: str) -> None:
self.add_text(data)

def handle_endtag(self, tag: str) -> None:
if tag in ["a", "b", "em", "i", "span", "strong", "sub", "sup", "u"]:
if tag in ["a", "b", "code", "em", "i", "span", "strong", "sub", "sup", "u"]:
self.finish_run()
elif tag in ["h1", "h2", "h3", "h4", "h5", "h6", "li", "ol", "p", "pre", "ul"]:
self.finish_p()
Expand Down
1 change: 1 addition & 0 deletions tests/data/code.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>Add this line: <code>value = get_value(arg)</code> to the file.</p>
17 changes: 17 additions & 0 deletions tests/data/code.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"text": "Add this line: value = get_value(arg) to the file.",
"runs": [
{
"text": "Add this line: "
},
{
"text": "value = get_value(arg)",
"name": "Mono"
},
{
"text": " to the file."
}
]
}
]
12 changes: 10 additions & 2 deletions tests/test_html2docx.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@

from .utils import PROJECT_DIR, TEST_DIR

FONT_ATTRS = ["bold", "italic", "strike", "subscript", "superscript", "underline"]
FONT_ATTRS = [
"bold",
"italic",
"name",
"strike",
"subscript",
"superscript",
"underline",
]


def generate_testdata():
Expand Down Expand Up @@ -56,7 +64,7 @@ def test_html2docx(html_path, spec_path):
)
for attr in FONT_ATTRS:
msg = f"Wrong {attr} for text '{run.text}' in {html_rel_path}"
assert getattr(run.font, attr) is run_spec.get(attr), msg
assert getattr(run.font, attr) == run_spec.get(attr), msg
if shapes_spec:
shapes = run.part.inline_shapes
assert len(shapes) == len(shapes_spec)
Expand Down

0 comments on commit 9b21b29

Please sign in to comment.