Java implementation uses FreeMarker to perfectly export word documents (with pictures)
preface
Recently, in the project, due to the customer's requirements, the page content (such as contract agreement) was exported into word, which turned a lot on the Internet. It felt too messy, but in the end, this problem was better solved.
Preparation of materials
1. Original word 2 Editor (firstobject free XML editor is recommended)
Implementation steps
1. Open the original word with Microsoft office word;
2. Replace the content that needs to be dynamically modified with * * *. If there are pictures, try to select small pictures with tens of K or so, and adjust the position;
3. Save as, select the save type word 2003 XML document (*. XML) [here's why you open it with Microsoft office word and want to save it as word 2003xml. Through personal test, I can't find the word 2003xml option with WPS. If you save it as word XML, there will be compatibility problems to avoid the problem that the exported word document can't be opened with Word 2003];
4. Open the file with firstobject free XML editor, select indent under tools [or press the shortcut key F8] to format the file content. The document structure is on the left and the document content is on the right;
5. Replace the part of the document that needs to be dynamically modified with the freemaker logo. In fact, it is the key in map < string, Object >, such as ${landname};
6. Where the image placeholder is added, you will see a piece of Base64 encoded code. Replace Base64 with ${image}, that is, the key in map < string, Object > and the value must be processed into Base64;
Code such as: < W: bindata W: name = "wordml: / / customize. PNG" XML: space = "preserve" > ${image} < / W: bindata >
Note: "> ${image} <" cannot add any other symbols such as space, tab, line feed and so on.
If a loop is required, use: < #list maps as map > < / #list > maps is the key in map < string, Object >, the value is array, and the map is user-defined;
7. After the identification is replaced, the template is finished and saved as FTL suffix file is enough. Note: you must not open the FTL template file with word, otherwise the XML content will change, resulting in the previous work in vain.
code implementation
Tool class wordutils Java
Action
Base64 processing
Javascript
Conclusion
If you are not familiar with the FreeMarker tag, you can learn it online to understand the document structure.
Related links
Download address of firstobject free XML Editor: http://www.firstobject.com/dn_editor.htm
Freemaker official website: http://freemarker.org/