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

来源:【itext学习之路】-------(第七篇)将html转成pdf(解决中文不显示)_tomatocc的博客-CSDN博客

在上一篇文章中,我们学习了使用对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将不会显示文字(因为生产环境的服务器不会有任何字体文件,而本地运行的话,会自动去电脑中的字体文件库中去寻找字体文件),因此,如果是需要发布的项目,务必将字体文件放到项目中,然后进行使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/496202.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows 安装 MongoDB 和 可视化工具Robo3T

MongoDB 官网下载地址&#xff1a;https://www.mongodb.com/try/download/community MongoDB 是一款非常热门的 NoSQL 面向文档的数据库管理系统&#xff0c; 分为 企业版收费版 和 社区免费版。MongoDB 使用 BSON 对象来存储&#xff0c;与 JSON 格式类型的 "键 - 值&quo…

【Vegas原创】VMWare安装Linux5的注意事项

1&#xff0c;VMWare版本需在6.5及以上。否则&#xff0c;在Linux桥接网络时&#xff0c;不能成功。 2&#xff0c;VMWare增强工具的安装问题请参看&#xff1a;http://www.cnblogs.com/vegaslee/archive/2009/09/22/1571671.html 3&#xff0c;VMWare下Linux的使用请参看&…

量子计算生态:市场预期、行业应用与“霸权”争夺

来源&#xff1a;资本实验室从IBM宣布推出业界首个商用量子计算系统&#xff0c;到我国开通全球首条量子通信干线并成功实现首次洲际量子通信&#xff0c;2017年的量子计算领域精彩不断&#xff0c;并不断提升市场对量子计算的预期。除了应用于国防安全&#xff0c;在科研、医疗…

linux下能运行python,(转)Linux下运行python

原文&#xff1a; http://blog.csdn.net/jackywgw/article/details/48847187在linux命令行下运行python&#xff0c;可以直接输出hello worldjackywgwjackywgw-A8F:~/python_learning$ pythonPython 3.3.6 (default, Apr 17 2015, 00:20:01)[GCC 4.9.2] on linuxType "hel…

xhtmlrenderer + iText-HTML转PDF

来源&#xff1a;xhtmlrenderer iText-HTML转PDF_hunan961的博客-CSDN博客_xhtmlrenderer xhtmlrendereitext2.0.8 将html转成pdf&#xff0c;带样式、图片(也支持二维码、条形码)等 主要步骤 生成html&#xff08;css样式直接放在style中&#xff09;html转换pdf方法数据返…

Ubuntu 防火墙 ufw

UbuntuHelp:UFW &#xff1a;http://wiki.ubuntu.org.cn/UbuntuHelp:UFW Ufw使用指南&#xff1a;http://wiki.ubuntu.org.cn/Ufw使用指南 ubuntu ufw防火墙&#xff1a;http://wap.dongnanshan.com/fn.php?subuntu ufw防火墙 UFW要领&#xff1a;通用防火墙规则和命令&#x…

NASA打算送机器蜜蜂去探索火星上的生命痕迹

来源&#xff1a;国际智能机器人用机械昆虫做侦察兵是科幻电影里存在了多年的场景&#xff0c;如今现实中已经有科学家在做这件事&#xff0c;譬如用机械蜜蜂探索太空。NASA最近就花了12.5万美元资助一个名为“Marsbees”的火星探测工具的科研项目。“Marsbees”是一款微型机器…

linux usb 驱动漏洞,不测不知道 这么多的USB漏洞要从何“补”起?

原标题&#xff1a;不测不知道 这么多的USB漏洞要从何“补”起?[PConline 杂谈]生活中&#xff0c;USB接口可以说无处不在&#xff0c;路由器、打印机、投影机、PC电脑、台式机等等&#xff0c;且使用频率极高。当然&#xff0c;作为硬件设备的输入输出接口&#xff0c;其安全…

小虎队 - 情难枕

现场感很好。。。时间在不远的前方穿梭&#xff0c;走在街头看着形色匆匆赶路回家的人群&#xff0c;这个城市&#xff0c;无声无息的变化........ 在这个意义上已到成熟的年纪&#xff0c;在茶语谈笑间总会想起往日的欢愉&#xff0c;在每个80后成长的人&#xff0c;那些昔日…

xhtmlrenderer 将html转换成pdf,完美css,带图片,手动分页,解决内容断开的问题

