< dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-web </ artifactId > < version > 2.6.3 </ version > </ dependency >

3. 创建 Service

TestService

package com.cnbai.service;
import com.cnbai.utils.HtmlToPdfUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
 * 根据 html 文件生成 pdf 文件
public class TestService {
    /** html 文件路径 */
    private static final String HTML_PATH = "html/test.html";
    /** 项目所在路径 */
    private static final String PATH = System.getProperty("user.dir");
    public static void main(String[] args) {
        try {
            String path = generatePdf(HTML_PATH);
            System.out.println("文件路径:" + path);
        } catch (Exception e) {
            e.printStackTrace();
     * 生成 pdf 文件
    private static String generatePdf(String path) throws Exception {
        String pdfDirPath = PATH + File.separator + "pdf" + File.separator;
        File file = new File(pdfDirPath);
        if (!file.exists()) {
            file.mkdirs();
        String pdfPath = pdfDirPath + "测试.pdf";
        ClassPathResource classPathResource = new ClassPathResource(path);
        InputStream inputStream = classPathResource.getInputStream();
        OutputStream outputStream = new FileOutputStream(pdfPath);
        HtmlToPdfUtils.convertToPdf(inputStream, outputStream);
        return pdfPath;

4. 创建工具类

HtmlToPdfUtils

package com.cnbai.utils;
import com.cnbai.pdf.WaterMarkEventHandler;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import org.springframework.core.io.ClassPathResource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 * 使用 itext7 将 html 生成 pdf
public class HtmlToPdfUtils {
    /** 自定义水印 */
    private static final String WATERMARK_TEXT = "cnbai";
    /** 自定义字体路径,ttc后缀的字体需要添加 -> ,0 */
    private static final String FONT_PATH = "/font/simsun.ttc";
     * html 转 pdf
     * @param inputStream  输入流
     * @param outputStream 输出流
    public static void convertToPdf(InputStream inputStream, OutputStream outputStream) throws IOException {
        PdfWriter pdfWriter = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        // 设置为 A4 大小
        pdfDocument.setDefaultPageSize(PageSize.A4);
        // 添加水印
        pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarkEventHandler(WATERMARK_TEXT));
        // 添加中文字体支持
        ConverterProperties properties = new ConverterProperties();
        FontProvider fontProvider = new FontProvider();
        // 添加自定义字体, 例如宋体
        ClassPathResource classPathResource = new ClassPathResource(FONT_PATH);
        String fontPath = classPathResource.getPath() + ",0";
        PdfFont microsoft = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, false);
        fontProvider.addFont(microsoft.getFontProgram(), PdfEncodings.IDENTITY_H);
        properties.setFontProvider(fontProvider);
        // 读取 Html 文件流,查找出当中的 &nbsp; 或出现类似的符号空格字符
        inputStream = readInputStream(inputStream);
        if (inputStream != null) {
            // 生成 pdf 文档
            HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
            pdfWriter.close();
            pdfDocument.close();
        } else {
            System.out.println("转换失败!");
     * 读取 HTML 流文件,并查询当中的 &nbsp; 或类似符号,并将其替换为空格
    private static InputStream readInputStream(InputStream inputStream) {
        try {
            // 1. 创建字节数组输出流,用来输出读取到的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 2. 创建缓存大小,1KB
            byte[] buffer = new byte[1024];
            int len; // 每次读取到内容的长度
            // 3. 开始读取输入流中的内容
            while ((len = inputStream.read(buffer)) != -1) { // 当等于 -1 说明没有数据可以读取了
                baos.write(buffer, 0, len);   // 把读取到的内容写到输出流中
            // 4. 把字节数组转换为字符串
            String content = baos.toString();
            // 5. 关闭输入流和输出流
            inputStream.close();
            baos.close();
            // 6. 判断 HTML 内容是否具有 HTML 的特殊字符标记
            Pattern compile = Pattern.compile("&[a-zA-Z]{1,10};", Pattern.CASE_INSENSITIVE);
            Matcher matcher = compile.matcher(content);
            String replaceAll = matcher.replaceAll("");
            // 7. 将字符串转化为输入流返回
            return getStringStream(replaceAll);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
     * 将一个字符串转化为输入流
    private static InputStream getStringStream(String sInputString) {
        if (sInputString != null && !sInputString.trim().equals("")) {
            try {
                return new ByteArrayInputStream(sInputString.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
        return null;

5. 创建配置类

PageEventHandler

package com.cnbai.pdf;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import java.io.IOException;
 * 生成 pdf 页码设置
public class PageEventHandler implements IEventHandler {
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
        PdfDocument document = documentEvent.getDocument();
        PdfPage page = documentEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfFont pdfFont = null;
        try {
            pdfFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        } catch (IOException e) {
            e.printStackTrace();
        PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), document);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);
        float  x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        float  y = pageSize.getBottom() + 15;
        Paragraph paragraph = new Paragraph("第" + document.getPageNumber(page) + "页/共" + document.getNumberOfPages() + "页")
                .setFontSize(10)
                .setFont(pdfFont);
        canvas.showTextAligned(paragraph, x, y, TextAlignment.CENTER);
        canvas.close();

WaterMarkEventHandler

package com.cnbai.pdf;
import com.itextpdf.kernel.colors.WebColors;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import java.io.IOException;
 * 生成 pdf 设置水印
public class WaterMarkEventHandler implements IEventHandler {
     * 水印内容
    private final String waterMarkContent;
     * 一页中有几列水印
    private final int waterMarkX;
     * 一页中每列有多少水印
    private final int waterMarkY;
    public WaterMarkEventHandler(String waterMarkContent) {
        this(waterMarkContent, 5, 5);
    public WaterMarkEventHandler(String waterMarkContent, int waterMarkX, int waterMarkY) {
        this.waterMarkContent = waterMarkContent;
        this.waterMarkX = waterMarkX;
        this.waterMarkY = waterMarkY;
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
        PdfDocument document = documentEvent.getDocument();
        PdfPage page = documentEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfFont pdfFont = null;
        try {
            pdfFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        } catch (IOException e) {
            e.printStackTrace();
        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), document);
        Paragraph waterMark = new Paragraph(waterMarkContent).setOpacity(0.5f);
        Canvas canvas = new Canvas(pdfCanvas, pageSize)
                .setFontColor(WebColors.getRGBColor("lightgray"))
                .setFontSize(16)
                .setFont(pdfFont);
        for (int i = 0; i < waterMarkX; i++) {
            for (int j = 0; j < waterMarkY; j++) {
                canvas.showTextAligned(waterMark, (150 + i * 300), (160 + j * 150), document.getNumberOfPages(), TextAlignment.CENTER, VerticalAlignment.BOTTOM, 120);
        canvas.close();

6. 创建 Html 文件

test.html

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>测试标题</title>
</head>
cnbai
</body>
</html>

7. 字体文件

字体文件在本地 windows 拷贝出来,放在图中目录下

用到的工具类: 通过这个工具类来讲html换为pdf,可先用main方法进行测试。以上是html模板 ,要求html遵守xhtml的规范,严格语法要求。vm模板: 使用此模板来进行渲染。然后下面是引用的maven坐标。 在我们日常开发中,经常会遇到导出pdf这种需求,比如导出合同、导出业务报告等。这中导出功能都有一个特点,导出pdf中有大量相同的文本布局以及样式,只有涉及到用户本人的信息时出现不同的内容。我们把这些相同的部分称作模版,在模版中放置一些变量来代表用户信息,比如用户姓名、年龄等。这样我们在导出pdf的时候,在数据库中把用户信息查出来,对模版中对应的变量进行替换,再把替换的结果pdf文件就可以了。模版的类型有很多种:html模版、doc模版、excel模版、pdf模版等等。