java将ftl转换成pdf,vue对转换的pdf进行预览、打印、下载
1、ftl模板依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、ftl转换pdf
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-core</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-slf4j</artifactId>
<version>1.0.10</version>
</dependency>
2.1、flt转pdf字节数组核心代码块
// 模板加载
Configuration conf = new Configuration(Configuration.VERSION_2_3_23);
conf.setDefaultEncoding(StandardCharsets.UTF_8.name());
conf.setDateTimeFormat(TimeUtil.NORMAL_TIME_FORMAT);
conf.setClassForTemplateLoading(getClass(), "/template/");
try {
Template template = conf.getTemplate("scenePreview.ftl");
// 参数与模板生成html字符串
String htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template, dto);
// html转换pdf
try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(htmlStr, "");
// 读取系统字体 若没有对应字体 则会出现中文字体乱码问题
if (FileUtil.exist(fontUrl)) {
builder.useFont(new FSSupplier<InputStream>() {
@SneakyThrows
@Override
public InputStream supply() {
return Files.newInputStream(Paths.get(fontUrl));
}
}, fontName);
} else {
log.error("中文字体缺失,对应文件路径为:{}", fontUrl);
}
builder.toStream(os);
builder.run();
byte[] bytes = os.toByteArray();
return new ResponseEntity<>(bytes, HttpStatus.OK);
}
} catch (IOException e) {
log.error("凭证查看异常,", e);
} catch (TemplateException e) {
log.error("凭证查看模板异常,", e);
}
2.2、得到ftl转换成pdf的字节数组
2.3、中文乱码处理
-
上传windows7的中文字体库(SimSun.ttf)至指定路径
-
ftl设置中文名称
-
flt转换pdf指定字体配置
3、转换后的PDF添加水印和页脚
<!-- 页脚和水印 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
3.1 水印效果
3.2、水印及页脚添加核心代码块
/**
* 添加页脚和水印
*
* @param bytes 输入文件流对象
* @param waterContent 水印内容
* @return 响应结果
*/
private byte[] addFooter(byte[] bytes, String footerContent, String waterContent) throws IOException {
PDDocument document = PDDocument.load(bytes);
try(InputStream fontInput = new FileInputStream(fontUrl)){
PDFont font = PDType0Font.load(document, fontInput, false);
for (in