来源&#xff1a;xhtmlrenderer 将html转换成pdf&#xff0c;完美css&#xff0c;带图片&#xff0c;手动分页&#xff0c;解决内容断开的问题 - 煮过的花朵 - 博客园 之前用itext7将html导出为pdf&#xff0c;比较方便&#xff0c;代码较少&#xff0c;而且支持base64的图片。…

商汤科技宣布C轮战略融资6亿美元 阿里领投苏宁跟投

来源&#xff1a;雷帝网 人工智能平台公司商汤科技SenseTime宣布完成6亿美元C轮融资&#xff0c;由阿里巴巴集团领投&#xff0c;新加坡主权基金淡马锡、苏宁等投资机构和战略伙伴跟投。商汤科技联合创始人、CEO徐立表示&#xff1a;商汤科技C轮融资将进一步夯实公司在人工智能…

MongoDB Shell和Robo3T使用以及与SQL语法比较

From&#xff1a;MongoDB Shell 了解使用 - 大葱哥 - 博客园 MongoDB基本管理命令&#xff1a;MongoDB基本管理命令_千与的专栏-CSDN博客_mongo查询命令 MongoDB常用操作命令大全&#xff1a;MongoDB常用操作命令大全_piaocoder-CSDN博客_mongodb常用命令 mongodb 命令行基本…

PowerDesiGner数据库设计

原文地址&#xff1a;http://hi.baidu.com/shunkunl/blog/item/871c75ef8596faeace1b3e00.htmlPowerDesign&#xff1a;PowerDesign是 Sybase推出的主打数据库设计工具。PowerDesign致力于采用基于Entiry-Relation的数据模型&#xff0c;分别从概念数据模型 (Conceptual Data M…

mipony linux客户端,Mipony网盘下载工具

Mipony是一个特别设计的下载管理器下载的免费网盘如Rapidshare&#xff0c;Megaupload&#xff0c;Hotfiles&#xff0c;Gigasize&#xff0c;Filefactory&#xff0c;Mediafire&#xff0c;Netload。简介&#xff1a;支援“HJSplit”档案合并功能&#xff0c;还可以自动侦测网…

2018全球100个最有价值的科技品牌 18个中国品牌上榜

来源&#xff1a;全球企业动态英国品牌评估机构Brand Finance发布“2018全球100个最有价值的科技品牌榜”(Top 100 most valuable tech brands 2018)&#xff0c;前五位都是美国品牌。美国上榜品牌总价值9590亿美元&#xff0c;占百强品牌总价值14673亿美元的65%。亚马逊跃升至…

Effective Java~2.Builder代替多参数Constructor

Builder模式 // Builder Pattern public class NutritionFacts {private final int servingSize;private final int servings;private final int calories;private final int fat;private final int sodium;private final int carbohydrate;public static class Builder {// R…

Alpine Linux 使用简介

From&#xff1a;https://www.aliyun.com/jiaocheng/137717.html Alpine Linux、CoreOS、RancherOS、Red Hat 原子项目、 VMware光子操作系统比较https://blog.csdn.net/hxpjava1/article/details/78482987 Alpine Linux配置使用技巧&#xff1a;https://www.aliyun.com/jiao…

实例学习SSIS(五)--理论介绍SSIS

导读&#xff1a; 实例学习SSIS&#xff08;一&#xff09;--制作一个简单的ETL包 实例学习SSIS&#xff08;二&#xff09;--使用迭代 实例学习SSIS&#xff08;三&#xff09;--使用包配置 实例学习SSIS&#xff08;四&#xff09;--使用日志记录和错误流重定向 实例学习SSIS…

MIT教授Tomaso Poggio演讲与专访:智能背后的科学与工程 | 腾讯AI Lab学术论坛

来源&#xff1a;腾讯AI实验室腾讯AI Lab第二届学术论坛在深圳举行&#xff0c;聚焦人工智能在医疗、游戏、多媒体内容、人机交互等四大领域的跨界研究与应用。全球30位顶级AI专家出席&#xff0c;对多项前沿研究成果进行了深入探讨与交流。腾讯AI Lab还宣布了2018三大核心战略…

linux捕捉信号sigint失败,为shell布置陷阱:trap捕捉信号方法论

本文目录&#xff1a;1.1 信号说明1.2 trap布置陷阱1.3 布置完美陷阱必备知识家里有老鼠&#xff0c;快消灭它&#xff01;哎&#xff0c;又给跑了。老鼠这小东西跑那么快&#xff0c;想直接直接消灭它还真不那么容易。于是&#xff0c;老鼠药、老鼠夹子或老鼠笼就派上用场了&a…