### Install python-docx-template with pip Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Install the docxtpl package using pip. ```default pip install docxtpl ``` -------------------------------- ### Advanced Listing example with autoescape Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/listing.md Demonstrates the interplay between Listing and autoescape rendering. Listing output is intentionally raw XML, while plain variables get escaped by Jinja2. ```python from docxtpl import DocxTemplate, Listing tpl = DocxTemplate("tpl.docx") special = "Use literally or \\n for a newline" lst = Listing(special) # render with autoescape=True: Listing output is intentionally raw XML # (it emits __html__), while plain variables get escaped by Jinja2 tpl.render({"code": lst, "note": special}, autoescape=True) tpl.save("out.docx") ``` -------------------------------- ### Basic RichText add example Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/richtext.md Demonstrates adding formatted text fragments with bold, color, underline, font, and size. ```python from docxtpl import RichText rt = RichText() rt.add("Important: ", bold=True) rt.add("see the note", color="#ff0000", underline="dotted") rt.add(" or the annex", font="Courier New", size=14) print(str(rt)) ``` -------------------------------- ### Basic render() example Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/template.md Basic usage of render() with a context dictionary. Loads a template, renders it with the provided variables, and saves the output document. ```python from docxtpl import DocxTemplate tpl = DocxTemplate("report_template.docx") context = { "company_name": "World company", "items": [{"label": "Apple", "price": 1.2}, {"label": "Orange", "price": 0.8}], } tpl.render(context) tpl.save("report.docx") ``` -------------------------------- ### Set up Pipenv environment and run tests Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Set up a Python environment using Pipenv for python-docx-template. Installs dependencies with Python 3.6, enters the virtual environment, and runs the tests. ```default pip install pipenv (if not already done) cd python-docx-template (where Pipfiles are) pipenv install --python 3.6 -d pipenv shell cd tests/ python runtests.py ``` -------------------------------- ### Install python-docx-template with conda Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Install the docxtpl package using conda from the conda-forge channel. ```default conda install docxtpl --channel conda-forge ``` -------------------------------- ### Basic Listing example Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/listing.md Shows how to use Listing to preserve newlines and paragraphs in a template. The template should contain {{ address }} in a single paragraph. ```python from docxtpl import DocxTemplate, Listing tpl = DocxTemplate("tpl.docx") address = "1st street\n2nd street\aPost: 75001 Paris" tpl.render({"address": Listing(address)}) tpl.save("out.docx") ``` -------------------------------- ### Create and use a sub-document Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/template.md Example of creating a sub-document with new_subdoc(), adding paragraphs, headings, and pictures, then rendering and saving the merged document. ```python from docxtpl import DocxTemplate from docx.shared import Inches tpl = DocxTemplate("master.docx") sd = tpl.new_subdoc() sd.add_paragraph("Inserted sub-document") sd.add_heading("Section title", level=1) sd.add_picture("logo.png", width=Inches(1.25)) tpl.render({"mysubdoc": sd}) tpl.save("merged.docx") ``` -------------------------------- ### Instantiate DocxTemplate with a template file Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/template.md Basic usage example: import DocxTemplate and instantiate it with a template file path. The document is not parsed until needed; loading happens lazily through init_docx(), get_docx(), render(), or save(). ```python from docxtpl import DocxTemplate tpl = DocxTemplate("invoice_template.docx") ``` -------------------------------- ### Install docxcompose and catch ImportError for Subdoc Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/errors.md Install the optional docxcompose dependency and catch the ImportError that occurs when Subdoc is not available. The import failure is swallowed in docxtpl/__init__.py, so Subdoc is absent and new_subdoc() also fails without docxcompose. ```shell pip install docxtpl[subdoc] ``` ```python try: from docxtpl import Subdoc except ImportError: print("install docxcompose: pip install docxtpl[subdoc]") ``` -------------------------------- ### RichTextParagraph usage example Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/richtext.md Example of creating a RichTextParagraph with a heading style and adding rich text, then rendering it into a template variable. ```python from docxtpl import RichTextParagraph p = RichTextParagraph("Title line", parastyle="Heading1") p.add(RichText("body text", italic=True)) tpl.render({"my_paras": p}) ``` -------------------------------- ### get_undeclared_template_variables usage example Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/template.md Example usage of get_undeclared_template_variables. It loads a template, passes a context with known variables, and prints the set of missing variables. ```python from docxtpl import DocxTemplate tpl = DocxTemplate("tpl.docx") missing = tpl.get_undeclared_template_variables(context={"known": 1}) print(missing) # e.g. {'customer_name'} ``` -------------------------------- ### Import Subdoc Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/subdoc.md Import the Subdoc class from docxtpl. This import is guarded and silently fails if the optional 'subdoc' extra is not installed. ```python from docxtpl import Subdoc ``` -------------------------------- ### Multi-rendering with reset_replacements Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/template.md Usage example for multi-rendering with the same DocxTemplate instance. The documented sequence per rendering is reset_replacements() → the replace_* calls → render(). ```python from docxtpl import DocxTemplate tpl = DocxTemplate("tpl.docx") for i in range(2): tpl.reset_replacements() tpl.replace_pic("logo.png", f"logo_{i}.png") tpl.render({"n": i}) tpl.save(f"out_{i}.docx") ``` -------------------------------- ### Example: same-part subdoc with python-docx API Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/subdoc.md Creates a sub-document using the same part as the master, adds paragraphs, headings, pictures, and a table, then renders it into the template. Requires the python-docx Inches import. ```python from docxtpl import DocxTemplate from docx.shared import Inches tpl = DocxTemplate("master.docx") sd = tpl.new_subdoc() # same-part subdoc, python-docx API sd.add_paragraph("This is a sub-document inserted into a bigger one") sd.add_heading("Heading, level 1", level=1) sd.add_picture("python_logo.png", width=Inches(1.25)) table = sd.add_table(rows=1, cols=3) for i, h in enumerate(["Qty", "Id", "Desc"]): table.rows[0].cells[i].text = h row = table.add_row().cells row[0].text, row[1].text, row[2].text = "1", "101", "Spam" tpl.render({"mysubdoc": sd}) tpl.save("output.docx") ``` -------------------------------- ### Correct variable spacing Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Use this syntax instead: always put a space after the starting var delimiter and a space before the ending one. ```default {{ myvariable }} {{r myrichtext }} ``` -------------------------------- ### Correct tag spacing Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Use this syntax instead: always put a space after the starting tag delimiter and a space before the ending one. ```default {% if something %} {%p if display_paragraph %} ``` -------------------------------- ### Example: subdoc from separate .docx file Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/subdoc.md Creates a sub-document from a separate .docx file, attaching styles, pictures, and numbering via docxcompose. Requires the optional 'subdoc' extra. ```python from docxtpl import DocxTemplate tpl = DocxTemplate("master.docx") sd = tpl.new_subdoc("subchapter.docx") # attaches styles/pictures/numbering tpl.render({"chapter": sd}) tpl.save("output.docx") ``` -------------------------------- ### Incorrect variable spacing (avoid) Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Avoid this syntax: always put a space after the starting var delimiter and a space before the ending one. ```default {{myvariable}} {{rmyrichtext}} ``` -------------------------------- ### Incorrect tag spacing (avoid) Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Avoid this syntax: always put a space after the starting tag delimiter and a space before the ending one. ```default {%if something%} {%pif display_paragraph%} ``` -------------------------------- ### Basic usage of DocxTemplate Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Shows how to load a Word template, render it with a context dictionary, and save the generated document. ```default from docxtpl import DocxTemplate doc = DocxTemplate("my_word_template.docx") context = { 'company_name' : "World company" } doc.render(context) doc.save("generated_doc.docx") ``` -------------------------------- ### DocxTemplate.init_docx() Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/configuration.md Documentation for the DocxTemplate.init_docx() method. ```APIDOC ## DocxTemplate.init_docx() ### Description Initializes the document. By default, it reloads a previously rendered document unless reload=False. ### Method Function ### Signature ```python DocxTemplate.init_docx(reload: bool = True) ``` ### Parameters - **reload** (bool) - Optional - Default: True - Reloads a previously rendered document unless reload=False. ``` -------------------------------- ### Get undeclared template variables with get_undeclared_template_variables Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Retrieves the set of undeclared template variables after rendering. If context is not passed, you will get a set with all keys you need, e.g. to be prompted to a user or written in a file for manual processing. ```default tpl=DocxTemplate('your_template.docx') tpl.render(context_dict) set_of_variables = tpl.get_undeclared_template_variables(context=context_dict) ``` -------------------------------- ### Horizontal merge within for loop Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Span horizontally within a for loop. See tests/horizontal_merge.py for an example. ```default {% hm %} ``` -------------------------------- ### Listing.__init__(text) Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/listing.md Initializes a Listing instance with the given text. Non-string values are cast to string and then HTML-escaped to ensure valid OOXML. ```APIDOC ## Listing.__init__(text) ### Description Initializes a Listing instance with the given text. Non-string values are cast to string and then HTML-escaped to ensure valid OOXML. ### Method Constructor ### Parameters - **text** (str / bytes / scalar) - Required - The text to preserve line structure of. Non-str/bytes values are cast via str(); then escaped with html.escape. ### Request Example ```python from docxtpl import Listing lst = Listing("1st street\n2nd street\aPost: 75001 Paris") ``` ### Response #### Success Response - **xml** (str) - The escaped string stored in the instance. #### Response Example ```python lst.xml # escaped string ``` ``` -------------------------------- ### Subdoc.__init__() Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/configuration.md Documentation for the Subdoc constructor. ```APIDOC ## Subdoc.__init__() ### Description Initializes a Subdoc instance. See subdoc.md for details. ### Method Constructor ### Signature ```python Subdoc.__init__(tpl, docpath=None) ``` ### Parameters - **tpl** - Required - The template. - **docpath** - Optional - The document path. ``` -------------------------------- ### Vertical merge within for loop Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Merge cells vertically within a for loop. See tests/vertical_merge.py for an example. ```default {% vm %} ``` -------------------------------- ### Use custom Jinja filter in template Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Template usage of the custom Jinja filter 'multiply_by' defined in the previous example. ```default Euros price : {{ price_dollars|multiply_by(0.88) }} ``` -------------------------------- ### DocxTemplate.__init__ Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/template.md Constructor for the DocxTemplate class, which loads a .docx template file for Jinja2 rendering. ```APIDOC ## DocxTemplate.__init__ ### Description Initializes a new DocxTemplate instance with a template file path or file-like object. The document is not parsed until needed; loading happens lazily through init_docx(), get_docx(), render(), or save(). ### Method Constructor ### Signature ```python def __init__(self, template_file: Union[IO[bytes], str, PathLike]) -> None: ``` ### Parameters - **template_file** (Union[IO[bytes], str, PathLike]) - Required - Path to the .docx template, or a readable binary file-like object (IO[bytes]). ### Usage Example ```python from docxtpl import DocxTemplate tpl = DocxTemplate("invoice_template.docx") ``` ### Notes - The constructor stores the template_file for lazy reloading. - Initializes internal state: docx is None, is_rendered is False, is_saved is False, allow_missing_pics is False, and replacement dicts are empty (via reset_replacements()). ``` -------------------------------- ### Jinja-like comments for paragraphs, rows, and cells Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Add jinja-like comments in your template using these tags. See tests/templates/comments_tpl.docx for an example. ```default {#p this is a comment as a paragraph #} {#tr this is a comment as a table row #} {#tc this is a comment as a table cell #} ``` -------------------------------- ### InlineImage.__init__ Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/inline-image.md Initializes an InlineImage instance with the given template, image descriptor, and optional dimensions, hyperlink anchor, title, and description. ```APIDOC ## InlineImage.__init__ ### Description Initializes an InlineImage instance. The image is anchored in the template at render time. ### Method Constructor ### Signature ```python InlineImage(tpl, image_descriptor, width=None, height=None, anchor=None, title=None, descr=None) ``` ### Parameters - **tpl** (DocxTemplate) - Required - The template the image belongs to; used to reach the part being rendered and to create hyperlink relationships. - **image_descriptor** (path, file-like object, or python-docx image descriptor) - Required - Passed to new_pic_inline(); can be a filename, stream, or image descriptor. - **width** (Length, e.g. Mm, Inches, Pt) - Optional - Desired width; if None and height given, derived from aspect ratio. - **height** (Length) - Optional - Desired height. - **anchor** (str URL) - Optional - If set, wraps the drawing as a hyperlink to this URL. - **title** (str) - Optional - Sets title on wp:docPr and pic:cNvPr. - **descr** (str) - Optional - Sets descr on wp:docPr and pic:cNvPr. ### Example ```python from docxtpl import InlineImage from docx.shared import Mm img = InlineImage(tpl, 'image.png', width=Mm(20), height=Mm(15), title='My Image', descr='Description') ``` ``` -------------------------------- ### Basic RichText usage with DocxTemplate Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/richtext.md Shows how to create a RichText object, add formatted text, and render it into a template. ```python from docxtpl import DocxTemplate, RichText tpl = DocxTemplate("tpl.docx") rt = RichText("Hello ") rt.add("bold", bold=True) tpl.render({"msg": rt}) tpl.save("out.docx") ``` -------------------------------- ### Subdoc.__str__() / __unicode__() / __html__() Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/subdoc.md Return the XML fragment from _get_xml(), which is what gets rendered into the master document when the subdoc is used in a template variable. ```APIDOC ## Subdoc.__str__() / __unicode__() / __html__() ### Description Return the XML fragment from _get_xml(), which is what gets rendered into the master document when the subdoc is used in a template variable. ### Method String conversion methods ### Returns - (str) - The inner XML fragment of the sub-document body. ### Usage These methods are automatically called when the Subdoc is rendered in a template, e.g., {{ mysubdoc }}. ``` -------------------------------- ### Import Listing Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/listing.md Import the Listing class from the docxtpl package. ```python from docxtpl import Listing ``` -------------------------------- ### Run docxtpl CLI to render a .docx template Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/cli.md Renders a .docx template from a JSON file of context data. The template_path and json_path must be existing files ending in .docx and .json respectively; output_filename must end in .docx and not exist unless overwrite is confirmed or forced with -o/--overwrite. Use -q/--quiet to suppress success and exit messages. ```bash python -m docxtpl [-h] [-o] [-q] template_path json_path output_filename ``` -------------------------------- ### Basic InlineImage usage with width and height Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/inline-image.md Creates a DocxTemplate, defines an InlineImage with a width of 20mm and a title/description, and a list of images with height 10mm. Renders the template and saves the output. ```python from docxtpl import DocxTemplate, InlineImage from docx.shared import Mm tpl = DocxTemplate("inline_image_tpl.docx") context = { "myimage": InlineImage( tpl, "python_logo.png", width=Mm(20), title="python-logo-title", descr="python-logo-description", ), "frameworks": [ {"image": InlineImage(tpl, "django.png", height=Mm(10)), "desc": "..."}, {"image": InlineImage(tpl, "zope.png", height=Mm(10)), "desc": "..."}, ], } tpl.render(context) tpl.save("out.docx") ``` -------------------------------- ### Long inline conditional text Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst A text containing Jinja2 tags may be unreadable if too long. This example shows a long inline conditional. ```default My house is located {% if living_in_town %} in urban area {% else %} in countryside {% endif %} and I love it. ``` -------------------------------- ### Subdoc.__init__(tpl, docpath=None) Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/subdoc.md Initializes a Subdoc instance bound to a master template. If a docpath is provided, it attaches parts from the sub-document to the master; otherwise, it shares the master's part. ```APIDOC ## Subdoc.__init__(tpl, docpath=None) ### Description Initializes a Subdoc instance bound to a master template. If a docpath is provided, it attaches parts from the sub-document to the master; otherwise, it shares the master's part. ### Method Constructor ### Parameters - **tpl** (DocxTemplate) - Required - The master template; its loaded Document (tpl.get_docx()) becomes both the compose target and the part reuse source. - **docpath** (str/path) - Optional - Path to the .docx sub-document file. When given, SubdocComposer(self.docx) is asked to attach_parts(self.subdocx) — copying styles, numbering, images, diagrams, shapes, footnotes and references from the sub-document into the master. When None, the sub-document shares the master document's part (self.subdocx._part = self.docx._part), so elements (pictures etc.) resolve through the master part. ### Example ```python from docxtpl import DocxTemplate tpl = DocxTemplate("master.docx") sd = tpl.new_subdoc() # same-part subdoc, python-docx API sd.add_paragraph("This is a sub-document inserted into a bigger one") sd.add_heading("Heading, level 1", level=1) sd.add_picture("python_logo.png", width=Inches(1.25)) table = sd.add_table(rows=1, cols=3) for i, h in enumerate(["Qty", "Id", "Desc"]): table.rows[0].cells[i].text = h row = table.add_row().cells row[0].text, row[1].text, row[2].text = "1", "101", "Spam" tpl.render({"mysubdoc": sd}) tpl.save("output.docx") ``` From a separate .docx file (requires docxcompose): ```python from docxtpl import DocxTemplate tpl = DocxTemplate("master.docx") sd = tpl.new_subdoc("subchapter.docx") # attaches styles/pictures/numbering tpl.render({"chapter": sd}) tpl.save("output.docx") ``` ``` -------------------------------- ### DocxTemplate __init__ and save signatures with Union[IO[bytes], str, PathLike] Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/types.md Two signatures in DocxTemplate that accept a template file or save filename as a binary stream, filesystem path, or os.PathLike object. The __init__ is at docxtpl/template.py:46 and save at :884. The union type allows flexible input for template loading and saving. ```python def __init__(self, template_file: Union[IO[bytes], str, PathLike]) -> None: ``` ```python def save(self, filename: Union[IO[bytes], str, PathLike], *args, **kwargs) -> None: ``` -------------------------------- ### Horizontal span with {% colspan %} Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Span table cells horizontally. must contain an integer for the number of columns to span. See tests/dynamic_table.py for an example. ```default {% colspan %} ``` -------------------------------- ### Listing __init__ method Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/listing.md The constructor of Listing, which casts non-string values to string and escapes the text. ```python def __init__(self, text): # If not a string : cast to string (ex: int, dict etc...) if not isinstance(text, (str, bytes)): text = str(text) self.xml = escape(text) ``` -------------------------------- ### Incorrect use of {%p ... %} in same paragraph Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Do not use {%p, {%tr, {%tc or {%r twice in the same paragraph, row, column, or run. This example shows the incorrect usage. ```default {%p if display_paragraph %}Here is my paragraph {%p endif %} ``` -------------------------------- ### Conditional paragraph with {%p if %} Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Example of using the {%p ... %} tag to conditionally include paragraphs. The paragraphs containing the {%p ... %} tags will never appear in the generated docx, regardless of the display_paragraph value. ```default {%p if display_paragraph %} One or many paragraphs {%p endif %} ``` -------------------------------- ### InlineImage __init__ signature Source: https://github.com/elapouya/python-docx-template/blob/master/_autodocs/api-reference/inline-image.md The constructor signature for InlineImage, accepting tpl, image_descriptor, width, height, anchor, title, and descr. ```python def __init__( self, tpl, image_descriptor, width=None, height=None, anchor=None, title=None, descr=None, ): ``` -------------------------------- ### python -m docxtpl command-line usage Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Command-line usage for generating a docx file from a template and JSON data. The -o flag overwrites an existing output file without confirmation, and -q suppresses non-essential messages. ```default usage: python -m docxtpl [-h] [-o] [-q] template_path json_path output_filename Make docx file from existing template docx and json data. positional arguments: template_path The path to the template docx file. json_path The path to the json file with the data. output_filename The filename to save the generated docx. optional arguments: -h, --help show this help message and exit -o, --overwrite If output file already exists, overwrites without asking for confirmation -q, --quiet Do not display unnecessary messages ``` -------------------------------- ### Run tests to generate docx files Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.rst Run the test suite to generate final docx files from the test templates. The generated files are placed in the tests/output directory. ```default cd tests/ python runtests.py ```