Skip to main content

3 Ways to Generate Word Documents from Templates in Java


A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library.

Prerequisite

First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that.

If you use maven, you need to add the following code to your project’s pom.xml file.

  1. <repositories>   
  2.   
  3.         <repository>   
  4.   
  5.             <id>com.e-iceblue</id>   
  6.   
  7.             <name>e-iceblue</name>   
  8.   
  9.             <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>   
  10.   
  11.         </repository>   
  12.   
  13. </repositories>   
  14.   
  15. <dependencies>   
  16.   
  17.     <dependency>   
  18.   
  19.         <groupId>e-iceblue</groupId>   
  20.   
  21.         <artifactId>spire.doc.free</artifactId>   
  22.   
  23.         <version>3.9.0</version>   
  24.   
  25.     </dependency>   
  26.   
  27. </dependencies>

For non-maven projects, download Free Spire.Doc for Java pack from this website and add Spire.Doc.jar in the lib folder into your project as a dependency.

Implementation

There are several ways to generate Word documents from templates using Free Spire.Doc for Java, they are:

  •  Generate Word document by replacing placeholder text
  • Generate Word document by replacing bookmarks
  • Generate Word document by using mail merge 

Generate Word document by replacing placeholder text

In the following code, you can see the methods to replace placeholder text in table, header/footer and in document body. Furthermore, you can also find the method to replace placeholder text with image.

The template document:


  1. import com.spire.doc.*;  
  2. import com.spire.doc.documents.Paragraph;  
  3. import com.spire.doc.documents.TextSelection;  
  4. import com.spire.doc.fields.DocPicture;  
  5. import com.spire.doc.fields.TextRange;  
  6.   
  7. import java.util.HashMap;  
  8. import java.util.Map;  
  9.   
  10. public class CreateByReplacingPlaceholderText {  
  11.     public static void main(String []args){  
  12.         //Load the template document  
  13.         Document document = new Document("PlaceholderTextTemplate.docx");  
  14.         //Get the first section  
  15.         Section section = document.getSections().get(0);  
  16.         //Get the first table in the section  
  17.         Table table = section.getTables().get(0);  
  18.   
  19.         //Create a map of values for the template  
  20.         Map<String, String> map = new HashMap<String, String>();  
  21.         map.put("firstName","Alex");  
  22.         map.put("lastName","Anderson");  
  23.         map.put("gender","Male");  
  24.         map.put("mobilePhone","+0044 85430000");  
  25.         map.put("email","alex.anderson@myemail.com");  
  26.         map.put("homeAddress","123 High Street");  
  27.         map.put("dateOfBirth","6th June, 1986");  
  28.         map.put("education","University of South Florida, September 2013 - June 2017");  
  29.         map.put("employmentHistory","Automation Inc. November 2013 - Present");  
  30.   
  31.         //Call the replaceTextinTable method to replace text in table  
  32.         replaceTextinTable(map, table);  
  33.         // Call the replaceTextWithImage method to replace text with image  
  34.         replaceTextWithImage(document, "photo""Avatar.jpg");  
  35.   
  36.         //Save the result document  
  37.         document.saveToFile("CreateByReplacingPlaceholder.docx", FileFormat.Docx_2013);  
  38.     }  
  39.   
  40.     //Replace text in table  
  41.     static void replaceTextinTable(Map<String, String> map, Table table){  
  42.         for(TableRow row:(Iterable<TableRow>)table.getRows()){  
  43.             for(TableCell cell : (Iterable<TableCell>)row.getCells()){  
  44.                 for(Paragraph para : (Iterable<Paragraph>)cell.getParagraphs()){  
  45.                     for (Map.Entry<String, String> entry : map.entrySet()) {  
  46.                         para.replace("${" + entry.getKey() + "}", entry.getValue(), falsetrue);  
  47.                     }  
  48.                 }  
  49.             }  
  50.         }  
  51.     }  
  52.   
  53.     //Replace text with image  
  54.     static  void replaceTextWithImage(Document document, String stringToReplace, String imagePath){  
  55.         TextSelection[] selections = document.findAllString("${" + stringToReplace + "}"falsetrue);  
  56.         int index = 0;  
  57.         TextRange range = null;  
  58.         for (Object obj : selections) {  
  59.             TextSelection textSelection = (TextSelection)obj;  
  60.             DocPicture pic = new DocPicture(document);  
  61.             pic.loadImage(imagePath);  
  62.             range = textSelection.getAsOneRange();  
  63.             index = range.getOwnerParagraph().getChildObjects().indexOf(range);  
  64.             range.getOwnerParagraph().getChildObjects().insert(index,pic);  
  65.             range.getOwnerParagraph().getChildObjects().remove(range);  
  66.         }  
  67.     }  
  68.   
  69.     //Replace text in document body  
  70.     static void replaceTextinDocumentBody(Map<String, String> map, Document document){  
  71.         for(Section section : (Iterable<Section>)document.getSections()) {  
  72.             for (Paragraph para : (Iterable<Paragraph>) section.getParagraphs()) {  
  73.                 for (Map.Entry<String, String> entry : map.entrySet()) {  
  74.                     para.replace("${" + entry.getKey() + "}", entry.getValue(), falsetrue);  
  75.                 }  
  76.             }  
  77.         }  
  78.     }  
  79.   
  80.     //Replace text in header or footer  
  81.     static  void replaceTextinHeaderorFooter(Map<String, String> map, HeaderFooter headerFooter){  
  82.         for(Paragraph para : (Iterable<Paragraph>)headerFooter.getParagraphs()){  
  83.             for (Map.Entry<String, String> entry : map.entrySet()) {  
  84.                 para.replace("${" + entry.getKey() + "}", entry.getValue(), falsetrue);  
  85.             }  
  86.         }  
  87.     }  
  88. }

