【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、中文乱码处理

  1. 上传windows7的中文字体库(SimSun.ttf)至指定路径
    在这里插入图片描述

  2. ftl设置中文名称
    在这里插入图片描述

  3. 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值