SpringBoot将HTML转化成PDF文件

发布于:2025-04-10 ⋅ 阅读:(37) ⋅ 点赞:(0)
  1. 准备好相关字体文件(如果HTML内含有中文,避免乱码)。我这边用的是谷歌免费的中文字体,源于:Gitee 极速下载/noto-cjk - Gitee.com(在此表示感谢)
  2. 准备好一个HTML文件(HTML标签记得封好),在HTML内字体也需要设置相同的谷歌免费字体
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8"/>
        <title>PDF Example</title>
        <style>
            body {
                // 设置字体样式
                font-family: Noto Sans SC, serif;
            }
        </style>
    </head>
    <body>
    <h1>这是一个测试标题</h1>
    <p>这是一段包含中文的文字内容。</p>
    </body>
    </html>
  3. 在spring boot中实现
    1. 依赖
      <dependency>
          <groupId>com.openhtmltopdf</groupId>
          <artifactId>openhtmltopdf-pdfbox</artifactId>
          <version>1.0.10</version>
      </dependency>

    2. 代码
    // 支持中文的字体路径(需要提前准备好中文字体文件)
    // 字体相对地址
    String htmlContent = Files.readString(Paths.get(htmlPath, "test2.html"));
    System.out.println(htmlContent);
    String outputFilePath = Paths.get(outputPath, "output.pdf").toString();
    OutputStream outputStream = new FileOutputStream(outputFilePath);
    PdfRendererBuilder builder = new PdfRendererBuilder();
    builder.useFastMode(); // 启用快速模式
    builder.withHtmlContent(htmlContent, null);
    builder.useFont(new File('字体绝对地址'),"Noto Sans SC");
    builder.toStream(outputStream);
    builder.run();

        4. 结果