struts2 + freemark + itext 导出pdf(基于模板方式)

生成静态页面方法:

private void statHtml(Product product){
       try{
           //初始化FreeMarker配置
           //创建一个Configuration实例
           cfg = new Configuration();
           cfg.setDirectoryForTemplateLoading(new File(ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"jsp\\product"));
           cfg.setEncoding(Locale.getDefault(), "utf-8");
           //创建模版对象
           Template t = cfg.getTemplate("look.html");
           t.setEncoding("utf-8");
           //生成静态
           String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"jsp\\product";
           //在模版上执行插值操作,并输出到制定的输出流中
           File fileName = new File(path + "\\look1.html");
           Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
           t.process(product, out);
           out.flush();
           out.close();
       }catch(Exception e){
           e.printStackTrace();
       }
   }

导出pdf:

public String downPdf() throws Exception{
       ITextRenderer renderer = new ITextRenderer();
       if(id > 0 && !"".equals(id)){
           product = productService.modProduct(id);
           statHtml(product);
       }
       String dest = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"jsp\\product";
       String outputFile =dest+"\\"+ "报告" + ".pdf"; //定义输出文件全名
       File outFile = new File(outputFile);
       if (!outFile.exists()) {
           outFile.getParentFile().mkdirs();
       }
       OutputStream os = new FileOutputStream(outputFile);
       String path = dest+"\\look1.html";
       String url = new File(path).toURI().toURL().toString();
       // 解决中文支持问题
       ITextFontResolver fontResolver = renderer.getFontResolver();
       fontResolver.addFont(dest +"\\arialuni.ttf", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
       renderer.setDocument(url);
       renderer.layout();
       renderer.createPDF(os);
       os.flush();
       os.close();
       return SUCCESS;
    }

private InputStream pdfStream;   private String pdfName;   给出get,set方法

xml配置:

<action name="downPdf" class="com.mobile.action.product.ProductAction" method="downPdf">
             <result name="success" type="stream">
                <param name="contentType">application/pdf; charset=gb2312</param>
                <param name="inputName">pdfStream</param>
                <param name="contentDisposition">attachment; filename="${pdfName}"</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>

html 模板:

<!DOCTYPE html>
<html>
  <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8"></meta>
      <style type="text/css">
    @page {
      size: A4 landscape;
    }
          
    h1{font-size:16px;text-align:center}
    table{width:100%;border-collapse:collapse;table-layout:fixed}
    table th,table td{border:1px solid gray;text-align:center;font-size:12px;padding:3px;font-weight:normal}
    table.signature td{border:0}
    p,ul li{line-height:1.5em}
    span.hl{color:red}
    #report-item-notes{list-style:none}
    #report-item-notes ol{list-style:none}
  </style>
  </head>
  <body style="font-family:'Arial Unicode MS'"> 必须加这个样式,style 样式要写在 head 里面
      <h1>产品信息</h1>
      <table>
            <tbody>
                <tr>
                    <th>产品名称:</th>
                    <th>产品价格:</th>
                </tr>
                <tr>
                    <td>${productName}</td>
                    <td>${productPrice}</td>
                </tr>
            </tbody>
        </table>

  </body>
</html>


你可能感兴趣的:(java,struts2.0)