首页 前端知识 SpringBoot 将 Html 导出为 Pdf

SpringBoot 将 Html 导出为 Pdf

2024-06-13 21:06:55 前端知识 前端哥 917 874 我要收藏

1. 项目目录

在这里插入图片描述

2. pom.xml

<!-- html 转 pdf -->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>html2pdf</artifactId>
	<version>3.0.2</version>
</dependency>
<!-- 中文字体支持 -->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>font-asian</artifactId>
	<version>7.1.13</version>
</dependency>
<!-- 流处理 -->
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.11.0</version>
</dependency>
<!-- 读取 resource 目录下文件 -->
<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">
<head>
    <meta charset="UTF-8">
    <title>测试标题</title>
</head>
<body>
cnbai
</body>
</html>

7. 字体文件

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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/12023.html
标签
评论
发布的文章

JQuery函数 | 选择器 | 事件

2024-06-20 00:06:11

双X轴的Echarts图

2024-06-20 00:06:08

在Vue3中使用echarts图表

2024-06-20 00:06:07

将echarts封装为js文件

2024-06-20 00:06:04

利用Echarts画地图和飞线

2024-06-20 00:06:03

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!