Java generates Word documents from Freemarket

Source: Internet
Author: User
Tags base64

1. The reason for using Freemarker is because POI and itext are missing when dealing with complex Word document formats, especially when building Word documents (other tools that work with word need to dynamically load the Windows dynamic-link library, and some are charged). And the need to insert a picture in Word location, so after referring to the POI and Itext official website to handle word and other tools on the Web, found that Freemarker can be set by the Word template, after processing the generated FTL file, You can generate a Word file at the specified location directly through the Freemarker tool jar package. (There are some drawbacks to using template generation: Inserting the image size in Word automatically zooms in or out according to the size of the picture in the template, so it is recommended that you upload the fixed image size in a predetermined format, and that the resulting Word document sometimes appears to prompt a document error, The docx template created with WPS is not a problem, but there is a problem with the DOC documentation for Office, and the problem is not solved yet. Tip: The template suffix name is best aligned with the generated document suffix! )


#注意事项: The 64-bit JDK jdk1.7.0_45,windows system is 64-bit WIN10


2. The basic process for generating the final Word document is

Execute the Word template--xml--ftl--java tool class to generate the required Word documents


3, Word template, for example: (The following is a Word document template Test.doc, on one page, too large, divided into three pictures screenshot, can be customized)

#注意事项: Because every page of data generated by Freemarker is populated with Word templates, the top and bottom of Word templates must not have extra empty lines!

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/86/74/wKiom1e_FEjCfuYMAAA4SkmoGWw032.jpg "style=" float: none; "title=" 1.jpg "alt=" Wkiom1e_fejcfuymaaa4skmogww032.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/86/74/wKiom1e_FEmRbMzqAACpaF65lrI188.jpg "style=" float: none; "title=" 2.jpg "alt=" Wkiom1e_femrbmzqaacpaf65lri188.jpg "/>

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M02/86/74/wKioL1e_FEmhJvvcAAAeTPQNEWc044.jpg "style=" float: none; "title=" 3.jpg "alt=" Wkiol1e_femhjvvcaaaetpqnewc044.jpg "/>



4. Save as an XML document, such as Test.xml

#由于这里要生成多页, the following areas need to be modified in the generated Test.xml:

4, 1 Open the Test.xml document, you will find all the images generated BASE64 encoding, you need to first BASE64 code all deleted.

#删除完之后可以使用XML格式化工具, the XML document is formatted, the following procedure is explained in the format of the XML format file.

Formatted address: Http://tool.oschina.net/codeformat/xml.

4, 2 because you want to generate multiple pages, so you want to add the list loop label and the corresponding value tag (in the form of map).

#以下只标注需要改动的地方

4, 2, 1 Add the list tag, search directly <w:tbl> and </w:tbl>, this one XML according to my example only a pair.

#listdataMap是个list, the list is loaded with multiple maps, which are datamap.

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M01/86/74/wKiom1e_F5DSTlRIAABwi4d8MMs567.jpg "title=" 4.jpg " alt= "Wkiom1e_f5dstlriaabwi4d8mms567.jpg"/>

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M01/86/74/wKioL1e_F9-jEJ6gAABrnbCl0e8688.jpg "title=" 5.jpg " alt= "Wkiol1e_f9-jej6gaabrnbcl0e8688.jpg"/>


4, 2, 2 Add the value tag in the list tag, the Test1 in the search template is replaced with ${datamap.test1},test2 and others.

#dataMap这是个Map, Test1 is the key value

650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M01/86/74/wKiom1e_GF6T7w4lAAAz70AkPrQ348.jpg "title=" 6.jpg " alt= "Wkiom1e_gf6t7w4laaaz70akprq348.jpg"/>

650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M02/86/74/wKioL1e_GKqh1_yFAABEX7IWhqs448.jpg "title=" 7.jpg " alt= "Wkiol1e_gkqh1_yfaabex7iwhqs448.jpg"/>

4, 2, 3 where the custom page number is also to be manually replaced (this field in the middle of the list above), it is found that word comes with a bad page number (footer inserted image is also not good), temporarily customized, if found to engage, then I will update this blog.

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M02/86/74/wKioL1e_GbeBWuwjAABwGsdiI7c995.jpg "title=" 8.jpg " alt= "Wkiol1e_gbebwuwjaabwgsdii7c995.jpg"/>


