Export word documents (including images) under spring mvc

Source: Internet
Author: User

Export word documents (including images) under spring mvc
Recently, I have been working on exporting word documents, sorting them out, and summarizing them. After some tests in Baidu and closed labs, most people use iText, iReport, and so on... when I try to use these methods, I need to meet my needs, but the amount of code is too large ~~~ Because the structure of my word documents is complicated and the content is large, I am a little too lazy to write. So I am seeking to export through jsp or javascript pages, so that the format has been edited directly on the web page, and the Code cannot be converted to the word form. ActiveXObject must be used in javascript mode, which requires the browser ~~ If you simply quit using jsp, the key to technical difficulties lies in exporting images. Baidu can know that it is enough to convert the image into base64 encoding and directly output it to the page. The next step is to go in this direction, and finally the FreeMarker is used to achieve the requirement. The following are the steps to create a word document template. Save the word document as xml. In this step, I try to put the xml file directly in the background and use the el expression to replace the base64 encoding of the image, an error occurs when the exported Word document is opened. Therefore, I will try again and save it. ftl freeMarker TEMPLATE 3. edit xml and replace the variable with the el expression. Here, change an image to the 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 am here to/WEB-INF/templates because I have combined spring mvc to implement, function, so I am in applicationConte Configure freeMarkerConfig in xt. xml as follows: <! -- 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 <bean id = "ftlViewResolver" class = "org. springframework. web. servlet. view. freemarker. freeMarkerViewResolver "> <property name =" viewClass "value =" org. springframework. web. servlet. view. Freemarker. freeMarkerView "/> <property name =" suffix "value = ". ftl "/> <property name =" exposeRequestAttributes "value =" true "/> <property name =" exposeSessionAttributes "value =" true "/> <property name =" exposeSpringMacroHelpers "value = "true"/> <property name = "order" value = "0"/> </bean> 6. compile controller @ RequestMapping (value = "/report") public String word (Model model) {getResponse (). setCharacterEnc Oding ("UTF-8"); getResponse (). setContentType ("application/msword"); getResponse (). addHeader ("Content-Disposition", "attachment?filename=report.doc"); // JFreeChart image model. addattrils ("dataPic", Base64Utils. image2Str (ChartUtils. createLineChart (prepareDataset (), "blood pressure data for the last 7 days", "time", "mmHg"), 1200,800); return "report ";} here we also provide a tool class for converting base64 to public class Base64Utils {private static BASE64Encoder e Ncoder = new BASE64Encoder (); private Base64Utils () {}/ *** convert local image to base64 encoded output */public static String localImage2Str (String imagePath) {File imageFile = new File (imagePath); if (imageFile. exists () & imageFile. isFile () {try {return image2Str (new FileInputStream (imageFile);} catch (FileNotFoundException e) {// ignore} return "";} /*** convert JFreeChart chart to base64 encoding */public static String c HartImage2Str (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} retur N "";}/*** network image to base64 encoded 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 "";} /*** input stream base 64 encoding */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 "";}}

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.