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

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

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,
 
3 Ways To Generate Word Documents From Templates In Java 
  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""[email protected]""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.     }  
  37. }  
The result document,
 
3 Ways To Generate Word Documents From Templates In Java 
 

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 in the documentation. Happy coding!


Similar Articles