|
| 1 | +""" |
| 2 | +
|
| 3 | +Markdown to DOCX conversion module extracted from md2docx-python project. |
| 4 | +
|
| 5 | +Project address: https://github.com/shloktech/md2docx-python/ |
| 6 | +Project LICENSE: LICENSE.MD2DOCX |
| 7 | +
|
| 8 | +The reason for extraction is to align the API and features with the needs. |
| 9 | +Changes: |
| 10 | +- input is text, not file |
| 11 | +- markdown2 is used instead of markdown |
| 12 | +- table support is added via markdown2 extras and additional HTML processing |
| 13 | +
|
| 14 | +""" |
| 15 | + |
| 16 | +import markdown2 |
| 17 | +from docx import Document |
| 18 | +from bs4 import BeautifulSoup, Tag |
| 19 | + |
| 20 | + |
| 21 | +def get_element_text(element: Tag) -> str: |
| 22 | + if hasattr(element, "get_text"): |
| 23 | + return element.get_text(strip=True) |
| 24 | + else: |
| 25 | + return str(element).strip() |
| 26 | + |
| 27 | + |
| 28 | +def process_list_items(list_element: Tag, doc: Document, style_base: str, level=0): |
| 29 | + # Get direct children li elements only (not nested) |
| 30 | + for li in list_element.find_all("li", recursive=False): |
| 31 | + # Get text content, excluding nested lists |
| 32 | + text_parts = [] |
| 33 | + for child in li.children: |
| 34 | + if child.name not in ["ul", "ol"]: |
| 35 | + text_parts.append(get_element_text(child)) |
| 36 | + |
| 37 | + text = " ".join(text_parts).strip() |
| 38 | + |
| 39 | + # Add paragraph with appropriate indentation level |
| 40 | + if text: |
| 41 | + style = style_base if level == 0 else f"{style_base} {level + 1}" |
| 42 | + doc.add_paragraph(text, style=style) |
| 43 | + |
| 44 | + # Process nested lists |
| 45 | + nested_ul = li.find("ul", recursive=False) |
| 46 | + nested_ol = li.find("ol", recursive=False) |
| 47 | + |
| 48 | + if nested_ul: |
| 49 | + process_list_items(nested_ul, doc, "List Bullet", level + 1) |
| 50 | + if nested_ol: |
| 51 | + process_list_items(nested_ol, doc, "List Number", level + 1) |
| 52 | + |
| 53 | + |
| 54 | +def markdown_to_word_file(markdown_source: str, word_file_path: str): |
| 55 | + doc = markdown_to_word_object(markdown_source) |
| 56 | + doc.save(word_file_path) |
| 57 | + |
| 58 | + |
| 59 | +def markdown_to_word_object(markdown_source: str) -> Document: |
| 60 | + # Converting Markdown to HTML |
| 61 | + html_content = markdown2.markdown(markdown_source, extras=["tables", "wiki-tables"]) |
| 62 | + |
| 63 | + # Creating a new Word Document |
| 64 | + doc = Document() |
| 65 | + |
| 66 | + # Converting HTML to text and adding it to the Word Document |
| 67 | + soup = BeautifulSoup(html_content, "html.parser") |
| 68 | + |
| 69 | + # Adding content to the Word Document |
| 70 | + for element in soup: |
| 71 | + if element.name == "h1": |
| 72 | + doc.add_heading(element.text, level=1) |
| 73 | + elif element.name == "h2": |
| 74 | + doc.add_heading(element.text, level=2) |
| 75 | + elif element.name == "h3": |
| 76 | + doc.add_heading(element.text, level=3) |
| 77 | + elif element.name == "p": |
| 78 | + paragraph = doc.add_paragraph() |
| 79 | + for child in element.children: |
| 80 | + if child.name == "strong": |
| 81 | + paragraph.add_run(child.text).bold = True |
| 82 | + elif child.name == "em": |
| 83 | + paragraph.add_run(child.text).italic = True |
| 84 | + else: |
| 85 | + paragraph.add_run(child) |
| 86 | + elif element.name == "ul": |
| 87 | + process_list_items(element, doc, "List Bullet") |
| 88 | + elif element.name == "ol": |
| 89 | + process_list_items(element, doc, "List Number") |
| 90 | + elif element.name == "table": |
| 91 | + rows_data = [] |
| 92 | + for row in element.find_all("tr"): |
| 93 | + cells = row.find_all(["th", "td"]) |
| 94 | + row_data = [cell.get_text(strip=True) for cell in cells] |
| 95 | + if row_data: |
| 96 | + rows_data.append(row_data) |
| 97 | + |
| 98 | + if rows_data: |
| 99 | + columns_count = len(rows_data[0]) |
| 100 | + table = doc.add_table(rows=len(rows_data), cols=columns_count) |
| 101 | + table.style = "Table Grid" |
| 102 | + |
| 103 | + for row_index, row_data in enumerate(rows_data): |
| 104 | + for column_index, cell_text in enumerate(row_data): |
| 105 | + if column_index < columns_count: |
| 106 | + table.rows[row_index].cells[column_index].text = cell_text |
| 107 | + |
| 108 | + # Make the first row bold if it is a header |
| 109 | + first_row = element.find("tr") |
| 110 | + if first_row and first_row.find("th"): |
| 111 | + for cell in table.rows[0].cells: |
| 112 | + for paragraph in cell.paragraphs: |
| 113 | + for run in paragraph.runs: |
| 114 | + run.bold = True |
| 115 | + |
| 116 | + return doc |
0 commit comments