From 9b21b29d54a9fc687fe9dfb79f274f8dcb8d75ac Mon Sep 17 00:00:00 2001 From: Roman Danilov Date: Tue, 3 Dec 2019 16:51:58 -0800 Subject: [PATCH] Add support for code element --- html2docx/html2docx.py | 4 +++- tests/data/code.html | 1 + tests/data/code.json | 17 +++++++++++++++++ tests/test_html2docx.py | 12 ++++++++++-- 4 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 tests/data/code.html create mode 100644 tests/data/code.json diff --git a/html2docx/html2docx.py b/html2docx/html2docx.py index 5f244d4..3237e18 100644 --- a/html2docx/html2docx.py +++ b/html2docx/html2docx.py @@ -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"]: @@ -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() diff --git a/tests/data/code.html b/tests/data/code.html new file mode 100644 index 0000000..bd636c6 --- /dev/null +++ b/tests/data/code.html @@ -0,0 +1 @@ +

Add this line: value = get_value(arg) to the file.

diff --git a/tests/data/code.json b/tests/data/code.json new file mode 100644 index 0000000..4210486 --- /dev/null +++ b/tests/data/code.json @@ -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." + } + ] + } +] diff --git a/tests/test_html2docx.py b/tests/test_html2docx.py index 3cef917..e8e4355 100644 --- a/tests/test_html2docx.py +++ b/tests/test_html2docx.py @@ -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(): @@ -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)