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.
- <repositories>
- <repository>
- <id>com.e-iceblue</id>
- <name>e-iceblue</name>
- <url>http:
- </repository>
- </repositories>
- <dependencies>
- <dependency>
- <groupId> e-iceblue </groupId>
- <artifactId>spire.doc.free</artifactId>
- <version>3.9.0</version>
- </dependency>
- </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,
- import com.spire.doc.*;
- import com.spire.doc.documents.Paragraph;
- import com.spire.doc.documents.TextSelection;
- import com.spire.doc.fields.DocPicture;
- import com.spire.doc.fields.TextRange;
- import java.util.HashMap;
- import java.util.Map;
-
- public class CreateByReplacingPlaceholderText {
- public static void main(String []args){
-
- Document document = new Document("PlaceholderTextTemplate.docx");
-
- Section section = document.getSections().get(0);
-
- Table table = section.getTables().get(0);
-
-
- Map<String, String> map = new HashMap<String, String>();
- map.put("firstName","Alex");
- map.put("lastName","Anderson");
- map.put("gender","Male");
- map.put("mobilePhone","+0044 85430000");
- map.put("email","[email protected]");
- map.put("homeAddress","123 High Street");
- map.put("dateOfBirth","6th June, 1986");
- map.put("education","University of South Florida, September 2013 - June 2017");
- map.put("employmentHistory","Automation Inc. November 2013 - Present");
-
-
- replaceTextinTable(map, table);
-
- replaceTextWithImage(document, "photo", "Avatar.jpg");
-
-
- document.saveToFile("CreateByReplacingPlaceholder.docx", FileFormat.Docx_2013);
- }
-
-
- static void replaceTextinTable(Map<String, String> map, Table table){
- for(TableRow row:(Iterable<TableRow>)table.getRows()){
- for(TableCell cell : (Iterable<TableCell>)row.getCells()){
- for(Paragraph para : (Iterable<Paragraph>)cell.getParagraphs()){
- for (Map.Entry<String, String> entry : map.entrySet()) {
- para.replace("${" + entry.getKey() + "}", entry.getValue(), false, true);
- }
- }
- }
- }
- }
-
-
- static void replaceTextWithImage(Document document, String stringToReplace, String imagePath){
- TextSelection[] selections = document.findAllString("${" + stringToReplace + "}", false, true);
- int index = 0;
- TextRange range = null;
- for (Object obj : selections) {
- TextSelection textSelection = (TextSelection)obj;
- DocPicture pic = new DocPicture(document);
- pic.loadImage(imagePath);
- range = textSelection.getAsOneRange();
- index = range.getOwnerParagraph().getChildObjects().indexOf(range);
- range.getOwnerParagraph().getChildObjects().insert(index,pic);
- range.getOwnerParagraph().getChildObjects().remove(range);
- }
- }
-
-
- static void replaceTextinDocumentBody(Map<String, String> map, Document document){
- for(Section section : (Iterable<Section>)document.getSections()) {
- for (Paragraph para : (Iterable<Paragraph>) section.getParagraphs()) {
- for (Map.Entry<String, String> entry : map.entrySet()) {
- para.replace("${" + entry.getKey() + "}", entry.getValue(), false, true);
- }
- }
- }
- }
-
-
- static void replaceTextinHeaderorFooter(Map<String, String> map, HeaderFooter headerFooter){
- for(Paragraph para : (Iterable<Paragraph>)headerFooter.getParagraphs()){
- for (Map.Entry<String, String> entry : map.entrySet()) {
- para.replace("${" + entry.getKey() + "}", entry.getValue(), false, true);
- }
- }
- }
- }
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,
- import com.spire.doc.*;
- import com.spire.doc.documents.*;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.util.HashMap;
- import java.util.Map;
-
- public class CreateByReplacingBookmarks {
- public static void main(String []args) throws Exception {
-
- Document doc = new Document("BookmarkTemplate.docx");
-
-
- Map<String, String> map = new HashMap<String, String>();
- map.put("firstName","Alex");
- map.put("lastName","Anderson");
- map.put("gender","Male");
- map.put("mobilePhone","+0044 85430000");
- map.put("email","[email protected]");
- map.put("homeAddress","123 High Street");
- map.put("dateOfBirth","6th June, 1986");
- map.put("education","University of South Florida, September 2013 - June 2017");
- map.put("employmentHistory","Automation Inc. November 2013 - Present");
-
-
- for (Map.Entry<String, String> entry : map.entrySet()) {
-
- BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
- bookmarkNavigator.moveToBookmark(entry.getKey());
- bookmarkNavigator.replaceBookmarkContent(entry.getValue(), true);
- }
-
-
-
- BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
- bookmarkNavigator.moveToBookmark("photo");
- Paragraph para = new Paragraph(doc);
- InputStream inputStream = new FileInputStream("Avatar.jpg");
- para.appendPicture(inputStream);
- bookmarkNavigator.insertParagraph(para);
-
-
- doc.saveToFile("CreateByReplacingBookmarks.docx", FileFormat.Docx_2013);
- }
- }
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,
- import com.spire.doc.Document;
- import com.spire.doc.FileFormat;
- import com.spire.doc.reporting.MergeImageFieldEventArgs;
- import com.spire.doc.reporting.MergeImageFieldEventHandler;
-
- public class CreateByMailMerge {
- public static void main(String []args) throws Exception {
-
- Document document = new Document("MailmergeTemplate.docx");
-
-
- String[] filedNames = new String[]{"firstName","lastName", "gender", "mobilePhone", "email", "homeAddress", "dateOfBirth", "education", "employmentHistory", "image"};
- 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"};
-
- document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
- @Override
- public void invoke(Object sender, MergeImageFieldEventArgs args) {
- mailMerge_MergeImageField(sender, args);
- }
- };
-
- document.getMailMerge().execute(filedNames, filedValues);
-
-
- document.saveToFile("CreateByMailMerge.docx", FileFormat.Docx_2013);
- }
- private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) {
- String filePath = field.getImageFileName();
- if (filePath != null && !"".equals(filePath)) {
- try {
- field.setImage(filePath);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
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 in the
documentation. Happy coding!