4, 2, 4 modify the image tag content, that is, 4, 1 corresponding BASE64 encoding related tags,

The modification principle is the same as 4, 2, 1--4, 2, 3.

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M00/86/75/wKiom1e_HHPRgBA7AAEVyNc7_KI038.jpg "title=" 9.jpg " alt= "Wkiom1e_hhprgba7aaevync7_ki038.jpg"/> #因为每页都需要图片展示, so the picture also needs to be displayed in the same place on each page, with the order of placement of the picture placed in the Word template from top to bottom.


4, 3 Save the above XML file as an FTL file, preferably stick to the Java project, see 4, 4.


4, 4 the project format is

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M00/86/75/wKiom1e_JAvRYWE4AAAsDEVsSTI099.jpg "title=" 10.jpg "alt=" Wkiom1e_javrywe4aaasdevssti099.jpg "/>



4.5documenthandler.java Tool Processing code example:

package org.mbox.test;import java.io.bufferedwriter;import java.io.file;import  Java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.fileoutputstream;import  java.io.IOException;import java.io.InputStream;import java.io.OutputStreamWriter;import  java.io.unsupportedencodingexception;import java.io.writer;import java.util.arraylist;import  java.util.hashmap;import java.util.list;import java.util.map;import sun.misc.base64encoder; import freemarker.template.configuration;import freemarker.template.template;import  Freemarker.template.templateexception;public class documenthandler {private configuration  configuration = null;public documenthandler ()  {configuration = new  Configuration (); Configuration.setdefaultencoding ("Utf-8");} Private static string getimagestr (String imgfile)  {     InputStream in = null;     byte[] data =  Null;     try {       in = new  fileinputstream (imgfile);        data = new byte[ In.available ()];       in.read (data);        in.close ();     } catch  (ioexception e)  {        e.printstacktrace ();     }      Base64encoder encoder = new base64encoder ();     return  Encoder.encode (data);    }public void createdoc (map<string, object>  Listdatamap,string filename)  throws unsupportedencodingexception { Configuration.setclassfortemplateloading (This.getclass (), &NBSP; " /org/mbox/test "); Template t=null;try {t = configuration.gettemplate ("TEST.FTL");}  catch  (ioexception e)  {e.printstacktrace ();} File outfile = new file (FileName); writer out = null; Fileoutputstream fos=null;try {fos = new fileoutputstream (outFile); OutputStreamWriter  owriter = new outputstreamwriter (FOS, "UTF-8"); out = new  BufferedWriter (Owriter); } catch  (filenotfoundexception e1)  {e1.printStackTrace ();}          try {t.process (listdatamap, out); Out.flush (); Fos.flush (); Out.close (); Fos.close ();}  catch  (templateexception e)  {e.printstacktrace ();}  catch  (ioexception e)  {e.printstacktrace ();}         }/** *  @param  args *  @throws   Unsupportedencodingexception &nbsP;*/public static void main (String[] args)  throws unsupportedencodingexception  {Map<String, Object> map = new HashMap<String,Object> (); List<map<string, object>> listdatamap = new arraylist<map<string,  Object>> ();for  (int i = 0; i < 5; i++)  {Map< String, object> datamap = new hashmap<string, object> ();d atamap.put (" Image1 ",  getimagestr (" G:/1.jpg "));d atamap.put (" Image2 ",  getimagestr (" G:/2.jpg "));d atamap.put (" Image3 ",  getimagestr (" G:/3.jpg "));d atamap.put (" Test1 ", " value "+i);d atamap.put (" Test2 ", " value "+i); Datamap.put ("Test3",  "value" +i);d atamap.put ("Test4",  "value" +i);d atamap.put ("Test5",  "value" +i) ;d atamap.put ("Pagenum",  (i+1)); Listdatamap.add (DATAMAP);} Map.put ("Listdatamap",  listdatamap);D Ocumenthandler mdoc = neW documenthandler (); Mdoc.createdoc (map,  "G:/outfile.doc");}} 



















This article is from the "You can choose Extraordinary" blog, please be sure to keep this source http://ylcodes01.blog.51cto.com/5607366/1842693

Java generates Word documents from Freemarket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.