65 lines
2.3 KiB
Markdown
65 lines
2.3 KiB
Markdown
## Easy Word Docs in Python
|
|
---
|
|
This library implements a word document builder class that allows you to pass a list of functions and it will generate a word document using each function to generate a page.
|
|
|
|
This has the benefit of providing modularity in scripts that make word documents as their outputs as a script can be configured to use any combination
|
|
of page functions to build a word doc.
|
|
|
|
### Tips:
|
|
---
|
|
The current page number can be accessed by accessing the current_section member variable of the document builder.
|
|
|
|
The current figure number and table number can be accessed with the member variables figure_number and table_number. This allows you to have dynanmically
|
|
labeled graphs and tables in your document pages
|
|
|
|
The PageConfig class allows you to customize the page breaking behavior to ensure the correct number of pages are present in the final document
|
|
|
|
## Usage:
|
|
---
|
|
```
|
|
from docx import Document
|
|
from docx.shared import Inches, Pt
|
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
from typing import Callable, List, Any
|
|
|
|
# Example page function
|
|
def title_page(builder: WordDocumentBuilder, title: str = "Document Title", author: str = "Author", **kwargs):
|
|
"""Create a title page."""
|
|
title_para = builder.doc.add_paragraph()
|
|
title_run = title_para.add_run(title)
|
|
title_run.font.size = Pt(28)
|
|
title_run.bold = True
|
|
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
|
|
builder.doc.add_paragraph() # Spacing
|
|
|
|
author_para = builder.doc.add_paragraph(author)
|
|
author_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
|
|
# Create document builder
|
|
builder = WordDocumentBuilder()
|
|
|
|
# Define pages, these are functions
|
|
pages = [
|
|
PageConfig(title_page, add_page_break=False)
|
|
]
|
|
|
|
# Create document with custom parameters. Only pages and the output path are required, the following parameters will be passed into the functions that
|
|
# request them through **kwargs. Think of it kinda like dependancy injection.
|
|
doc = builder.create_document(
|
|
pages,
|
|
"output/my_document.docx",
|
|
title="My Custom Report",
|
|
author="John Doe",
|
|
heading="Introduction",
|
|
content="This is the introduction section with detailed information.",
|
|
table_data=[
|
|
["Product", "Price", "Quantity"],
|
|
["Widget", "$10", "100"],
|
|
["Gadget", "$25", "50"]
|
|
],
|
|
table_title="Sales Data"
|
|
)
|
|
```
|
|
|