使用freemarker和itextpdf结合,将html转化为pdf

2024-02-05 08:44

本文主要是介绍使用freemarker和itextpdf结合,将html转化为pdf,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

工作中遇到模板中的html,需要转化成pdf作为附件上传到系统

于是经过研究分析,得出用freemarker和itextpdf结合

maven需要导入包:

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>${itextpdf.version}</version></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.5.8</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>

新建FreemarkerUtils工具类

package com.example.common.util;import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import freemarker.core.HTMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;import com.itextpdf.tool.xml.XMLWorkerHelper;@Component
@Slf4j
public class FreemarkerUtils {@Resourceprivate Configuration stringConfiguration;private static final String FONT = "fonts/simhei.ttf";/*** 根据模板构建* @param content 模板内容* @param dataModel 模板数据**/public String buildByTemplate(String content, Map<String,Object> dataModel){return buildByTemplate(content, dataModel, StrUtil.EMPTY);}/*** 根据模板替换变量,得到变量替换后的内容* @param content 模板内容* @param dataModel 模板数据* @param defaultString 构建失败返回的默认值**/public String buildByTemplate(String content, Map<String,Object> dataModel,String defaultString) {try {
//            stringConfiguration.setOutputFormat(HTMLOutputFormat.INSTANCE);return FreeMarkerTemplateUtils.processTemplateIntoString(new Template("", content,   stringConfiguration),dataModel);}catch (Exception e){log.warn("解析模板失败", e);}return defaultString;}public void htmlToPdf(String content) {// 创建一个Document对象Document document = new Document();try {// 创建一个PdfWriter实例来写PDF文件PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(Paths.get("E:\\张三测试.pdf")));// 打开文档document.open();InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));FontProviderUtil fontProviderUtil = new FontProviderUtil();// 读取HTML文件并将其转换为PDFXMLWorkerHelper.getInstance().parseXHtml(writer, document,inputStream, null, StandardCharsets.UTF_8, fontProviderUtil);// 关闭文档document.close();} catch (DocumentException | IOException e) {e.printStackTrace();}}}

 解决中文乱码和生成的pdf中文不显示问题

package com.example.common.util;import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import lombok.extern.slf4j.Slf4j;/*** 字体*/
@Slf4j
public class FontProviderUtil extends XMLWorkerFontProvider {/*** 黑体 常规**/public static final String SIMHEI_TTF = "fonts/simhei.ttf";/*** 解决乱码和中文在pdf不显示问题* @param fontname    the name of the font* @param encoding    the encoding of the font* @param embedded    true if the font is to be embedded in the PDF* @param size	    the size of this font* @param style	    the style of this font* @param color	    the <CODE>BaseColor</CODE> of this font.* @param cached 		true if the font comes from the cache or is added to* 				the cache if new, false if the font is always created new* @return*/@Overridepublic Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color, boolean cached) {BaseFont bf = null;try {bf = BaseFont.createFont(SIMHEI_TTF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);} catch (Exception e) {log.info(e.getMessage());e.printStackTrace();}Font font = new Font(bf, size, style, color);font.setColor(color);return font;}}

在业务层调用即可

  freemarkerUtils.htmlToPdf(content);

这篇关于使用freemarker和itextpdf结合,将html转化为pdf的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/680359

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali