talira

Use a docx as a jinja2 template

open sourceLGPL-2.1-onlyself-hostablefree

docxtpl (python-docx-template) is a Python library that renders a Word document you design in Word as a Jinja2 template, using python-docx to read and write it. Besides {{ }} and {% %} tags it has paragraph, table row, table column and run forms ({%p %}, {%tr %}, {%tc %}, {%r %}) so loops and conditions can repeat or remove whole rows and paragraphs, plus RichText, inline images, subdocuments, merged cells and replacing pictures or embedded files in headers and footers. It's LGPL-2.1 and can also render from the command line (python -m docxtpl).

Problems it solves

  • write Word templates with Jinja2 syntax and fill them from a Python dict
  • repeat a table row in a .docx for each item in a Python list
  • add a table column per month in a generated Word report from Python
  • insert a chart PNG at a fixed size into a Word document generated by a Django app
  • swap the logo picture in a Word template's header for each client
  • merge another .docx into a generated document as a subdocument
  • find which variables a Word template still needs before rendering it
  • colour table cells and merge them dynamically in a Word report from Python

Features

  • Jinja2 tags, filters and variables inside a Word document
  • {%p %}, {%tr %}, {%tc %} and {%r %} tags for paragraphs, table rows, table columns and runs
  • RichText and RichTextParagraph for styled text and hyperlinks
  • InlineImage (JPEG, PNG) with sizes in mm, inches or points
  • subdocuments, including merging existing .docx files
  • replace pictures, media and embedded objects, including in headers and footers
  • table helpers: colspan, horizontal and vertical merge, cell background
  • get_undeclared_template_variables()
  • custom Jinja2 environments and filters
  • command line: python -m docxtpl renders a template from JSON

Limitations

  • Doesn't let a Jinja2 tag span several paragraphs, table rows or runs: loops and conditions over them use the {%p %}, {%tr %}, {%tc %} and {%r %} forms1

Capabilities

Has a command line toolplan not known

Alternatives

The same job

These do what docxtpl does.

  1. Sablon Ruby document template processor based on docx templates and Mail Merge fields
  2. docxtemplater Powerful Word, PowerPoint and Excel generation
  3. docx-templates Template-based docx report creation for both Node and the browser
  4. Carbone Generates PDF, DOCX and other documents from JSON data and Office templates
  5. docx4j JAXB-based Java library for Word docx, Powerpoint pptx, and Excel xlsx files
  6. Docmosis API-first, template-based document generation

Compare docxtpl with the top 3