Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get nice table borders in MicroSoft Word #225

Merged
merged 1 commit into from
Oct 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions backend/document/stet/stet.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from document.utils.file_utils import template_path
from docx import Document # type: ignore
from htmldocx import HtmlToDocx # type: ignore
from docx.oxml import OxmlElement # type: ignore
from docx.oxml.ns import qn # type: ignore

logger = settings.logger(__name__)

Expand Down Expand Up @@ -185,6 +187,26 @@ def get_word_entry_dtos(
return word_entry_dtos, list(set(book_codes_))


def set_docx_table_borders_for_word(docx_filepath: str) -> None:
# Open or create the document
doc = Document(docx_filepath)
# Loop through tables and set borders
for table in doc.tables:
tbl = table._element
tblBorders = OxmlElement("w:tblBorders")
for border_name in ["top", "left", "bottom", "right", "insideH", "insideV"]:
border = OxmlElement(f"w:{border_name}")
border.set(qn("w:val"), "single")
border.set(qn("w:sz"), "8") # 1px equivalent in Word (1/8 point units)
border.set(qn("w:space"), "0")
border.set(qn("w:color"), "000000") # Border color
tblBorders.append(border)
tbl.tblPr.append(tblBorders)

# Save the updated document
doc.save(docx_filepath)


def generate_docx_document(
lang0_code: str,
lang1_code: str,
Expand Down Expand Up @@ -362,6 +384,10 @@ def generate_docx_document(
html_to_docx = HtmlToDocx()
# docx_filepath = f"{Path(filepath_).stem}.docx"
html_to_docx.parse_html_file(filepath_, f"{output_dir}/{Path(docx_filepath_).stem}")
# At this point the tables have a border if viewed in libreoffice,
# but getting table borders to work in Word takes a little more work:
set_docx_table_borders_for_word(docx_filepath_)

return docx_filepath_
# # doc = html_to_docx.parse_html_string(html)
# # logger.debug("doc: %s", doc)
Loading