Using Freemarker to build a Word document in a Java Web project

Source: Internet
Author: User
Tags base64

It is common to build Word documents in Web projects, and there are many Java-based solutions, including the use of Jacob, Apache POI, Java2word, Itext, and so on, in fact, starting with Office 2003, You can convert an Office document to an XML file so that you can use a template engine like Freemarker to replace the placeholder with the real data as long as you put the ${} placeholder on the content you want to fill in, which is easier than any other scenario.


Here is a simple example, such as filling out a resume on a Web page, and then clicking Save to download it locally, as shown below.


Open the downloaded Word file


Start by creating a new dynamic Web project in Eclipse Java EE Edition, as shown in the project structure


To add the Freemarker jar file to your project, you can get the latest version of Freemarker using the link below:

Http://freemarker.org/freemarkerdownload.html


Template file Resume.ftl is how to build, in fact, very simple, will need to do the Word document, choose Save as XML file, save after the proposal with EditPlus, notepad++, sublime and other tools to open the view, Because sometimes the placeholder you write may be taken apart so that freemarker cannot be processed.


Open the XML file look, if you have just written ${title}, ${name} was broken up by the XML file, modify the XML file is OK.


After the modification, save as RESUME.FTL template file as follows:


Next is the servlet (or STRUTS2 action, the controller of Spring MVC, etc.) and the authoring of the tool class Wordgenerator and the creation of the page test.jsp, as shown in the code below:

Code for small Services:

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.httpservletrequest;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 (Httpservle Trequest req, HttpServletResponse resp) throws Servletexception, IOException {req.setcharacterencoding ("utf-8"); map<string, object> map = new hashmap<string, object> (); enumeration<string> paramnames = Req.getparameternames ();//The form parameter is placed in a key-value pair map by looping while ( Paramnames.hasmoreelements ()){String key = Paramnames.nextelement (); String value = Req.getparameter (key); Map.put (key, value);} Tip: Before invoking a tool class to generate a Word document, you should check that all fields are complete//otherwise the Freemarker template is attentive to the error when it is processed. This step is ignored for the time being. file File = Null;inputstream fin = Null Servletoutputstream out = null;try {//Call tool class Wordgenerator Createdoc method to generate Word document file = Wordgenerator.createdoc (map, " Resume "), Fin = new FileInputStream (file), resp.setcharacterencoding (" Utf-8 "); Resp.setcontenttype (" application/ MSWord ");//Set browser to process the file by default named Resume.docresp.addHeader (" Content-disposition "," Attachment;filename=resume.doc " ); out = Resp.getoutputstream (); byte[] buffer = new byte[512];//buffer int bytestoread = -1;//outputs the contents of a read-in Word file to the browser by looping 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 temp file}}}

Code for the tool class:

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> alltemplates = 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 () {throw 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 {//This place cannot be used filewriter because the encoding type needs to be specified otherwise the resulting Word document cannot open writer W = new because of an unrecognized encoding OutputStreamWriter (new FileOutputStream (f), "utf-8"); T.process (DataMap, W); W.close ();} catch (Exception ex) {ex.printstacktrace (); throw new RuntimeException (ex);} return f;}}

The code for the JSP page:

<%@ page pageencoding= "UTF-8"%><! DOCTYPE html>
Description: The small service is configured with annotations, so your server needs to support the Servlet 3 specification, and the server I use is Tomcat 7.0.52. If your server does not support the Servlet 3 specification then use Web. XML to configure your small service, no other place is different. If you are unfamiliar with the new features of the Servlet 3 specification, you can read another article on CSDN, as shown in the following link:

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

In addition, if you want to insert a picture in a Word document, you can replace the long string (BASE64 encoded string) that represents the picture in the XML file that word saved as a placeholder to convert the picture object that will be inserting the Word document into a BASE64 encoded string. Replace the placeholder with the string, and the code looks like this:


The code to convert the picture 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, Rt.jar has this class, but it cannot be used directly, it needs to modify the access permissions, which can be modified in eclipse.

Right-click on the project to select the Properties menu entry to enter the interface as shown:



This allows you to use the Base64encoder class when you call the Getimagestring method in your project to specify the full file name of the picture you want to insert (the file name with the path), and the string returned by the method is the string that the picture is processed into BASE64 encoded. I hope you follow the above steps once success!

Using Freemarker to build a Word document in a Java Web project

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.