Java程序输出PDF格式文件

使用模板引擎构建文档内容

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

设置变量并在Html中引用

Context context = new Context();
context.setVariable("var1", "变量1");
context.setVariable("var2", "变量2可以是对象");

编辑Html文件

<html lang="en" xmlns:th="http://www.thymelead.org">
thymeleaf语法
<span th:text="${var1}"/>
循环
<span th:each="item,state:${var-list}">
集合序号
  <span th:text="${state.index + 1}"/>
循环的值  
  <span th:text="${item}"/>
</span>
IF判断变量不为空
<span th:if="${var1 != null}"/>

模板引擎获取Html文件
文件位置:resources/templates/test.html

@Resource
private TemplateEngine templateEngine;
String html = templateEngine.process("test.html", context);

Itextpdf转Html为PDF

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>5.0.5</version>
</dependency>

这里字体文件可在 C:\Windows\Fonts 下复制

private static final String[] FONTS = {"simfang.ttf","simhei.ttf"};

public static void htmlToPdf(String html, OutputStream outputStream) {
    try {
            FontProvider fontProvider = new FontProvider();
            for (String font : FONTS) {
                InputStream inputStream = new ClassPathResource("/fonts/" + font).getInputStream();
                byte[] bytes = IOUtils.toByteArray(inputStream);
                fontProvider.addFont(bytes);
            }

            fontProvider.addSystemFonts();
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setFontProvider(fontProvider);

            HtmlConverter.convertToPdf(html, outputStream, converterProperties);
        } catch (Exception e) {
            log.error("Html转PDF发生异常", e);
        }
}

解决字体问题

@font-face {
    font-family: 'Simhei';
    src: url("/fonts/simhei.ttf");
}

body {
    font-family: Simhei;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值