当前位置: 首页 > news >正文

java中使用Jsoup和Itext实现将html转换为PDF

1.在build.gradle中安装所需依赖:

implementation group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13'
implementation group: 'com.itextpdf.tool', name: 'xmlworker', version: '5.5.13'
implementation group: 'org.jsoup', name: 'jsoup', version: '1.15.3'

2.创建工具类,实现转换方法

/*** convert the html to pdf.*/public void htmlToPdf(String oldFilePath, String newFilePath) throws IOException, com.itextpdf.text.DocumentException {Document doc = Jsoup.parse(new File(oldFilePath), "UTF-8");// jsoup标准化标签,生成闭合标签doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4, 36, 36, 36, 36);PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(newFilePath));document.open();//html to pdf, base64 image support.final TagProcessorFactory tagProcessorFactory = Tags.getHtmlTagProcessorFactory();tagProcessorFactory.removeProcessor(HTML.Tag.IMG);tagProcessorFactory.addProcessor(new ImageTagRefreshFilter(), HTML.Tag.IMG);//设置中文字体final CssFilesImpl cssFiles = new CssFilesImpl();cssFiles.add(XMLWorkerHelper.getInstance().getDefaultCSS());final StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);final HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(asianFontRefreshFilter));hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(tagProcessorFactory);final HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, pdfWriter));final Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);final XMLWorker worker = new XMLWorker(pipeline, true);final Charset charset = StandardCharsets.UTF_8;final XMLParser xmlParser = new XMLParser(true, worker, charset);InputStream inputStream = new ByteArrayInputStream(doc.html().getBytes());xmlParser.parse(inputStream, charset);
//        XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, inputStream, Charset.forName("UTF-8"));document.close();}

3.base64过滤类:

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.NoCustomContextException;
import com.itextpdf.tool.xml.Tag;
import com.itextpdf.tool.xml.WorkerContext;
import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException;
import com.itextpdf.tool.xml.html.HTML;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;public class ImageTagRefreshFilter extends com.itextpdf.tool.xml.html.Image {/*** html to pdf, base64 image support.* */@Overridepublic List<Element> end(final WorkerContext ctx, final Tag tag, final List<Element> currentContent) {final Map<String, String> attributes = tag.getAttributes();String src = attributes.get(HTML.Attribute.SRC);List<Element> elements = new ArrayList<Element>(1);if (null != src && src.length() > 0) {Image img = null;if (src.startsWith("data:image/")) {final String base64Data = src.substring(src.indexOf(",") + 1);try {img = Image.getInstance(Base64.decode(base64Data));} catch (Exception e) {throw new RuntimeException(e);}if (img != null) {try {final HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx);elements.add(getCssAppliers().apply(new Chunk((com.itextpdf.text.Image) getCssAppliers().apply(img, tag, htmlPipelineContext), 0, 0, true), tag,htmlPipelineContext));} catch (NoCustomContextException e) {throw new RuntimeWorkerException(e);}}}if (img == null) {elements = super.end(ctx, tag, currentContent);}}return elements;}
}

4.字体类代码,window用户可在C:\windows\font\中寻找自己所需字体即可。我这里用的为黑体:

simhei.ttf

import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class AsianFontRefreshFilter extends XMLWorkerFontProvider {//此处写字体文件的绝对路径private String fontPath;@Overridepublic Font getFont(String fontname, String encoding, float size, final int style) {try {//字体文件绝对路径BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);return new Font(bfChinese, size, style);} catch (Exception e) {e.printStackTrace();}return super.getFont(fontname, encoding, size, style);}
}

效果如下:

html页面预览:

pdf页面预览:

 

 

http://www.lryc.cn/news/109637.html

相关文章:

  • 无人驾驶实战-第七课(高精地图和V2X )
  • springboot集成Sentinel
  • 数据结构——单链表OJ题
  • 【雕爷学编程】MicroPython动手做(31)——物联网之Easy IoT
  • 《前端开发 实践之 构建工具的了解》
  • MySQL 主从搭建
  • 国内GitHub加速访问工具-Fetch GitHub Hosts
  • Webpack5新手入门简单配置
  • 基于ali-oss实现不同类型文件上传不同的bucket
  • 域名校验?反爬界的掩耳盗铃!
  • Cesium 实战教程 - 调整 3dtiles 倾斜摄影大小
  • python机器学习(七)决策树(下) 特征工程、字典特征、文本特征、决策树算法API、可视化、解决回归问题
  • 数据结构与算法中的双向链表
  • 数据安全治理的关键-数据分类分级工具
  • Spring集成Junit
  • Java正则校验密码至少包含:字母数字特殊符号中的2种
  • Stable Diffusion教程(6) - 扩展安装
  • Jenkins通过OpenSSH发布WinServer2016
  • 字母异位词分组 LeetCode热题100
  • 使用angular和electron 构建桌面应用
  • 安达发制造工业迈向智能化:APS高级计划排程助力提升生产效率
  • Flink - sink算子
  • 【项目 线程2】3.5 线程的分离 3.6线程取消 3.7线程属性
  • Filebeat+ELK 部署
  • el-table点击表格某一行添加到URL参数,访问带参URL加载表格内容并滚动到选中行位置 [Vue3] [Element-plus 2.3]
  • 【树】 二叉树 堆与堆排序 平衡(AVL)树 红黑(RB)树
  • 信号平滑或移动平均滤波研究(Matlab代码实现)
  • 黑客技术(网络安全)自学
  • 使用七牛云、阿里云、腾讯云的对象存储上传文件
  • 使用阿里云DataX完成数据同步