ITextRenderer freemarker 生成pdf demo,并解决中文不显示的问题

最少jar包

core-renderer-R8.jar
itext-2.0.8.jar
freemarker-2.3.23.jar

package com.pdf;


import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.util.HashMap;

/**
 * Created by admin on 2017/7/5.
 */
public class PdfHandler {
    private static final String CONTRACT = "resource/contract/";//文件存储路径
    private static final String TEMPLATE = "resource/templates/";//模板存储路径


    private static final String PDFNAME = "pdfDemo";//pdf文件名
    private static final String HTMLNAME = "pdfDemo";//html文件名


    public static void contractHandler(String templateName,
                                       HashMap paramMap) throws Exception {
        // 获取本地模板存储路径、文件存储路径
        String templatePath = TEMPLATE;
        String contractPath = CONTRACT;
        // 组装html和pdf合同的全路径URL
        String localHtmlUrl = contractPath + HTMLNAME + ".html";
        String localPdfPath = contractPath + "/";
        // 判断本地路径是否存在如果不存在则创建
        File localFile = new File(localPdfPath);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }
        String localPdfUrl = localFile + "/" + PDFNAME + ".pdf";
        templateName = templateName + ".ftl";
        htmHandler(templatePath, templateName, localHtmlUrl, paramMap);// 生成html合同
        pdfHandler(localHtmlUrl, localPdfUrl);// 根据html合同生成pdf合同
        deleteFile(localHtmlUrl);// 删除html格式合同

        System.out.println("PDF生成成功");
    }

    private static void deleteFile(String fileUrl) {
        File file = new File(fileUrl);
        file.delete();
    }

    private static void pdfHandler(String htmUrl, String pdfUrl) throws IOException, DocumentException {
        File htmFile = new File(htmUrl);
        File pdfFile = new File(pdfUrl);
        String url = htmFile.toURI().toURL().toString();
        OutputStream os = new FileOutputStream(pdfFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(TEMPLATE + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        renderer.layout();
        renderer.createPDF(os);
        os.close();
    }

    private static void htmHandler(String templatePath, String templateName, String hHtmlUrl, HashMap paramMap) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setDirectoryForTemplateLoading(new File(templatePath));
        Template template = cfg.getTemplate(templateName);
        File outHtmFile = new File(hHtmlUrl);
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outHtmFile)));
        template.process(paramMap, writer);
        writer.close();
    }

    public static void main(String[] args) throws Exception {
        String templateName = "201";
        HashMap paramMap = new HashMap<>();
        paramMap.put("user", "nihao");
        paramMap.put("url", "192.168.1.2");
        paramMap.put("name", "生成成功");
        contractHandler(templateName, paramMap);
    }
}

 其中解决中文问题java代码如下:(此处:.addFont() 方法中 “simsun.ttc” 后不加 “,” ;与BaseFont.createFont 不同

        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(TEMPLATE + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

 对应的ftl文件中必须加上   :  body{font-family: SimSun},并且只有body中能显示中文,body外部分不显示

<html>
    <head>
        <style>
            body{font-family: SimSun}
        </style>
        <title>
            welcome!
        </title>

    </head>
    <body>
        <h1>welcome! ${user}${name}</h1>
        用户名:${user}
        URL:${url}
        姓名:${name}
    </body>
     姓名:${name}
     URL:${url} </html>

 

posted @ 2017-07-06 15:39  java小蜗牛  阅读(3748)  评论(0)    收藏  举报