先讲讲思路:
第一步:使用 poi 将word转换成 html,这里代码一搜一堆没什么好说的,千篇一律。
(值得注意的地方是IText 根据html生成pdf文件的时候,会验证html文件是否标准,例如通过poi转换的出来的html文件的一些标签会缺少标签闭合 ” / “ :
举个栗子:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<img src="test/0.jpg" style="width:5.765972in;height:8.647917in;vertical-align:text-bottom;">
这是我直接用pio生成的html中的一部分, META、img 标签明显就没有对应闭合标签。如果用这种html进行转换是没有办法通过itext 的校验的。会出现以下异常
错误: “The element type "meta" must be terminated by the matching end-tag "</meta>".”
org.xhtmlrenderer.util.XRRuntimeException: Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException: The element type "meta" must be terminated by the matching end-tag "</meta>". 。
从错误分析也知道是我们的html不规范拉,我们采用第三方 jar 包Jsoupÿ