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

相关推荐
程序员张32 小时前
Maven编译和打包插件
java·spring boot·maven
灵犀学长3 小时前
EasyExcel之SheetWriteHandler:解锁Excel写入的高阶玩法
spring boot·excel
zwjapple4 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
Eiceblue5 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
AA-代码批发V哥6 小时前
HTML之语义化标签与多媒体标签
html
像风一样自由20206 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
DuelCode7 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
优创学社27 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理7 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
猴哥源码7 小时前
基于Java+springboot 的车险理赔信息管理系统
java·spring boot