SpringBoot将HTML转化成PDF文件

  1. 准备好相关字体文件(如果HTML内含有中文,避免乱码)。我这边用的是谷歌免费的中文字体,源于:Gitee 极速下载/noto-cjk - Gitee.com(在此表示感谢)

  2. 准备好一个HTML文件(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. 依赖

      html 复制代码
      <dependency>
          <groupId>com.openhtmltopdf</groupId>
          <artifactId>openhtmltopdf-pdfbox</artifactId>
          <version>1.0.10</version>
      </dependency>
    2. 代码

    java 复制代码
    // 支持中文的字体路径(需要提前准备好中文字体文件)
    // 字体相对地址
    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. 结果

相关推荐
小强库计算机毕业设计1 小时前
SpringBoot+Vue3 学生宿舍管理系统实战
java·spring boot·后端·vue·学生宿舍管理系统
zh_xuan5 小时前
github搭建个人主页
html·github
2601_963906786 小时前
可自由切割与合并的 PDF 尺寸调整与打印工具
pdf
2601_965912917 小时前
PDF转Word与拆分组合操作实测:从格式保真到批量处理的方案对比
pdf·word
小妖6668 小时前
设置了 box-sizing: border-box; 不管用,下边框还是被挤压没了
前端·css·html
海兰10 小时前
【应用】ClawPDF 完全指南:安装、部署与使用
人工智能·pdf·openclaw
XLYcmy11 小时前
PDF论文处理器 - 功能总结
数据库·python·pdf·csv·pymupdf·dify·文本分割
阿伟玩不懂12 小时前
AI帮你读PDF——自建文档解析与智能问答工具
人工智能·pdf
Flittly1 天前
【雕虫大技】Agent 动态 Skill 供应链安全加固(三):输出校验与治理闭环实战
java·spring boot·spring
鬼手点金1 天前
Scrapy 网络爬虫框架
爬虫·python·scrapy·ajax·html·json·requsts