Use Freemarker in Java Web projects to generate WORD Documents and webfreemarker

Source: Internet
Author: User

Use Freemarker in Java Web projects to generate WORD Documents and webfreemarker

It is not uncommon for Web projects to generate WORD Documents. There are also many Java-based solutions, including the use of Jacob, Apache POI, Java2Word, iText, and other methods. In fact, since Office 2003, the Office document can be converted to an XML file, so that you only need to put the content to be filled in with the placeholder $, you can use a template engine like Freemarker to replace the placeholder with real data. This method is simpler than other solutions.


The following is a simple example. For example, enter your resume on the Web page and click Save to download it to your local computer, as shown below.


Open the downloaded Word file


Create a Dynamic Web Project in Eclipse Java EE, as shown in figure


To add the JAR file of freemarker to the project, you can obtain the latest version of Freemarker through the following link:

Http://freemarker.org/freemarkerdownload.html


Template File resume. how does ftl be generated? It is actually very simple. After completing the required Word documents, you can choose to save them as XML files, we recommend that you use Editplus, Notepad ++, Sublime, and other tools to open the storage. Sometimes the placeholders you write may be split, so that Freemarker cannot process them.


Open the XML file. If the $ {title} and $ {name} files you just wrote are split up by the xml file, you can modify the XML file.


Save the modification as a resume. ftl template file as follows:


The following is the compilation of Servlet (or Struts2 Action, Spring MVC Controller, etc.), tool WordGenerator, and test. jsp on the page. The Code is as follows:

Code of the small service:

Package com. lovo. servlet; import java. io. file; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. util. enumeration; import java. util. hashMap; import java. util. map; import javax. servlet. servletException; import javax. servlet. servletOutputStream; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServle TRequest; import javax. servlet. http. httpServletResponse; import com. lovo. util. wordGenerator;/*** Servlet implementation class MyServlet */@ WebServlet ("/saveDocServlet") public class MyServlet extends HttpServlet {private static final long serialVersionUID = 1L; @ Overrideprotected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req. setCharacterEncodi Ng ("UTF-8"); Map <String, Object> map = new HashMap <String, Object> (); Enumeration <String> paramNames = req. getParameterNames (); // put form parameters in key-Value Pair ing through loops while (paramNames. hasMoreElements () {String key = paramNames. nextElement (); String value = req. getParameter (key); map. put (key, value);} // prompt: before calling the tool class to generate a Word document, you should check whether all fields are complete. // otherwise, the Freemarker template may report an error because the value cannot be found during processing. Here, this step is temporarily ignored. File = null; inputStream fin = null; ServletOutputStream out = null; try {// call the createDoc method of WordGenerator in the tool class to generate a Word document file = WordGenerator. createDoc (map, "resume"); fin = new FileInputStream (file); resp. setCharacterEncoding ("UTF-8"); resp. setContentType ("application/msword"); // set the viewer to download the method to process the file named resume.doc resp. addHeader ("Content-Disposition", "attachment?filename=resume.doc"); out = resp. getOutputStream (); byte [] buffer = new byte [512]; // slow Int bytesToRead =-1; // output the content of the read Word file to the browser through a loop while (bytesToRead = fin. read (buffer ))! =-1) {out. write (buffer, 0, bytesToRead) ;}} finally {if (fin! = Null) fin. close (); if (out! = Null) out. close (); if (file! = Null) file. delete (); // delete temporary file }}}

Tool code:

Package com. lovo. util; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStreamWriter; import java. io. writer; import java. util. hashMap; import java. util. map; import freemarker. template. configuration; import freemarker. template. template; public class WordGenerator {private static Configuration configuration = null; private static Map <String, Template> allTem Plates = null; static {configuration = new Configuration (); configuration. setDefaultEncoding ("UTF-8"); configuration. setClassForTemplateLoading (WordGenerator. class, "/com/lovo/ftl"); allTemplates = new HashMap <> (); // Java 7 diamond syntax try {allTemplates. put ("resume", configuration. getTemplate ("resume. ftl ");} catch (IOException e) {e. printStackTrace (); throw new RuntimeException (e) ;}} private WordGenerator () {t Hrow new AssertionError ();} public static File createDoc (Map <?, ?> DataMap, String type) {String name = "temp" + (int) (Math. random () * 100000) + ". doc "; File f = new File (name); Template t = allTemplates. get (type ); try {// FileWriter cannot be used here because the encoding type needs to be specified. Otherwise, the generated Word document cannot open Writer w = new OutputStreamWriter (new FileOutputStream (f) Due to unidentifiable encoding ), "UTF-8"); t. process (dataMap, w); w. close ();} catch (Exception ex) {ex. printStackTrace (); throw new RuntimeException (ex);} return f ;}}

JSP page code:

<% @ Page pageEncoding = "UTF-8" %> <! DOCTYPE html> 

Note: small services are configured with annotations. Therefore, your server must support the Servlet 3 specification. The server I use is Tomcat 7.0.52. If your server does not support the Servlet 3 specification, use web. xml to configure your small service. If you are not familiar with the new features of Servlet 3 specifications, read another article on CSDN. The link is as follows:

Http://blog.csdn.net/zhongweijian/article/details/8279650

In addition, if you want to insert an image into a Word document, you can replace the long string (base64-encoded string) representing the image in the XML file saved as Word with a placeholder, after converting the image object to be inserted into a Word document to a BASE64 encoded string, replace the placeholder with this string. The Code is as follows:


The code for converting an image to a BASE64 string is as follows:

public static String getImageString(String filename) throws IOException { InputStream in = null;         byte[] data = null;         try {             in = new FileInputStream(filename);             data = new byte[in.available()];             in.read(data);             in.close();         } catch (IOException e) {             throw e;         } finally {         if(in != null) in.close();         }         BASE64Encoder encoder = new BASE64Encoder();         return data != null ? encoder.encode(data) : "";}

Note: The BASE64Encoder class used here is in the sun. misc package, and rt. jar contains this class, but it cannot be used directly. You need to modify the access permission, which can be modified in Eclipse.

Right-click the project and choose Properties to go to the interface shown in:



After this setting, you can use the BASE64Encoder class. In the project, call the getImageString method to specify the complete file name (with path name) of the image to be inserted ), the string returned by this method is a base64-encoded string. I hope you have successfully followed the steps above!


An error occurred while using Freemarker to export Word in the Web project. An error was reported using the <# list abc as being> </# list> flag in the XML file. The error cannot be identified.

<# List> </# list> label of the freemarker template. Are you sure you can use it in xml?

In a java web project, to generate complex Word documents, I use the xml file of the Word documents and freemark to generate

You can find the path in another way;
Private Configuration configuration = null;
Template t = null;
// You create a java class in the template. ftl package. This java class is not written, for example, model. java.
// Use the following method to find the path
TemplateLoader = new ClassTemplateLoader (model. class );
Configuration. setTemplateLoader (templateLoader );
T = configuration. getTemplate (path );
T. setEncoding ("UTF-8 ");
You can get it in this way. If not, ask me.

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.