使用iText 7 生成pdf

阅读更多
  1. pom.xml

 

        
            org.freemarker
            freemarker
            2.3.19
        
        
        
            com.itextpdf
            itext7-core
            7.1.3
            pom
        
        
            com.itextpdf
            html2pdf
            2.0.0
        

 

 

2. 添加模板

 

├─base
│  ├─css
│  │      base.css
│  │
│  ├─font
│  │      simhei.ttf
│  │      SIMSUN.TTC
│  │
│  └─images
│          aloner.jpg
│
└─hello
    ├─css
    │      hello.css
    │
    ├─images
    │      csdn.jpg
    │
    └─tpl
            hello.ftl

 

 

base.css

 

@CHARSET "UTF-8";
/*
 * Sunnysoft.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
body {
    font-family: 'SimSun', 'Simhei', 'Serif', serif;
    margin: 0 8px 0 8px;
    padding: 0;
}

table {
    border-collapse: collapse;
    border-spacing: 0;
    border-left: 1px solid grey;
    border-top: 1px solid grey;
    table-layout: fixed;
    word-break: break-strict;
    width: 100%;
}

th, td {
    border-right: 1px solid grey;
    border-bottom: 1px solid grey;
    padding: 5px 15px;
}

th {
    font-weight: bold;
}

 

 

hello2.ftl

 

<#--
功能描述:这个模板主要是用于演示如何使用FreeMarker+iTextPdf生成pdf文件
-->



    
    
    
    
    hello
    
    
    



演示本地图片
演示网络图片
演示临时图片

基本信息

姓名 ${emp.aac001} 证件号 ${emp.aac002}
年龄 ${emp.aac003} 出生日期 ${emp.aac002}

执行信息

<#list empList as emp >
aac001 aac002 aac003 执行案号 执行法院 执行内容 执行状态 异议备注
${emp.aac001} ${emp.aac002} ${emp.aac003} 执行案号 执行法院 执行内容 执行状态 异议备注
This is the first div.
This is the second div.
This is the third div.
This is the fourth div.
This is the fifth div.
This is the sixth div.
This is the last div.

 

FreemarkerConfiguration.java

 

 

import freemarker.template.Configuration;

public class FreemarkerConfiguration {
	public static final String PATHPREFIX = "/templates";
	private static Configuration config;

	/*
	 * Static initialization.
	 * 
	 * Initialize the configuration of Freemarker.
	 */
	static {
		config = new Configuration();
		config.setClassForTemplateLoading(FreemarkerConfiguration.class, PATHPREFIX);
	}

	public static Configuration getConfiguation() {
		return config;
	}
}

 

HtmlGenerator.java

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.BufferedWriter;
import java.io.StringWriter;
import java.util.Map;

public class HtmlGenerator {

    /**
     * Generate html string.
     *
     * @param template the name of freemarker teamlate.
     * @param dataMap  the data of teamlate.
     * @return htmlStr
     * @throws Exception
     */
    public static String generate(String template, Map dataMap)
            throws Exception {
        Configuration config = FreemarkerConfiguration.getConfiguation();
        Template tp = config.getTemplate(template);
        StringWriter stringWriter = new StringWriter();
        BufferedWriter writer = new BufferedWriter(stringWriter);
        tp.setEncoding("UTF-8");
        tp.process(dataMap, writer);
        String htmlStr = stringWriter.toString();
        writer.flush();
        writer.close();
        return htmlStr;
    }
}

 

PdfGenerator.java

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Map;
import java.util.UUID;

/**
 * @author LewJun
 * @version v0.1 2018/10/16 17:21 LewJun Exp $$
 */
public class PdfGenerator {
    private static String              RESOURCESPATH;
    private static ConverterProperties props;

    static {
        RESOURCESPATH = PdfGenerator.class.getResource("/").getPath();

        DefaultFontProvider fontProvider = new DefaultFontProvider();
        try {
            // 方式1
//            PdfFont f2 = PdfFontFactory.createFont(RESOURCESPATH + "templates/base/font/simhei.ttf",
//                    PdfEncodings.IDENTITY_H,true);
//        方式2 使用ttf字体
//        String fontPath = RESOURCESPATH + "templates/base/font/simhei.ttf";
//        fontProvider.addFont(fontPath);

            // 方式3 使用ttc字体
            PdfFont ttcFont = PdfFontFactory.createTtcFont(RESOURCESPATH + "templates/base/font/SIMSUN.TTC", 1,
                    PdfEncodings.IDENTITY_H, false, true);
            fontProvider.addFont(ttcFont.getFontProgram());
        } catch (IOException e) {
            e.printStackTrace();
        }
        props = new ConverterProperties();
        props.setFontProvider(fontProvider);
    }

    public static InputStream generate(String tpl, Map dataMap) throws Exception {
        String htmlStr = HtmlGenerator.generate(tpl, dataMap);
        File tmpPdfFile = File.createTempFile(System.currentTimeMillis() + "", ".pdf");
        File tmpHtmlFile = new File(RESOURCESPATH + UUID.randomUUID().toString() + ".html");
        OutputStream outfile = new FileOutputStream(tmpHtmlFile);
        IOUtils.write(htmlStr, outfile);
        IOUtils.closeQuietly(outfile);
        HtmlConverter.convertToPdf(tmpHtmlFile, tmpPdfFile, props);
        return new FileInputStream(tmpPdfFile);
    }
}

 

PrintServlet.java

response.setCharacterEncoding("utf-8");
            response.setContentType("application/pdf");
            response.addHeader(
                    "Content-Disposition",
                    "attachment; filename="
                            + String.format("%s.pdf",
                            Long.toString(System.currentTimeMillis())));
            out = response.getOutputStream();

            Map dataMap = new HashMap<>();
            dataMap.put("img1", "/templates/base/images/aloner.jpg");
            dataMap.put("img2", "http://mmbiz.qpic.cn/mmbiz/PiajxSqBRaEIQxibpLbyuSK8jCzLMb60WcYoLMD3nrCodIwbPeds9WFXYcEQapJ88EE4vfAwufMZWH1ZdC49HiaSg/0?wx_fmt=png");
            File tempFile = File.createTempFile(System.currentTimeMillis() + "", ".jpg");
            IOUtils.copy(new FileInputStream("d:/jing.png"), new FileOutputStream(tempFile));
            dataMap.put("img3", tempFile.getPath());
            dataMap.put("emp", new Emp(111, new Date(), 22));
            dataMap.put("empList", CollectionUtil.newArrayList(
                    new Emp(111, new Date(), 234),
                    new Emp(222, new Date(), 523452),
                    new Emp(333, new Date(), 534),
                    new Emp(444, new Date(), 4645),
                    new Emp(555, new Date(), 6456)
                    )
            );

            IOUtils.copy(PdfGenerator.generate("hello/tpl/hello2.ftl", dataMap), out);

 

 

  • 使用iText_7_生成pdf.zip (3.3 KB)
  • 下载次数: 24

你可能感兴趣的:(iText7,pdf,中文乱码)