【itext学习之路】-------(第七篇)将html转成pdf(解决中文不显示)

2024-04-15 16:08

本文主要是介绍【itext学习之路】-------(第七篇)将html转成pdf(解决中文不显示),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

版权声明:如需转载使用,请注明原文地址

在上一篇文章中,我们学习了使用对pdf进行盖章/签章/数字签名,到此为止,常用的pdf操作已经全部实现,但是实际开发中很多人比较喜欢将html转成pdf,本文介绍将html转pdf的方法(之前用的都是itext5,这次需要用到itext7中的html2pdf这个强大的组件)

  • 首先,先贴上代码之前一直使用的itext5的方式,将html转pdf(很多标签无法兼容)
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.ElementHandlerPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import com.jfinal.log.Log;
import com.jfinal.template.Engine;/** 
* @author 作者 : tomatocc
* pdf工具类
*/
public class PdfKit {private static Log log = Log.getLog(PdfKit.class);private PdfKit() {}/*** Creates a PDF with the words* * @param html* @param file* @throws IOException* @throws DocumentException*/public static void creatHtmlpdf(String html, String file) throws IOException, DocumentException {// step 1 new Document 默认大小A4Document document = new Document(PageSize.A4.rotate());// step 2PdfWriter.getInstance(document, new FileOutputStream(file));// step 3document.open();// step 4Paragraph context = new Paragraph();ElementList elementList = parseToElementList(html, null);for (Element element : elementList) {context.add(element);}document.add(context);// step 5document.close();}/*** 设置字体信息* @return*/private static Font getFontInf() {// 字体路径String fontPath =  PathKit.getWebRootPath() + "/WEB-INF/vm/font/simhei.ttf";BaseFont baseFont = null;Font font = null;try {// 设置字体路径,字体编码,是否将字体嵌入pdf(默认false)baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);// 设置默认字体数据font = new Font(baseFont, 12f,Font.NORMAL,BaseColor.BLACK);} catch (DocumentException e) {log.error("get pdf font info DocumentException " , e );} catch (IOException e) {log.error("get pdf font info IOException " , e );}return font;}/*** html转pdf 写法* @param html* @param css* @return* @throws IOException*/public static ElementList parseToElementList(String html, String css) throws IOException {// CSSCSSResolver cssResolver = new StyleAttrCSSResolver();if (css != null) {CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(css.getBytes()));cssResolver.addCss(cssFile);}// HTMLMyFontsProvider fontProvider = new MyFontsProvider();CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());htmlContext.autoBookmark(false);// PipelinesElementList elements = new ElementList();ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end);CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);// XML WorkerXMLWorker worker = new XMLWorker(cssPipeline, true);XMLParser p = new XMLParser(worker);html = html.replace("<br>", "").replace("<hr>", "").replace("<img>", "").replace("<param>", "").replace("<link>", "");p.parse(new ByteArrayInputStream(html.getBytes()));return elements;}static class MyFontsProvider extends XMLWorkerFontProvider {public MyFontsProvider() {super(null, null);}@Overridepublic Font getFont(final String fontname, String encoding, float size, final int style) {return getFontInf();}}public static void main(String[] args) throws IOException, DocumentException {Map<String, Object> paramMap = new HashMap<String, Object>();// pdf路径String file = "d:/test2.pdf";// 读取html模板String html = Engine.use().setBaseTemplatePath(PathKit.getWebRootPath()).getTemplate("WEB-INF/vm/test.html").renderToString(paramMap);PdfKit.creatHtmlpdf(html, file);}
}
  • 下面是html
<html>
<head>
<style>
.col {padding: 3px 20px 3px 20px
}
</style>
</head>
<body><div style="background:rgb(230,230,230); padding:5px ;border:1px solidblack;"><b style="color:rgb(51,153,255)">测试html</b></div><br /><table border="0" style='border-collapse: collapse;'><tr><td class="col">姓名:</td><td class="col">tomatocc</td></tr><tr><td class="col">年龄:</td><td class="col">0age</td></tr><tr><td class="col">性别:</td><td class="col">boy</td></tr><tr><td class="col">职业:</td><td class="col">段子手</td></tr></table><br /><br /><br /><hr /><br />
</body>
</html>
接下来我们使用itext7中的html2pdf来实现html转pdf
  1. 首先需要下载jar包 点击下载,maven项目用下面坐标即可。
		  <dependency><groupId>com.itextpdf</groupId><artifactId>html2pdf</artifactId><version>2.1.4</version></dependency>
  1. 下面是代码部分
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.layout.font.FontProvider;
import com.jfinal.log.Log;
import com.jfinal.template.Engine;/*** itext7中将html转pdf*/
public class Pdf7Kit {private static Log log = Log.getLog(Pdf7Kit.class);/*** 设置BaseFont* @param fontPath  字体路径* @return*/private static ConverterProperties creatBaseFont(String fontPath) {if(StrKit.isBlank(fontPath)) {fontPath =  PathKit.getWebRootPath() + "/WEB-INF/vm/font/simhei.ttf";}ConverterProperties properties = new ConverterProperties();FontProvider fontProvider = new DefaultFontProvider();FontProgram fontProgram;try {fontProgram = FontProgramFactory.createFont(fontPath);fontProvider.addFont(fontProgram);properties.setFontProvider(fontProvider);} catch (IOException e) {log.error("creat base font erro" , e );}return properties;}/*** 将html文件转换成pdf* @param htmlPath* @param pdfPath* @param fontPath* @throws IOException*/public static void creatPdf(String htmlPath , String pdfPath,String fontPath) throws IOException {if(StrKit.isBlank(htmlPath) || StrKit.isBlank(pdfPath)) {log.warn("html2pdf fail. htmlPath or pdfPath is null .");return;}// 拼接html路径String src = PathKit.getWebRootPath() + htmlPath;ConverterProperties properties = creatBaseFont(fontPath);HtmlConverter.convertToPdf(new File(src), new File(pdfPath),properties);}/*** 通过模板创建pdf* @param html html路径* @param pdf 生成的pdf路径* @param font  字体文件路径* @param paramMap 参数* @throws IOException*/public static void creatPdfByTem(String html , String pdf,String font ,Map<String, Object> paramMap) throws IOException {if(StrKit.isBlank(html) || StrKit.isBlank(pdf)) {log.warn("html2pdf fail. htmlPath or pdfPath is null .");return;}// 拼接临时文件目录String srctmp = PathKit.getWebRootPath() + html + StrKit.genUuid(true);File file = new File(srctmp);// 使用文件模板Engine.use().setBaseTemplatePath(PathKit.getWebRootPath()).getTemplate(html).render(paramMap, srctmp);ConverterProperties properties = creatBaseFont(font);HtmlConverter.convertToPdf(file, new File(pdf),properties);// 删除临时文件if(file.exists()) {file.delete();}}public static void main(String[] args) throws IOException {String pdfPath = "d:/test1.pdf";Map<String, Object> paramMap = new HashMap<String, Object>();paramMap.put("name","tomatocc");String htmlPath =  "/WEB-INF/vm/test.html";// 使用html模板创建pdf// creatPdfByTem(htmlPath, pdfPath, null, paramMap);// 将html转换成pdfcreatPdf(htmlPath, pdfPath, null);}}

代码中写了两个方法,第一个是将html转为pdf,是比较简单的,第二种是用html模板,将html转换成pdf,我的模板引擎用的是jfinal模板引擎,其他模板引擎是类似的,需要注意的是HtmlConverter.convertToPdf方法的第一个参数必须是FIle类型,之前模板引擎后的返回值都是String,因此需要做代码改造即可。

这里需要说明一个情况,如果项目中不引入字体文件,那么生成的pdf将不会显示文字(因为生产环境的服务器不会有任何字体文件,而本地运行的话,会自动去电脑中的字体文件库中去寻找字体文件),因此,如果是需要发布的项目,务必将字体文件放到项目中,然后进行使用。

【itext学习之路】系列教程

【itext学习之路】-----(第一篇)创建一个简单的pdf文档
【itext学习之路】-----(第二篇)设置pdf的一些常用属性
【itext学习之路】-----(第三篇)对pdf文档进行加密和权限设置
【itext学习之路】-----(第四篇)给pdf增加文本水印和图片水印
【itext学习之路】-----(第五篇)对pdf进行盖章/签章/数字签名
【itext学习之路】-----(第六篇)将html转成pdf(解决中文不显示)

欢迎关注本人个人公众号,交流更多技术信息

在这里插入图片描述

这篇关于【itext学习之路】-------(第七篇)将html转成pdf(解决中文不显示)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

vite搭建vue3项目的搭建步骤

《vite搭建vue3项目的搭建步骤》本文主要介绍了vite搭建vue3项目的搭建步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1.确保Nodejs环境2.使用vite-cli工具3.进入项目安装依赖1.确保Nodejs环境

Nginx搭建前端本地预览环境的完整步骤教学

《Nginx搭建前端本地预览环境的完整步骤教学》这篇文章主要为大家详细介绍了Nginx搭建前端本地预览环境的完整步骤教学,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录项目目录结构核心配置文件:nginx.conf脚本化操作:nginx.shnpm 脚本集成总结:对前端的意义很多

IDEA和GIT关于文件中LF和CRLF问题及解决

《IDEA和GIT关于文件中LF和CRLF问题及解决》文章总结:因IDEA默认使用CRLF换行符导致Shell脚本在Linux运行报错,需在编辑器和Git中统一为LF,通过调整Git的core.aut... 目录问题描述问题思考解决过程总结问题描述项目软件安装shell脚本上git仓库管理,但拉取后,上l

前端缓存策略的自解方案全解析

《前端缓存策略的自解方案全解析》缓存从来都是前端的一个痛点,很多前端搞不清楚缓存到底是何物,:本文主要介绍前端缓存的自解方案,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、为什么“清缓存”成了技术圈的梗二、先给缓存“把个脉”:浏览器到底缓存了谁?三、设计思路:把“发版”做成“自愈”四、代码

通过React实现页面的无限滚动效果

《通过React实现页面的无限滚动效果》今天我们来聊聊无限滚动这个现代Web开发中不可或缺的技术,无论你是刷微博、逛知乎还是看脚本,无限滚动都已经渗透到我们日常的浏览体验中,那么,如何优雅地实现它呢?... 目录1. 早期的解决方案2. 交叉观察者:IntersectionObserver2.1 Inter

解决docker目录内存不足扩容处理方案

《解决docker目录内存不足扩容处理方案》文章介绍了Docker存储目录迁移方法:因系统盘空间不足,需将Docker数据迁移到更大磁盘(如/home/docker),通过修改daemon.json配... 目录1、查看服务器所有磁盘的使用情况2、查看docker镜像和容器存储目录的空间大小3、停止dock

Vue3视频播放组件 vue3-video-play使用方式

《Vue3视频播放组件vue3-video-play使用方式》vue3-video-play是Vue3的视频播放组件,基于原生video标签开发,支持MP4和HLS流,提供全局/局部引入方式,可监听... 目录一、安装二、全局引入三、局部引入四、基本使用五、事件监听六、播放 HLS 流七、更多功能总结在 v

idea npm install很慢问题及解决(nodejs)

《ideanpminstall很慢问题及解决(nodejs)》npm安装速度慢可通过配置国内镜像源(如淘宝)、清理缓存及切换工具解决,建议设置全局镜像(npmconfigsetregistryht... 目录idea npm install很慢(nodejs)配置国内镜像源清理缓存总结idea npm in

Java高效实现PowerPoint转PDF的示例详解

《Java高效实现PowerPoint转PDF的示例详解》在日常开发或办公场景中,经常需要将PowerPoint演示文稿(PPT/PPTX)转换为PDF,本文将介绍从基础转换到高级设置的多种用法,大家... 目录为什么要将 PowerPoint 转换为 PDF安装 Spire.Presentation fo

idea突然报错Malformed \uxxxx encoding问题及解决

《idea突然报错Malformeduxxxxencoding问题及解决》Maven项目在切换Git分支时报错,提示project元素为描述符根元素,解决方法:删除Maven仓库中的resolv... 目www.chinasem.cn录问题解决方式总结问题idea 上的 maven China编程项目突然报错,是