zoukankan      html  css  js  c++  java
  • Java使用IText(VM模版)导出PDF,IText导出word(二)

    ===============action===========================

        //退款导出word
        public void exportWordTk() throws IOException{
             Long userId=(Long)ServletActionContext.getContext().getSession().get(Constant.SESSION_USER_ID);
            //获取生成Pdf需要的一些路径
            String tmPath=ServletActionContext.getServletContext().getRealPath("download/template");//vm 模板路径
            String wordPath=ServletActionContext.getServletContext().getRealPath("download/file");//生成word路径
            //wordPath+"/"+userId+"_"+fk+".doc"
            //数据
            Map map=new HashMap();//velocity模板中的变量
            map.put("date1",this.fk);
            map.put("date",new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
            String newFile=wordPath+"/tk_word_"+userId+".doc";
            File file=new File(newFile);
            if(!file.exists()){
                //设置字体,支持中文显示
                new PdfUtil().addFontAbsolutePath(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun.ttf"));//这个字体需要自己去下载
                PdfUtil.createByVelocityPdf(tmPath,"tk_word.vm", wordPath+"/tk_word_"+userId+".pdf", map);//导出PDF
                PdfUtil.createByVelocityDoc(tmPath,"tk_word.vm",newFile, map);//导出word
            }
            sendMsgAjax("dzz/download/file/tk_word_"+userId+".doc");
        }
       

    =================vm 文件模板(tk_word.vm)=====================


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <style type="text/css">
        body, button, input, select, textarea {
        color: color:rgb(0,0,0);
        font: 14px/1.5 tahoma,arial,宋体,sans-serif;
        }
        p{
        margin:0;padding:0;
        }
        .title{
        border-bottom:1px solid rgb(0,0,0);
        margin:0;
        padding:0;
        85%;
        height:25px;
        }
        li{
        list-style:none;
        }
        .li_left li{
            text-align:left;
            line-height:47px;
             font-size:14pt;
        }
        .li_left{
            610px;
        }
        .fnt-21{
        font-size:16pt;
        }
        table{
        90%;
        /*argin-left:25px;*/
        }
        div_cls{
            100%;
            text-align:center;
        }
        </style>
      </head>
     
      <body style="font-family: songti;100%;text-align:center;">
     <div style="text-align:center;"><b class="fnt-21">&nbsp;&nbsp;本组评审结果清单</b> </div>
      <table  border="1" cellpadding="0" cellspacing="0" style="90%;margin-left:25px;">
        <tr>
          <td style="20%" align="center">申报单位</td>
          <td style="10%" align="center">申报经费(万元)</td>

        </tr>
       
      </table>
          <br/>
          <div>
              <ul style="float:right;margin-right:40px;">
                  <li>$date</li><!--获取后天封装的数据-->
              </ul>
          </div>
      </body>
    </html>

    ====================工具类======================

    package com.qgc.dzz.util;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;

    import org.apache.struts2.ServletActionContext;
    import org.apache.velocity.Template;
    import org.apache.velocity.VelocityContext;
    import org.apache.velocity.app.VelocityEngine;
    import org.xhtmlrenderer.pdf.ITextFontResolver;
    import org.xhtmlrenderer.pdf.ITextRenderer;

    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Font;
    import com.lowagie.text.Image;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.BaseFont;
    import com.lowagie.text.pdf.PdfImportedPage;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfWriter;

    public class PdfUtil {
        private static List<String> fonts = new ArrayList();//字体路径

        /**
         * 使用vm导出word
         * @param localPath VM 模板路径
         * @param templateFileName vm 模板名称
         * @param docPath 生成文件的路径,包含文件如:d://temp.doc
         * @param map 参数,传递到vm
         * @return
         */
          public static boolean createByVelocityDoc(String localPath, String templateFileName, String docPath, Map<String, Object> map)
          {
            try
            {
                createFile(localPath,templateFileName,docPath, map);
              return true;
            } catch (Exception e) {
            e.printStackTrace();
                
            }
            return false;
          }
          
        /**
         * 导出pdf
         * @param localPath VM 模板路径
         * @param templateFileName vm 模板名称
         * @param pdfPath 生成文件的路径,包含文件如:d://temp.pdf
         * @param map 参数,传递到vm
         * @return
         */
          public static boolean createByVelocityPdf(String localPath, String templateFileName, String pdfPath, Map<String, Object> map)
          {
            try
            {
            
                  
              String htmlPath = pdfPath + UUID.randomUUID().toString() + ".html";

             createFile(localPath, templateFileName, htmlPath, map);//生成html 临时文件

             HTML2OPDF(htmlPath, pdfPath, fonts);//html转成pdf

             File file = new File(htmlPath);
             file.delete();

              return true;
            } catch (Exception e) {
            e.printStackTrace();
                
            }
            return false;
          }
          
          /**
           * 合并PDF
           * @param writer
           * @param document
           * @param reader
           * @throws DocumentException
           */
        public void addToPdfUtil(PdfWriter writer, Document document,
                PdfReader reader) throws DocumentException {

            int n = reader.getNumberOfPages();

            Rectangle pageSize = document.getPageSize();

            float docHeight = pageSize.getHeight();

            float docWidth = pageSize.getWidth();

            for (int i = 1; i <= n; i++) {

                document.newPage();

                PdfImportedPage page = writer.getImportedPage(reader, i);

                Image image = Image.getInstance(page);

                float imgHeight = image.getPlainHeight();

                float imgWidth = image.getPlainWidth();

                if (imgHeight < imgWidth) {

                    float temp = imgHeight;

                    imgHeight = imgWidth;

                    imgWidth = temp;

                    image.setRotationDegrees(90.0F);

                }

                if ((imgHeight > docHeight) || (imgWidth > docWidth)) {

                    float hc = imgHeight / docHeight;

                    float wc = imgWidth / docHeight;

                    float suoScale = 0.0F;

                    if (hc > wc)

                        suoScale = 1.0F / hc * 100.0F;

                    else {

                        suoScale = 1.0F / wc * 100.0F;

                    }

                    image.scalePercent(suoScale);

                }

                image.setAbsolutePosition(0.0F, 0.0F);

                document.add(image);

            }
        }

        
        /**
         * html 转成 pdf 方法
         * @param htmlPath html路径
         * @param pdfPath pdf路径
         * @param fontPaths 字体路径
         * @throws Exception
         */
        public static void HTML2OPDF(String htmlPath, String pdfPath,
                List<String> fontPaths)

        throws Exception

        {

            String url = new File(htmlPath).toURI().toURL().toString();//获取生成html的路径

            OutputStream os = new FileOutputStream(pdfPath);//创建输出流
            
            ITextRenderer renderer = new ITextRenderer();//itext 对象
            
            ITextFontResolver fontResolver = renderer.getFontResolver();//字体
    //        //支持中文显示字体
    //        fontResolver.addFont(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun_0.ttf"),    
    //                BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            if ((fontPaths != null) && (!fontPaths.isEmpty())) {

                URL classPath = PdfUtil.class.getResource("/");

                for (String font : fontPaths) {

                    if (font.contains(":"))

                        fontResolver.addFont(font, "Identity-H", false);

                    else {

                        fontResolver.addFont(classPath + "/" + font, "Identity-H",
                                false);

                    }

                }

            }

            renderer.setDocument(url);//设置html路径

            renderer.layout();

            renderer.createPDF(os);//html转换成pdf

            System.gc();

            os.close();

            System.gc();

        }

        public static boolean createFile(String localPath, String templateFileName,
                String newFilePath, Map<String, Object> map)

        {

            try

            {

                VelocityEngine engine = new VelocityEngine();

                engine.setProperty("file.resource.loader.path", localPath);//指定vm路径

                Template template = engine.getTemplate(templateFileName, "UTF-8");//指定vm模板

                VelocityContext context = new VelocityContext();//创建上下文对象

                if (map != null)

                {

                    Object[] keys = map.keySet().toArray();

                    for (Object key : keys) {

                        String keyStr = key.toString();

                        context.put(keyStr, map.get(keyStr));//传递参数到上下文对象

                    }

                }

                PrintWriter writer = new PrintWriter(newFilePath, "UTF-8");//写入参数到vm
            
                template.merge(context, writer);

                writer.flush();

                writer.close();

                return true;

            } catch (Exception e) {

                e.printStackTrace();

            }
            return false;

        }

        public static Font FONT = getChineseFont();

        public static BaseFont BSAE_FONT = getBaseFont();

        /**
         * 支持显示中文
         * @return
         */
        public static Font getChineseFont() {

            BaseFont bfChinese = null;

            try {

                bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
                        false);

            } catch (DocumentException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            }

            Font fontChinese = new Font(bfChinese);

            return fontChinese;

        }

        public static BaseFont getBaseFont() {

            BaseFont bfChinese = null;

            try {

                bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
                        false);

            } catch (DocumentException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return bfChinese;

        }
        
          public void addFontAbsolutePath(String path)
          {
            this.fonts.add(path);
          }

          public void addFontClassPath(String path)
          {
            this.fonts.add(path);
          }

          public List<String> getFonts() {
            return this.fonts;
          }

          public void setFonts(List<String> fonts) {
            this.fonts = fonts;
          }

    }

  • 相关阅读:
    老陌与博客
    有关模式窗体和无(非)模式窗体的区别
    10月9日至10月22日备忘录
    9月4日至9月10日备忘录
    VS2015 远程调试:Remote Debugger
    8月28日至9月3日备忘录
    8月21日至8月27日技术积累
    用函数方法实现迭代器
    python中eval, exec, execfile,和compile(转载)
    dev 中的GridControl中的行实现选择的功能实现
  • 原文地址:https://www.cnblogs.com/qgc88/p/4769140.html
Copyright © 2011-2022 走看看