The result document:


Generate Word document by replacing bookmarks

The BookmarksNavigator class is used to locate bookmarks and replace bookmark content in a document. The following code shows how to replace bookmark content with text and image.

The template document:


  1. import com.spire.doc.*;  
  2. import com.spire.doc.documents.*;  
  3.   
  4. import java.io.FileInputStream;  
  5. import java.io.InputStream;  
  6. import java.util.HashMap;  
  7. import java.util.Map;  
  8.   
  9. public class CreateByReplacingBookmarks {  
  10.     public static void main(String []args) throws Exception {  
  11.         //Load the template document  
  12.         Document doc = new Document("BookmarkTemplate.docx");  
  13.   
  14.         //Create a map of values for the template  
  15.         Map<String, String> map = new HashMap<String, String>();  
  16.         map.put("firstName","Alex");  
  17.         map.put("lastName","Anderson");  
  18.         map.put("gender","Male");  
  19.         map.put("mobilePhone","+0044 85430000");  
  20.         map.put("email","alex.anderson@myemail.com");  
  21.         map.put("homeAddress","123 High Street");  
  22.         map.put("dateOfBirth","6th June, 1986");  
  23.         map.put("education","University of South Florida, September 2013 - June 2017");  
  24.         map.put("employmentHistory","Automation Inc. November 2013 - Present");  
  25.   
  26.         //Replace bookmark content with text  
  27.         for (Map.Entry<String, String> entry : map.entrySet()) {  
  28.             //Locate the bookmark  
  29.             BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);  
  30.             bookmarkNavigator.moveToBookmark(entry.getKey());  
  31.             bookmarkNavigator.replaceBookmarkContent(entry.getValue(), true);  
  32.         }  
  33.   
  34.         //Replace bookmark content with image  
  35.         //Locate the bookmark  
  36.         BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);  
  37.         bookmarkNavigator.moveToBookmark("photo");  
  38.         Paragraph para = new Paragraph(doc);  
  39.         InputStream inputStream = new FileInputStream("Avatar.jpg");  
  40.         para.appendPicture(inputStream);  
  41.         bookmarkNavigator.insertParagraph(para);  
  42.   
  43.         //Save the result document  
  44.         doc.saveToFile("CreateByReplacingBookmarks.docx", FileFormat.Docx_2013);  
  45.     }  
  46. }   

The result document:


Generate Word document by using mail merge

You can use the execute method in MailMerge class to mail merge text and image into a template document as shown in the below example.

The template document:


  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FileFormat;  
  3. import com.spire.doc.reporting.MergeImageFieldEventArgs;  
  4. import com.spire.doc.reporting.MergeImageFieldEventHandler;  
  5.   
  6. public class CreateByMailMerge {  
  7.     public static void main(String []args) throws Exception {  
  8.         //Load the template document  
  9.         Document document = new Document("MailmergeTemplate.docx");  
  10.   
  11.         //Create two arrays of values for the template  
  12.         String[] filedNames = new String[]{"firstName","lastName""gender""mobilePhone""email""homeAddress""dateOfBirth""education""employmentHistory""image"};  
  13.         String[] filedValues = new String[]{"Alex","Anderson""male""+0044 85430000""alex.anderson@myemail.com""123 High Street""6th June, 1986""University of South Florida, September 2013 - June 2017""Automation Inc. November 2013 - Present""Avatar.jpg"};  
  14.   
  15.         document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {  
  16.             @Override  
  17.             public void invoke(Object sender, MergeImageFieldEventArgs args) {  
  18.                 mailMerge_MergeImageField(sender, args);  
  19.             }  
  20.         };  
  21.         //Call execute method to merge image and string values to the document  
  22.         document.getMailMerge().execute(filedNames, filedValues);  
  23.   
  24.         //Save the result document  
  25.         document.saveToFile("CreateByMailMerge.docx", FileFormat.Docx_2013);  
  26.     }  
  27.     private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) {  
  28.         String filePath = field.getImageFileName();  
  29.         if (filePath != null && !"".equals(filePath)) {  
  30.             try {  
  31.                 field.setImage(filePath);  
  32.             } catch (Exception e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.         }  
  36.     }  

The result document:


Conclusion

Thank you for taking time to read this article. I hope it clarified how to generate Word documents from templates using Free Spire.Doc for Java library. The library also can be utilized to manipulate, convert and print Word documents, you can take a moment to explore more about it by the documentation. Happy coding!

Comments

Popular posts from this blog

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();         workbook.loadFromFile( "Sample.xlsx" );         //Fit to page         workbook.getConverterSetting().setShee

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>                   <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>               </repository>       </repositories>       <dependencies>           <dependency>               <groupId>