Generate Your First Document from a Python Dict
Leave feedback
Overview
This guide walks you through creating your first document with GroupDocs.Assembly for Python via .NET. You’ll generate a simple document from an in-memory Python dict, demonstrating the basic workflow of template-based document assembly.
DataSourceInfo - wraps data source objects with optional names
Here are the steps to generate your first document:
Describe your data as a Python dict whose keys are the names the template reads
Populate the dict with sample data
Create a template document (DOCX) with expression tags referencing the dict’s keys
Use DocumentAssembler to assemble the template with your data
Save the assembled document to a file
Describe the Data as a Dict
In Python you do not declare a class for the data. A dict is enough: each key becomes a member the template can read, and the value’s Python type decides what the template sees (str, int, float, decimal.Decimal, bool, datetime, nested dicts and lists).
Now, pass the dict to the assembler together with the name the template uses for it:
fromgroupdocs.assemblyimportDataSourceInfo,DocumentAssembler# Create sample dataperson={"Name":"Amara Osei","Age":41,"Email":"amara.osei@harborlane.example",}# Paths for template and outputtemplate_path="person-card.docx"output_path="person-card-report.docx"# Assemble the documentassembler=DocumentAssembler()assembler.assemble_document(template_path,output_path,DataSourceInfo(person,"person"))print("Document generated successfully:",output_path)
The following sample file is used in this example: person-card.docx
You can also use contextual member access, which allows you to omit the data source name in simple scenarios:
fromgroupdocs.assemblyimportDataSourceInfo,DocumentAssemblerperson={"Name":"Lena Park","Age":29,"Email":"lena.park@harborlane.example",}assembler=DocumentAssembler()# When using contextual access, you can omit the data source nameassembler.assemble_document("person-card-contextual.docx","person-card-contextual-report.docx",DataSourceInfo(person))
When using contextual object member access, the template expressions can reference the dict’s keys directly without the data source name prefix. This is useful for simple, single-object scenarios. A template that still names the source (<<[person.Name]>>) fails when the source has no name: the engine looks for a person key in the dict.
Advanced Usage Topics
To learn more about working with complex data structures, multiple data sources, and advanced template syntax, please refer to the advanced usage section.
More resources
GitHub Examples
You may easily run the code above and see the feature in action in our GitHub examples: