Generate Your First Document from Java Object
Leave feedback
Overview
This guide walks you through creating your first document with GroupDocs.Assembly for Java. You’ll generate a simple document from an in-memory Java object, demonstrating the basic workflow of template-based document assembly.
The data class must be public. Otherwise, the engine rejects it as a data source with the “A data source object must be of a visible type” error.
Generate Document from Object
Now, create a method to generate a document from this object:
importcom.groupdocs.assembly.*;publicstaticvoidgenerateFirstDocument()throwsException{// Create sample data
Personperson=newPerson();person.setName("John Doe");person.setAge(30);person.setEmail("john.doe@example.com");// Paths for template and output
StringtemplatePath="Template.docx";StringoutputPath="Output.docx";// Assemble the document
DocumentAssemblerassembler=newDocumentAssembler();assembler.assembleDocument(templatePath,outputPath,newDataSourceInfo(person,"person"));System.out.println("Document generated successfully: "+outputPath);}
Template Document Example
Your template document (Template.docx) should contain expression tags like this:
Name: John Doe
Age: 30
Email: john.doe@example.com
Note
Members of Java objects are accessed in templates by calling their public methods, such as getters (person.getName()). A property-like reference such as person.Name does not work for Java objects.
Using Contextual Object Member Access
You can also use contextual member access, which allows you to omit the data source name in simple scenarios:
publicstaticvoidgenerateDocumentWithContextualAccess()throwsException{Personperson=newPerson();person.setName("Jane Smith");person.setAge(28);person.setEmail("jane.smith@example.com");DocumentAssemblerassembler=newDocumentAssembler();// When using contextual access, you can omit the data source name
assembler.assembleDocument("Template.docx","Output.docx",newDataSourceInfo(person));}
When using contextual object member access, the template expressions can call the object’s methods directly without the data source name prefix. This is useful for simple, single-object scenarios.
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: