### Install python-docx-template using pip or conda Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Instructions for installing the python-docx-template package using either pip or conda. This is the first step before using the library. ```shell pip install docxtpl ``` ```shell conda install docxtpl --channel conda-forge ``` -------------------------------- ### Basic Usage of python-docx-template Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md A simple example demonstrating how to load a Word template, define a context with variables, render the template, and save the generated document. ```python from docxtpl import DocxTemplate doc = DocxTemplate("my_word_template.docx") context = { 'company_name' : "World company" } doc.render(context) doc.save("generated_doc.docx") ``` -------------------------------- ### Dynamic Table Generation with docxtpl Source: https://context7.com/elapouya/python-docx-template/llms.txt Illustrates generating tables with dynamic rows and columns within a Word document using Jinja2 loops and control structures facilitated by the 'docxtpl' library. This example assumes a 'table_template.docx' exists and is set up for table templating. The output is a .docx file with a populated table. ```python from docxtpl import DocxTemplate doc = DocxTemplate("table_template.docx") ``` -------------------------------- ### Insert Subdocuments with python-docx-template Source: https://context7.com/elapouya/python-docx-template/llms.txt Incorporate existing Word documents or programmatically generated sections as subdocuments into a main document using python-docx-template. This method requires the `subdoc` extra during installation (`pip install "docxtpl[subdoc]"`). Subdocuments can be inserted using `new_subdoc()` and rendered via Jinja2 tags like `{{p subdoc_variable}}`. ```python from docxtpl import DocxTemplate # Requires: pip install "docxtpl[subdoc]" doc = DocxTemplate("master_template.docx") # Method 1: Insert existing docx file subdoc1 = doc.new_subdoc("appendix_a.docx") # Method 2: Create subdoc programmatically using python-docx API subdoc2 = doc.new_subdoc() subdoc2.add_heading("Generated Section", level=1) subdoc2.add_paragraph("This is a dynamically created paragraph.") subdoc2.add_paragraph("Another paragraph with some content.") table = subdoc2.add_table(rows=2, cols=2) table.cell(0, 0).text = "Cell 1" table.cell(0, 1).text = "Cell 2" table.cell(1, 0).text = "Cell 3" table.cell(1, 1).text = "Cell 4" context = { 'appendix': subdoc1, 'dynamic_section': subdoc2 } doc.render(context) doc.save("merged_output.docx") # In template use: {{p appendix }} or {{p dynamic_section }} ``` -------------------------------- ### Insert Sub-Document from File Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Embed content from another .docx file as a sub-document within the main template. This requires installing the 'subdoc' extra (`pip install “docxtpl[subdoc]”`). The sub-document is inserted at the location of a template variable (e.g., {{p mysubdoc }}). ```python from docxtpl import DocxTemplate tpl = DocxTemplate('templates/merge_docx_master_tpl.docx') # Get the sub-document object from an existing .docx file sd = tpl.new_subdoc('templates/merge_docx_subdoc.docx') context = { 'mysubdoc': sd, } tpl.render(context) tpl.save('output/merge_docx.docx') ``` -------------------------------- ### Format Text Listings with Special Characters Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Use the `Listing` class to include multi-line text with preserved formatting and handle special characters like newlines (`\n`), paragraph separators (`\a`), and XML characters (`<`, `>`, `&`). Keeps existing character styling unless a new paragraph is started. ```python from docxtpl import DocxTemplate, Listing tpl = DocxTemplate('my_template.docx') # Create a Listing object with text including special characters listing_text = 'This is the first line.\nThis is the second line.\n\nThis is a new paragraph.\aThis starts another paragraph.\aAnd some special chars: <>&' my_listing = Listing(listing_text) context = { 'mylisting': my_listing } tpl.render(context) tpl.save('output_listing.docx') ``` -------------------------------- ### Get Undeclared Template Variables Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md This method retrieves a set of template variables that were not declared or provided during the rendering process. It can be used to identify missing context variables for user prompting or manual processing. Passing the context dictionary is optional but provides more accurate results. ```python tpl=DocxTemplate('your_template.docx') tpl.render(context_dict) set_of_variables = tpl.get_undeclared_template_variables(context=context_dict) ``` -------------------------------- ### Get Undeclared Template Variables Source: https://context7.com/elapouya/python-docx-template/llms.txt Provides a method to retrieve all variables used in a docx template that are not present in the provided context. This is useful for validating templates and ensuring all required data is supplied before rendering. ```python from docxtpl import DocxTemplate doc = DocxTemplate("complex_template.docx") # Get all variables used in template all_vars = doc.get_undeclared_template_variables() print(f"Template requires: {all_vars}") # Output example: {'company_name', 'employee_name', 'salary', 'start_date', 'manager'} # Check missing variables against provided context context = { 'company_name': 'Acme Corp', 'employee_name': 'Jane Smith', 'start_date': '2024-01-15' } missing_vars = doc.get_undeclared_template_variables(context=context) print(f"Missing variables: {missing_vars}") # Output: {'salary', 'manager'} if missing_vars: # Prompt user or raise error for var in missing_vars: context[var] = input(f"Please provide value for {var}: ") doc.render(context) doc.save("output_complete.docx") ``` -------------------------------- ### Run Tests for python-docx-template Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Instructions for running the test suite of the `python-docx-template` library. This involves navigating to the `tests/` directory, executing `runtests.py`, and optionally using `pipenv` for environment management to ensure compatibility. ```bash cd tests/ python runtests.py ``` ```bash 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 ``` -------------------------------- ### Display Help Information Source: https://context7.com/elapouya/python-docx-template/llms.txt This command displays the help message for the python-docx-template command-line interface. It lists available options and provides a brief overview of how to use the tool. ```shell python -m docxtpl -h ``` -------------------------------- ### Basic Template Rendering with docxtpl Source: https://context7.com/elapouya/python-docx-template/llms.txt Loads a Word template, renders it with provided context data, and saves the generated document. Requires the 'docxtpl' library and a .docx template file. Outputs a new .docx file. ```python from docxtpl import DocxTemplate # Load template doc = DocxTemplate("my_template.docx") # Define context variables context = { 'company_name': "Acme Corporation", 'employee_name': "John Doe", 'start_date': "2024-01-15", 'position': "Software Engineer", 'salary': 75000 } # Render template with context doc.render(context) # Save generated document doc.save("generated_contract.docx") ``` -------------------------------- ### Command-line Execution of docxtpl Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Provides the command-line usage for the `docxtpl` module. It outlines the required arguments: template path, JSON data path, and output filename. Optional arguments for overwriting existing files and controlling verbosity are also detailed. ```bash 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 ``` -------------------------------- ### Rich Text Formatting with docxtpl Source: https://context7.com/elapouya/python-docx-template/llms.txt Demonstrates creating and applying rich text formatting, including colors, fonts, bold, italic, underline, hyperlinks, and special text effects, within a Word document template using the 'docxtpl' library. Requires a template with a placeholder for rich content. Outputs a .docx file with formatted text. ```python from docxtpl import DocxTemplate, RichText doc = DocxTemplate("template.docx") # Create rich text with various styling options rt = RichText() rt.add("This is normal text. ") rt.add("This is bold", bold=True) rt.add(" and ") rt.add("this is italic", italic=True) rt.add(" and ") rt.add("this is colored", color="#FF0000") rt.add(" and ") rt.add("highlighted", highlight="#FFFF00") rt.add(".\n") rt.add("Different font sizes: ") rt.add("small", size=14) rt.add(" and ") rt.add("LARGE", size=48) rt.add(".\n") rt.add("Custom fonts: ", font="Arial") rt.add("Courier", font="Courier New") rt.add("\nWith ") rt.add("hyperlink", url_id=doc.build_url_id("https://example.com")) rt.add("\nSpecial formatting: ") rt.add("superscript", superscript=True) rt.add(" and ") rt.add("subscript", subscript=True) rt.add("\nUnderline styles: ") rt.add("single", underline="single") rt.add(", ") rt.add("double", underline="double") rt.add(", ") rt.add("dotted", underline="dotted") context = {'rich_content': rt} doc.render(context) doc.save("output_richtext.docx") # In template use: {{r rich_content }} ``` -------------------------------- ### Jinja2 syntax for displaying variables Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Illustrates how to display variables using double braces {{ variable }}. It also covers special handling for newline characters and RichText objects using {{r variable }} syntax. ```jinja2 {{ myvariable }} {{r myrichtext }} ``` -------------------------------- ### Command-Line Usage with JSON Data Source: https://context7.com/elapouya/python-docx-template/llms.txt This snippet indicates the capability to use the docxtpl library directly from the command line, processing JSON data files for template rendering. The specific command syntax is missing but implies integration with shell environments. ```bash # Execute docxtpl directly from command line using JSON data files. # (Specific command syntax is omitted in the original text) ``` -------------------------------- ### Create JSON Data File Source: https://context7.com/elapouya/python-docx-template/llms.txt This snippet demonstrates how to create a JSON file named 'data.json' which will serve as the context data for generating a Word document. The JSON object contains key-value pairs that can be used to populate placeholders within the Word template. ```shell cat > data.json << EOF { "company_name": "Acme Corporation", "employee_name": "John Doe", "position": "Software Engineer", "salary": 75000, "start_date": "2024-01-15", "benefits": ["Health Insurance", "401k", "Paid Time Off"] } EOF ``` -------------------------------- ### Generate Word Document from Template and JSON Source: https://context7.com/elapouya/python-docx-template/llms.txt This command uses the python-docx-template library to generate a Word document. It takes a template file ('template.docx') and a JSON data file ('data.json') as input and produces an output document ('output.docx'). ```shell python -m docxtpl template.docx data.json output.docx ``` -------------------------------- ### Generate Dynamic Tables with python-docx-template Source: https://context7.com/elapouya/python-docx-template/llms.txt Populate tables in a Word document using dynamic data provided in a Python dictionary. The template uses Jinja2 syntax to iterate over lists and dictionaries to build table rows and cells. Requires the python-docx-template library. ```python from docxtpl import DocxTemplate doc = DocxTemplate("template.docx") context = { 'col_labels': ['Product', 'Q1', 'Q2', 'Q3', 'Q4', 'Total'], 'sales_data': [ {'product': 'Widget A', 'quarters': [1200, 1350, 1400, 1500], 'total': 5450}, {'product': 'Widget B', 'quarters': [800, 950, 900, 1100], 'total': 3750}, {'product': 'Widget C', 'quarters': [1500, 1600, 1550, 1700], 'total': 6350} ], 'employees': [ {'name': 'Alice', 'dept': 'Engineering', 'salary': 85000}, {'name': 'Bob', 'dept': 'Sales', 'salary': 72000}, {'name': 'Charlie', 'dept': 'Marketing', 'salary': 68000} ] } doc.render(context) doc.save("output_tables.docx") # In template, create table structure like: # Header row with: {% for col in col_labels %}{{ col }}{% endfor %} # Data rows with: {%tr for row in sales_data %}{{ row.product }}{% for q in row.quarters %}{{ q }}{% endfor %}{{ row.total }}{%tr endfor %} ``` -------------------------------- ### Inline Image Insertion with docxtpl Source: https://context7.com/elapouya/python-docx-template/llms.txt Dynamically inserts images into a Word document using the 'docxtpl' library. Supports various sizing units (Mm, Inches, Pt) and can be used within loops for dynamic content. Requires image files and a template with image placeholders. Outputs a .docx file with embedded images. ```python from docxtpl import DocxTemplate, InlineImage from docx.shared import Mm, Inches, Pt doc = DocxTemplate("template_with_images.docx") # Create inline images with different sizing methods logo = InlineImage(doc, "company_logo.png", width=Mm(30)) chart = InlineImage(doc, "sales_chart.jpg", width=Inches(4), height=Inches(3)) signature = InlineImage(doc, "signature.png", height=Mm(15)) # Use in loops with dynamic data products = [ { 'name': 'Product A', 'image': InlineImage(doc, 'product_a.png', width=Mm(40)), 'price': '$99.99' }, { 'name': 'Product B', 'image': InlineImage(doc, 'product_b.png', width=Mm(40)), 'price': '$149.99' } ] context = { 'company_logo': logo, 'sales_chart': chart, 'signature': signature, 'products': products } doc.render(context) doc.save("output_with_images.docx") # In template use: {{ company_logo }} for images # In loops: {% for product in products %}{{ product.name }}: {{ product.image }}{% endfor %} ``` -------------------------------- ### Multiple Rendering Sessions with One Template Source: https://context7.com/elapouya/python-docx-template/llms.txt Illustrates how to reuse a single `DocxTemplate` object for generating multiple documents with different contexts. It iterates through a list of employee data, rendering a personalized letter for each and saving it to a unique filename. Crucially, it includes `doc.reset_replacements()` if media/embedded file replacements were used between renders. ```python from docxtpl import DocxTemplate doc = DocxTemplate("employee_letter.docx") employees = [ {'name': 'Alice Johnson', 'dept': 'Engineering', 'salary': 85000, 'bonus': 5000}, {'name': 'Bob Smith', 'dept': 'Sales', 'salary': 72000, 'bonus': 8000}, {'name': 'Charlie Brown', 'dept': 'Marketing', 'salary': 68000, 'bonus': 4000} ] for emp in employees: context = { 'employee_name': emp['name'], 'department': emp['dept'], 'annual_salary': emp['salary'], 'bonus_amount': emp['bonus'], 'total_compensation': emp['salary'] + emp['bonus'] } # Render with current context doc.render(context) # Save to unique filename filename = f"letter_{emp['name'].replace(' ', '_')}.docx" doc.save(filename) # If using replace_media/replace_embedded/replace_zipname, reset between renders doc.reset_replacements() print(f"Generated {len(employees)} personalized letters") ``` -------------------------------- ### Python: Generate Advanced Word Document with Context Source: https://context7.com/elapouya/python-docx-template/llms.txt This Python script demonstrates generating a Word document using advanced template features. It loads a template, defines a complex context dictionary with booleans, lists, and nested dictionaries, renders the template with this context, and saves the output document. ```python from docxtpl import DocxTemplate doc = DocxTemplate("advanced_template.docx") context = { 'show_section': True, 'hide_section': False, 'items': ['Apple', 'Banana', 'Cherry'], 'employees': [ {'name': 'Alice', 'active': True}, {'name': 'Bob', 'active': False}, {'name': 'Charlie', 'active': True} ], 'merge_cells': [ {'category': 'Fruits', 'items': ['Apple', 'Banana']}, {'category': 'Vegetables', 'items': ['Carrot', 'Lettuce', 'Tomato']} ] } doc.render(context) doc.save("output_advanced.docx") ``` -------------------------------- ### Replace Dummy Media in Document Body, Headers, and Footers Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Replace placeholder media (including images) in a Word document with new media files. This method requires the source media files to calculate their CRC for identification within the document. The dummy file must exist in the template directory during rendering. ```python from docxtpl import DocxTemplate tpl = DocxTemplate('template_with_dummy_media.docx') # Replace 'dummy_header_pic.jpg' with 'header_pic_i_want.jpg' # Note: 'dummy_header_pic.jpg' must exist in the template directory tpl.replace_media('dummy_header_pic.jpg', 'header_pic_i_want.jpg') context = {} tpl.render(context) tpl.save('output_media_replaced.docx') ``` -------------------------------- ### Implement Custom Jinja Filters Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Demonstrates how to extend the Jinja environment used by `python-docx-template` to include custom filters. This involves creating a Jinja2 `Environment` object, registering a custom filter function, and passing the environment to the `render()` method. The custom filter can then be used within the template. ```python from docxtpl import DocxTemplate import jinja2 def multiply_by(value, by): return value * by doc = DocxTemplate("my_word_template.docx") context = { 'price_dollars' : 5.00 } jinja_env = jinja2.Environment() jinja_env.filters['multiply_by'] = multiply_by doc.render(context,jinja_env) doc.save("generated_doc.docx") ``` -------------------------------- ### Replace Pictures in Headers/Footers with python-docx-template Source: https://context7.com/elapouya/python-docx-template/llms.txt Programmatically replace placeholder images within Word document templates (including headers and footers) with actual images using python-docx-template. Images can be replaced by specifying the placeholder filename and the replacement image filename, or by providing an image as a file-like object (e.g., `io.BytesIO`). ```python from docxtpl import DocxTemplate doc = DocxTemplate("template_with_dummy_images.docx") # Replace by filename (used when inserting into template) doc.replace_pic('dummy_logo.png', 'actual_company_logo.png') doc.replace_pic('placeholder_chart.jpg', 'real_sales_chart.jpg') # Can also use file-like objects import io with open('signature.png', 'rb') as f: image_data = io.BytesIO(f.read()) doc.replace_pic('dummy_signature.png', image_data) context = {'company': 'Acme Corp'} doc.render(context) doc.save("output_with_replaced_images.docx") # Note: The aspect ratio is preserved from the original dummy image # Insert dummy images in Word template first, then replace them programmatically ``` -------------------------------- ### Overwrite Existing Output Document Source: https://context7.com/elapouya/python-docx-template/llms.txt This command generates a Word document and overwrites the output file ('output.docx') if it already exists, without prompting for confirmation. This is useful for automated workflows where re-generation is intended. ```shell python -m docxtpl -o template.docx data.json output.docx ``` -------------------------------- ### Replace Dummy Image in Document Body, Headers, and Footers Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Replace a placeholder image within a Word document (body, headers, footers) with a new image. The aspect ratio of the original image is maintained. Only the basename of the image file used in the template is required. ```python from docxtpl import DocxTemplate tpl = DocxTemplate('template_with_dummy_image.docx') # Replace 'dummy_header_pic.jpg' with 'header_pic_i_want.jpg' tpl.replace_pic('dummy_header_pic.jpg', 'header_pic_i_want.jpg') context = {} tpl.render(context) tpl.save('output_image_replaced.docx') ``` -------------------------------- ### Escaping Jinja2 Delimiters in Templates Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Provides the syntax for displaying literal Jinja2 delimiters (`{%`, `%}`, `{{`, `}}`) within a docx template. By using `{_%`, `%_}`, `{_{`, or `}_}`, these special characters can be rendered as plain text instead of being interpreted as template tags. ```default {_% , %_}, {_{ or }_} ``` -------------------------------- ### Generate Document in Quiet Mode Source: https://context7.com/elapouya/python-docx-template/llms.txt This command generates a Word document while suppressing informational messages during the process. The '-q' flag enables quiet mode, which is beneficial for cleaner logs in automated systems. ```shell python -m docxtpl -q template.docx data.json output.docx ``` -------------------------------- ### Handle Special Characters and Code Listings with python-docx-template Source: https://context7.com/elapouya/python-docx-template/llms.txt Manage special characters and preserve formatting for code or text containing XML entities using python-docx-template. It supports the `Listing` class for code blocks, manual HTML escaping using `html.escape`, and `RichText` objects which auto-escape content. Auto-escaping can also be enabled for the entire rendering process. ```python from docxtpl import DocxTemplate, Listing from html import escape doc = DocxTemplate("code_template.docx") # Method 1: Using Listing class (handles \n, \a, \f and escapes HTML) code_listing = Listing("""def hello_world(): print(\"Hello, World!\") return True if __name__ == "__main__": hello_world()""") # Method 2: Manual escaping xml_content = escape("Content & more") # Method 3: Using RichText (auto-escapes) from docxtpl import RichText safe_text = RichText("Text with chars & symbols") context = { 'code': code_listing, 'xml_example': xml_content, 'safe_content': safe_text } # Method 4: Enable autoescape for entire rendering doc.render(context, autoescape=True) doc.save("output_escaped.docx") # In template: # For Listing: {{ code }} # For escaped vars: {{ xml_example|e }} or with autoescape=True: {{ xml_example }} # For RichText: {{r safe_content }} ``` -------------------------------- ### Style Table Cells Dynamically with python-docx-template Source: https://context7.com/elapouya/python-docx-template/llms.txt Apply dynamic background colors and column spans to table cells using python-docx-template. The context dictionary provides color codes (e.g., '00FF00') and colspan values. Jinja2 template tags like `cellbg` and `colspan` are used within the document template. ```python from docxtpl import DocxTemplate doc = DocxTemplate("styled_table_template.docx") context = { 'rows': [ {'name': 'Project Alpha', 'status': 'Complete', 'color': '00FF00', 'colspan': 1}, {'name': 'Project Beta', 'status': 'In Progress', 'color': 'FFFF00', 'colspan': 1}, {'name': 'Project Gamma', 'status': 'Not Started', 'color': 'FF0000', 'colspan': 1}, {'name': 'Summary Section', 'status': '', 'color': 'CCCCCC', 'colspan': 2} ] } doc.render(context) doc.save("output_styled_table.docx") # In template for cell background color: {% cellbg row.color %} # In template for column spanning: {% colspan row.colspan %} # Example cell: {%tr for row in rows %}{% cellbg row.color %}{{ row.name }}{% endtr %} ``` -------------------------------- ### Replace Media and Embedded Files in Documents Source: https://context7.com/elapouya/python-docx-template/llms.txt Demonstrates how to replace images, embedded documents, and zipped files within a docx template. It requires the original file to calculate CRC for media replacements. After replacements, the document is rendered with a context and saved. ```python from docxtpl import DocxTemplate doc = DocxTemplate('template.docx') # Replace media files (requires original file for CRC calculation) doc.replace_media('original_header_image.png', 'new_header_image.png') doc.replace_media('original_footer_logo.jpg', 'updated_footer_logo.jpg') # Replace embedded documents doc.replace_embedded('original_embedded.docx', 'updated_embedded.docx') # Replace by zipname (for files MSWord modifies, like embedded spreadsheets) doc.replace_zipname( 'word/embeddings/Excel_Worksheet1.xlsx', 'updated_spreadsheet.xlsx' ) context = {'title': 'Updated Document'} doc.render(context) doc.save("output_replaced_media.docx") # For multiple renderings, reset replacements between renders if needed doc.reset_replacements() ``` -------------------------------- ### Add Custom Jinja2 Filters for Templating Source: https://context7.com/elapouya/python-docx-template/llms.txt Shows how to define and register custom Jinja2 filters to extend the templating capabilities of docxtpl. These filters can perform operations like multiplication, currency formatting, and text transformation within the template. ```python from docxtpl import DocxTemplate import jinja2 def multiply_by(value, multiplier): """Custom filter to multiply values""" return value * multiplier def format_currency(value, symbol='$'): """Format number as currency""" return f"{symbol}{value:,.2f}" def uppercase(text): """Convert text to uppercase""" return str(text).upper() doc = DocxTemplate("template_with_filters.docx") # Create Jinja2 environment and register filters jinja_env = jinja2.Environment() jinja_env.filters['multiply_by'] = multiply_by jinja_env.filters['currency'] = format_currency jinja_env.filters['caps'] = uppercase context = { 'base_price': 99.99, 'quantity': 5, 'tax_rate': 0.08, 'customer_name': 'john doe' } doc.render(context, jinja_env) doc.save("output_with_filters.docx") # In template use: # Price per item: {{ base_price|currency }} # Total: {{ base_price|multiply_by(quantity)|currency }} # Customer: {{ customer_name|caps }} ``` -------------------------------- ### Using RichText for Dynamic Styling Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Demonstrates the use of `RichText` (or `R()`) objects in Python to dynamically apply styles like color, bold, italics, font, and size to text within a docx template. It supports special characters for newlines (`\n`), paragraphs (`\a`), tabs (`\t`), and page breaks (`\f`). ```python from docxtpl import RichText # Example of setting font for a specific region ch = RichText('测试TEST', font='eastAsia:微软雅黑') # Using RichText to add a hyperlink tpl = DocxTemplate('your_template.docx') rt = RichText('You can add an hyperlink, here to ') rt.add('google', url_id=tpl.build_url_id('http://google.com')) context = {'my_text': rt} ``` -------------------------------- ### Document Properties Templating with Jinja2 Source: https://context7.com/elapouya/python-docx-template/llms.txt Explains how to use Jinja2 variables within the document's metadata properties (like Title, Author, Subject) which are set in Word's File -> Info section. These properties are automatically rendered during the `doc.render()` process. ```python from docxtpl import DocxTemplate import jinja2 doc = DocxTemplate("template.docx") # Document properties can contain Jinja2 variables # Set in Word: File -> Info -> Properties # Before rendering, set template strings in properties like: # Title: "{{ report_type }} - {{ year }}" # Author: "{{ author_name }}" # Subject: "{{ department }} Report" context = { 'report_type': 'Quarterly Sales Report', 'year': 2024, 'author_name': 'Financial Department', 'department': 'Sales', 'quarter': 'Q1' } jinja_env = jinja2.Environment() doc.render(context, jinja_env) doc.save("output_with_properties.docx") # Properties are automatically rendered during doc.render() # Rendered properties: Title="Quarterly Sales Report - 2024", Author="Financial Department" ``` -------------------------------- ### Splitting and Merging Text with Jinja2 Tags Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Shows how to manage text flow across multiple lines in docx templates using Jinja2 tags. The `{%-` and `-%}` tags allow merging text with preceding or succeeding lines, respectively, aiding in the readability of long text blocks containing conditional logic. ```default My house is located {% if living_in_town %} in urban area {% else %} in countryside {% endif %} and I love it. ``` ```default My house is located {%- if living_in_town -%} in urban area {%- else -%} in countryside {%- endif -%} and I love it. ``` -------------------------------- ### Jinja2-like tags for document structure control Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Demonstrates special Jinja2 tags like {%p%}, {%tr%}, {%tc%}, and {%r%} used to control paragraphs, table rows, table columns, and runs within the Word document template. These tags also handle conditional display and removal of elements. ```jinja2 {%p if display_paragraph %} One or many paragraphs {%p endif %} ``` -------------------------------- ### Setting Table Cell Background Color Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Explains how to set the background color of a table cell using the `{% cellbg %}` tag. The `` must be a hexadecimal color code without the leading hash symbol. ```default {% cellbg %} ``` -------------------------------- ### Add Inline Image to Document Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Dynamically add JPEG or PNG images into a document using a template tag and the InlineImage class. Requires specifying the template object, image file path, and optionally dimensions (width, height) using Mm, Inches, or Pt units. ```python from docxtpl import DocxTemplate, InlineImage from docxtpl.units import Mm tpl = DocxTemplate('my_template.docx') # Create an InlineImage object myimage = InlineImage(tpl, image_descriptor='path/to/your/image.png', width=Mm(20), height=Mm(10)) context = { 'my_image_variable': myimage } tpl.render(context) tpl.save('output_with_image.docx') ``` -------------------------------- ### Handle Special Characters with RichText Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Addresses issues with Microsoft Word 2016 ignoring tabulations and leading spaces in Jinja2 tags. The solution involves using the `RichText` object to preserve these formatting elements. These `RichText` objects are then rendered using the `{{r ...}}` notation in the template. ```python tpl.render({ 'test_space_r' : RichText(' '), 'test_tabs_r': RichText(5*' '), }) ``` -------------------------------- ### Table Cell Spanning with colspan, hm, and vm Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Illustrates methods for spanning table cells in docx templates. `colspan ` spans cells horizontally, `{% hm %}` merges cells horizontally within a loop, and `{% vm %}` merges cells vertically within a loop. Requires integer for colspan. ```default {% colspan %} ``` ```default {% hm %} ``` ```default {% vm %} ``` -------------------------------- ### RichText Paragraph Formatting Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Introduces `RichTextParagraph` (or `RP()`) for modifying paragraph properties. These objects are added to the template using the `{{p }}` tag, allowing for dynamic control over paragraph-level formatting. ```default {{p }} ``` -------------------------------- ### Replace Media by CRC with python-docx-template Source: https://context7.com/elapouya/python-docx-template/llms.txt Replace media files, such as images or embedded objects, within a Word document by matching their CRC checksum using the python-docx-template library. This method allows for replacing specific media instances without needing to know their exact name in the template. ```python from docxtpl import DocxTemplate doc = DocxTemplate("template.docx") ``` -------------------------------- ### Jinja2 Comments in docx-template Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Demonstrates how to insert Jinja2-like comments within docx templates to add annotations without affecting the final document. These comments can be designated for specific elements like paragraphs, table rows, or table cells. ```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 #} ``` -------------------------------- ### Replace Embedded Objects in Docx Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md This function allows for the replacement of embedded objects within a .docx template, such as other .docx files. It requires the original embedded file to exist in the template directory. For objects not directly supported (e.g., Excel, PowerPoint), it suggests using `replace_zipname` with the correct internal zip path. ```python tpl.replace_embedded('embedded_dummy.docx','embedded_docx_i_want.docx') ``` ```python tpl.replace_zipname( 'word/embeddings/Feuille_Microsoft_Office_Excel1.xlsx', 'my_excel_file.xlsx' ) ``` -------------------------------- ### Escape Special XML Characters for Template Variables Source: https://github.com/elapouya/python-docx-template/blob/master/docs/index.md Handle special XML characters (<, >, &) within template variables to prevent document generation errors. Offers multiple methods: using the `R` object, the `|e` filter in the template, the `escape()` function, or enabling autoescaping during rendering. ```python from docxtpl import DocxTemplate, R from xml.sax.saxutils import escape tpl = DocxTemplate('my_template.docx') # Method 1: Using R object (use {{r var}} in template) context_r = { 'var': R('my text with <, >, &') } # Method 2: Using |e filter (use {{var|e}} in template) context_filter = { 'var': 'my text with <, >, &' } # Method 3: Using escape() function (use {{var}} in template) context_escape = { 'var': escape('my text with <, >, &') } # Method 4: Enable autoescape during render (use {{var}} in template) # tpl.render(context, autoescape=True) # Example rendering with one context: tpl.render(context_filter) # Assuming {{var|e}} is used in template tpl.save('output_escaped.docx') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.