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. 结果

相关推荐
一 乐3 小时前
家政服务管理系统|基于springboot + vue家政服务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家政服务管理系统
xinhuanjieyi4 小时前
html修复游戏种太阳错误
前端·游戏·html
Sour5 小时前
【无标题】aPPT 翻译后保留版式的流程:文本框、图片、母版和动画检查
pdf·powerpoint
无心水6 小时前
27、私有化部署|PaddleOCR-Server 本地OCR服务搭建
金融·pdf·ocr·pdf解析·pdf抽取·pdf提取·ocr服务
LaughingZhu7 小时前
Product Hunt 每日热榜 | 2026-06-11
人工智能·经验分享·神经网络·html·产品运营
老马聊技术7 小时前
AI对话功能之SpringBoot整合Vue3
vue.js·人工智能·spring boot·后端
码不停蹄的玄黓8 小时前
SpringBoot 全局异常处理器实现
java·spring boot·后端
可乐ea10 小时前
【Spring Boot + MyBatis|第7篇】JWT 登录认证与拦截器实现
java·spring boot·后端·mybatis·状态模式
ShyanZh10 小时前
【skill】HTML PPT Skill:用 Claude Code 一句话生成专业演示文稿
前端·ai·html·powerpoint·skill
我登哥MVP11 小时前
SpringCloud Alibaba 核心组件解析:服务注册与发现(Nacos)
java·spring boot·后端·spring·spring cloud·java-ee·maven