SpringBoot将HTML转化成PDF文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值