Word documents (with pictures) exported under Spring MVC

Source: Internet
Author: User
Tags base64

Recently in processing Word document export work, organize and summarize below.


After some Baidu and pro-test, most people use itext,ireport and so on ... When I try to use these methods, to achieve my needs can be, but the code is too large ~ ~ ~ because my Word document structure is more complex, more content, a little lazy to write. So I'm looking for a JSP or JavaScript page to export, this format is directly on the Web page has been edited, not to be converted into Word by the code.


JavaScript mode words need to use to ActiveXObject, this looks like the browser is required ~ ~ Give up

Through the JSP way, technical difficulties key in the export of pictures. Baidu can know, the picture into the Base64 code directly output to the page, the back is going in this direction, and finally combined with freemarker, to achieve the demand.


The following steps are given

    1. Create a Word document template

    2. Save Word document as XML format

In this step, I try to put the XML file directly into the background, the image Base64 encoding through the El expression directly replaced, found that the export Word document open error, so I'll go around, save it as. FTL freemarker Template

3. Edit the XML, replace the variable with the El expression, as shown here to change a picture to an El expression

<pkg:part pkg:name= "/word/media/image4.jpeg" pkg:contenttype= "Image/jpeg" pkg:compression= "Store" > <pkg: Binarydata>${datapic}</pkg:binarydata></pkg:part>

4. Put the template under the project, I'm here to/web-inf/templates

Because I combine spring MVC to implement, function, so I do freemarkerconfig in Applicationcontext.xml configuration such as:

<!-- Freemarker  configuration  -->    <bean id= "Freemarkerconfig"   class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >         <property name= "Templateloaderpath"  value= "/web-inf/templates/"  />         <property name= "Defaultencoding"      value= "UTF-8"  />        <property name= " Freemarkersettings ">            <props>                 <prop  key= "Template_update_delay" >10</prop>                 <prop key= "Locale" >zh_CN</prop>                 <prop key= "Number_format" >0.##########</prop>                 <prop key= " Datetime_format ">yyyy-MM-dd HH:mm:ss</prop>                 <prop key= "Classic_compatible" >true</prop>                 <prop  key= "Template_exception_handler" >ignore</prop>             </props>        </property>     </bean>

5. Add Viewresolver to parse Freemarker

<bean id= "Ftlviewresolver" class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" > <property name= "Viewclass" value= "Org.springframework.web.servlet.view.freemarker.FreeMarkerView"/> <pro Perty name= "suffix" value= ". Ftl"/> <property name= "exposerequestattributes" value= "true"/> <pr Operty name= "Exposesessionattributes" value= "true"/> <property name= "Exposespringmacrohelpers" value= "true" /> <property name= "order" value= "0"/> </bean>

6. Writing a Controller

@RequestMapping (value = "/report") public String Word (model model) {GetResponse (). setcharacterencoding ("UTF-8")        ;        GetResponse (). setContentType ("Application/msword");        GetResponse (). AddHeader ("Content-disposition", "Attachment;filename=report.doc"); Jfreechart picture Model.addattribute ("Datapic", Base64utils.image2str (Chartutils.createlinechart (PrepareDataset (), "        Last 7 days blood pressure data "," Time "," MmHg "), 1200, 800);    return "Report"; }


A tool class for turning Base64 is also available here

public class base64utils {    private static base64encoder  Encoder = new base64encoder ();     private base64utils ()  {     }    /**     *  Local image ext  base64  encoded output &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;*/&NBSP;&NBSP;&NBSP;&NBSP;PUBLIC&NBSP;STATIC&NBSP;STRING&NBSP;LOCALIMAGE2STR ( String imagepath)  {        File imageFile =  New file (ImagePath);        if  (imagefile.exists ()   && imagefile.isfile ())  {             try {                 return image2str (New fileinputstream (imagefile));             } catch  (filenotfoundexception e)  {                 // ignore             }        }         return  "";    }    /**     *  jfreechart  Chart Turn  base64  encode      */    public  Static string chartimage2str (jfreechart chart, int width, int height)   {        bytearrayoutputstream out = new  Bytearrayoutputstream ();        try {             chartutilities.writechartasjpeg (Out, 1.0f, chart,  width, height,  null);             out.flush ();             byte[] data = out.tobytearray ();             return image2str (new  Bytearrayinputstream (data));        } catch  (IOException  e)  {            // ignore         } finally {             try {                 out.close ();             } catch  (ioexception e)  {                 // ignore            }         }        return  "";     }     /**     *  Network Image turn  base64  encode output       */    public static string webimage2str (String urlPath)  {        InputStream in = null;         try {             url url = new url (URLPath);             urlconnection connection = url.openconnection ();             connection.connect ();              In = connection.getinputstream ();             return image2str (in);        } catch  (IOException  e)  {            // ignore         } finally {             if  (in != null)  {                 try {                     in.close ();                 } catch  (IOException  e)  {                     // ignore                }             }         }        return  "";    }     /**     *  Picture Input flow  base 64  coding       */    public static string image2str (InputStream stream)  {        if  (stream != null)  {             try {                 byte[] data = new byte[ Stream.available ()];                 int length =  stream.read (data);                 if  (length > 0)  {                     return encoder.encode (data);                 }             } catch  (ioexception e)  {                 // ignore             }        }         return  "";     }}


This article is from the "Half Bucket Water" blog, please be sure to keep this source http://kinken.blog.51cto.com/4569049/1709913

Word documents (with pictures) exported under Spring MVC

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.