java 使用itext7 将HTML转PDF

本文的目的

前两篇文章介绍了velocity模板引擎,我们可以使用velocity模板引擎生成复杂的HTML(图片、文字等),然后将HTML转成样式完全一样的PDF文件
Java使用 VelocityEngine模板引擎快速生成HTML等各种代码
Velocity模板引擎实战:动态生成HTML、Word、Excel等报表

一、引入pom

<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>itext7-coreartifactId>
    <version>7.1.0version>
    <type>pomtype>
dependency>

<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>html2pdfartifactId>
    <version>2.0.0version>
dependency>

<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-ioartifactId>
    <version>1.3.2version>
dependency>

二、下载字体

另存图片到本地,将后缀改为.rar或.zip使用压缩软件解压得到字体
当然也可以在Windows系统下,控制面板—>右上角点击大图标—>字体—>里面有很多字体可以复制出来使用

三、使用方式

1、工具类
package utils;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.attach.impl.DefaultTagWorkerFactory;
import com.itextpdf.kernel.Version;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.font.FontProvider;
import org.apache.commons.io.FileUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;

public class PdfService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PdfFromHTML.class);
    public static final String RESOURCE_PREFIX_INDEX = "C:/Users/Admin/Desktop";
    public static final String FONT_NAME = "msyh.ttf";
    private static final String FONT_CLASS_PATH = "font/msyh.ttf";

    public void copyFont(String dirStr) {
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(FONT_CLASS_PATH);
            File dir = new File(dirStr);
            FileUtils.forceMkdir(dir);
            FileOutputStream fout = new FileOutputStream(dirStr + "msyh.ttf");
            if (inputStream != null && fout != null) {
                org.apache.commons.io.IOUtils.copy(inputStream, fout);
            }
        } catch (Exception e) {
            LOGGER.error("failed to copy font: ", e);
            e.printStackTrace();
        }
    }

    public void createPdfFromHtml(String pdfFileName, InputStream htmlInputStream, String resourcePrefix) {
        PdfDocument pdfDoc = null;
        try {
            FileOutputStream outputStream = new FileOutputStream(resourcePrefix + pdfFileName);
            WriterProperties writerProperties = new WriterProperties();
            writerProperties.addXmpMetadata();
            PdfWriter pdfWriter = new PdfWriter(outputStream, writerProperties);
            pdfDoc = createPdfDoc(pdfWriter);
            ConverterProperties props = createConverterProperties(resourcePrefix);
            HtmlConverter.convertToPdf(htmlInputStream, pdfDoc, props);
        } catch (Exception e) {
            LOGGER.error("failed to create pdf from html exception: ", e);
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(pdfDoc);
        }

    }
    private PdfDocument createPdfDoc(PdfWriter pdfWriter) {
        PdfDocument pdfDoc;
        pdfDoc = new PdfDocument(pdfWriter);
        pdfDoc.getCatalog().setLang(new PdfString("zh-CN"));
        pdfDoc.setTagged();
        pdfDoc.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));
        return pdfDoc;
    }
    private ConverterProperties createConverterProperties(String resourcePrefix) {
        ConverterProperties props = new ConverterProperties();
        props.setFontProvider(createFontProvider(resourcePrefix));
        props.setBaseUri(resourcePrefix);
        props.setCharset("UTF-8");
        DefaultTagWorkerFactory tagWorkerFactory = new DefaultTagWorkerFactory();
        props.setTagWorkerFactory(tagWorkerFactory);
        return props;
    }

    private FontProvider createFontProvider(String resourcePrefix) {
        FontProvider fp = new FontProvider();
        fp.addStandardPdfFonts();
        fp.addDirectory(resourcePrefix);
        return fp;
    }
}
2、使用方式
import org.apache.commons.io.FileUtils;
import utils.PdfService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Created by JackieLee on 2018/3/21.
 *
 * @author 李智龙
 * @date 2018/3/21
 */
public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        PdfService pdfService = new PdfService();
        String timeFile = System.currentTimeMillis() + "";
        String tempFile = PdfService.RESOURCE_PREFIX_INDEX + "/" + timeFile + "/";
        createDirs(timeFile);
        // 添加字体,这一步很关键,否则中文会显示不出来
        pdfService.copyFont(tempFile);
        FileInputStream inputStream = new FileInputStream("C:/Users/Admin/Desktop/demo.html");
        File pdfFile = createFlawPdfFile(tempFile, "demo");
        pdfService.createPdfFromHtml(pdfFile.getName(), inputStream, tempFile);
    }
    /**
     * 新建文件夹
     * @param dirsPath
     */
    private static void createDirs(String dirsPath) {
        File temFile = new File(dirsPath);
        if (!temFile.exists()) {
            temFile.mkdirs();
        }
    }
    /**
     * 创建漏洞pdf版本空文件
     * @param fileDir
     * @param fileName
     * @return
     */
    private static File createFlawPdfFile(String fileDir, String fileName) {
        File tempFile;
        do {
            tempFile = new File(fileDir + fileName + ".pdf");
        } while (tempFile.exists());
        return tempFile;
    }
}
3、源文件demo.html

java 使用itext7 将HTML转PDF_第1张图片

4、转换文件

文件格式,注意字体也被拷贝到对应文件夹下
java 使用itext7 将HTML转PDF_第2张图片
文件内容java 使用itext7 将HTML转PDF_第3张图片

你可能感兴趣的:(java,后台开发)