Load Template Documents from File or Stream
Leave feedback
Overview
GroupDocs.Assembly for Java supports loading template documents from both file paths and streams. This flexibility allows you to work with templates stored on disk, in memory, or retrieved from remote sources.
The main class involved is:
DocumentAssembler - provides overloads for both file paths and streams
Here are the steps to load and use templates:
Load template from a file path using a String path parameter
Load template from a stream using an InputStream parameter
Choose the appropriate method based on your use case (file system vs memory/remote)
Save assembled document to a file path or an OutputStream accordingly
Note
When using streams, ensure proper closing of stream resources. The DocumentAssembler does not close the input and output streams passed to it, so you should manage the stream lifecycle yourself (for example, with try-with-resources).
Load Template from File Path
The simplest way to load a template is from a file path:
importcom.groupdocs.assembly.*;publicstaticvoidloadTemplateFromFile()throwsException{// Template and output file paths
StringtemplatePath="C:\\Templates\\InvoiceTemplate.docx";StringoutputPath="C:\\Output\\Invoice.docx";// Sample data
InvoiceDatainvoiceData=newInvoiceData("ABC Corp",1500.00);// Assemble document from file path
DocumentAssemblerassembler=newDocumentAssembler();assembler.assembleDocument(templatePath,outputPath,newDataSourceInfo(invoiceData,"invoice"));System.out.println("Document assembled successfully.");}// POJO for the data source
publicclassInvoiceData{privatefinalStringcustomerName;privatefinaldoubleamount;publicInvoiceData(StringcustomerName,doubleamount){this.customerName=customerName;this.amount=amount;}publicStringgetCustomerName(){returncustomerName;}publicdoublegetAmount(){returnamount;}}
Load Template from Stream
When working with templates in memory or from remote sources, use streams:
importcom.groupdocs.assembly.*;importjava.io.*;importjava.nio.file.*;importjava.util.Date;publicstaticvoidloadTemplateFromStream()throwsException{// Load template into memory stream
byte[]templateBytes=Files.readAllBytes(Paths.get("Template.docx"));try(InputStreamtemplateStream=newByteArrayInputStream(templateBytes);// Create output stream
OutputStreamoutputStream=newFileOutputStream("Output.docx")){ReportDatadata=newReportData("Report",newDate());DocumentAssemblerassembler=newDocumentAssembler();assembler.assembleDocument(templateStream,outputStream,newDataSourceInfo(data,"report"));System.out.println("Document assembled from stream successfully.");}}// POJO for the data source
publicclassReportData{privatefinalStringtitle;privatefinalDatedate;publicReportData(Stringtitle,Datedate){this.title=title;this.date=date;}publicStringgetTitle(){returntitle;}publicDategetDate(){returndate;}}
Load Template from Remote Source
You can load templates from URLs or remote sources:
importcom.groupdocs.assembly.*;importjava.io.*;importjava.net.URI;publicstaticvoidloadTemplateFromRemote()throwsException{// Download template from remote URL
try(InputStreamtemplateStream=URI.create("https://example.com/templates/ReportTemplate.docx").toURL().openStream();OutputStreamoutputStream=newFileOutputStream("Output.docx")){CompanyDatadata=newCompanyData("My Company",2024);DocumentAssemblerassembler=newDocumentAssembler();assembler.assembleDocument(templateStream,outputStream,newDataSourceInfo(data,"company"));System.out.println("Document assembled from remote template.");}}// POJO for the data source
publicclassCompanyData{privatefinalStringcompany;privatefinalintyear;publicCompanyData(Stringcompany,intyear){this.company=company;this.year=year;}publicStringgetCompany(){returncompany;}publicintgetYear(){returnyear;}}
Mixed File Path and Stream Usage
You can mix files and streams as needed. DocumentAssembler accepts either two paths or two streams, so open the template file as a stream when the output should go to a stream:
importcom.groupdocs.assembly.*;importjava.io.*;importjava.nio.file.*;publicstaticvoidmixedFileAndStream()throwsException{// Load template from file path
StringtemplatePath="Template.docx";// Save output to stream
try(InputStreamtemplateStream=newFileInputStream(templatePath);ByteArrayOutputStreamoutputStream=newByteArrayOutputStream()){ItemDatadata=newItemData("Test",100);DocumentAssemblerassembler=newDocumentAssembler();assembler.assembleDocument(templateStream,outputStream,newDataSourceInfo(data,"item"));// Use the output stream (e.g., send via HTTP, save to database)
byte[]outputBytes=outputStream.toByteArray();Files.write(Paths.get("Output.docx"),outputBytes);System.out.println("Document assembled with mixed file/stream usage.");}}// POJO for the data source
publicclassItemData{privatefinalStringname;privatefinalintvalue;publicItemData(Stringname,intvalue){this.name=name;this.value=value;}publicStringgetName(){returnname;}publicintgetValue(){returnvalue;}}
Warning
When using streams for output, read the assembled content (for example, via ByteArrayOutputStream.toByteArray()) only after assembleDocument returns. The output stream is neither closed nor reset by the assembler, so close it yourself when you are done.
Advanced Usage Topics
To learn more about working with different template formats, custom document loading, and advanced stream handling, 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: