A fast Python library for merging two Microsoft Word (.docx) documents into one. Easily insert content at specific positions or based on placeholder patterns.
Install via pip:
pip install docx-merge-xmlOnly one dependency:
lxml– for parsing and modifying the DOCX XML content
merge_docx(
source_path: str,
content_path: str,
output_path: str | None = None,
pattern: str | None = None,
insert_start: bool = False,
insert_end: bool = False,
) -> BytesIOParameters:
source_path(required) – Path to the base.docxfilecontent_path(required) – Path to the.docxfile to insert into the baseoutput_path– Path to save the merged documentpattern– Placeholder string in the source file to be replaced with inserted contentinsert_start– Insert the content at the beginning of the source fileinsert_end– Insert the content at the end of the source file
🔔 Note: You can combine pattern, insert_start, and insert_end and at least one is required.
from docx_merge import merge_docx
buffer = merge_docx(
source_path="./source.docx",
content_path="./table.docx",
pattern="{{table}}"
)
# Use buffer (e.g., send as a response in a server)from docx_merge import merge_docx
buffer = merge_docx(
source_path="./source.docx",
content_path="./table.docx",
output_path="./output.docx",
pattern="{{table}}"
)from docx_merge import merge_docx
merge_docx(
source_path="./source.docx",
content_path="./table.docx",
output_path="./output.docx",
insert_start=True
)from docx_merge import merge_docx
merge_docx(
source_path="./source.docx",
content_path="./table.docx",
output_path="./output.docx",
insert_end=True
)This project uses Pytest for unit testing.
To run tests:
poetry run pytestMIT
Contributions, bug reports, and feature requests are welcome! Feel free to open an issue or submit a pull request.