知方号

知方号

使用poi+itextpdf将word转成pdf

使用poi+itextpdf将word转成pdf

将word转换成pdf确实有很多种方案!

背景

最近正好需要做一个这样的功能,需求是将word模板进行签名后转换为pdf。为此,我花了一点时间去网上找方案。期间遇到了一些坑,这里记录一下。

方案选择

首先,因为代码是跑在linux服务器上的,所以一般的,依赖windows office功能的方案就行不通了。这就排除了jacob这样一些效果很好的方案。

其次,我们的服务器上是不能安装office这样的软件的,而且对外部引入的maven jar包很严格,时间也比较紧张。考虑到这些因素,没有办法对这些方案一一详细了解。最终我选用了poi+itextpdf这样一种比较传统的方式。

poi+itextpdf这种方案利用html进行中转。也就是说先将word转成html格式,然后再将html转成pdf。html是String格式的,可以很方便地利用jsoup或字符串操作进行修改。这也是我选择这种方案的一个原因。

关于依赖

首先遇到的一个问题就是maven依赖,网上的示例要么不全,要么存在缺失,要么版本有问题。经过最终验证,得到以下maven依赖。 注意jar包版本!我只在以下确定的版本上测试成功了。

org.apache.poipoi-ooxml3.14org.apache.poipoi-scratchpad3.14fr.opensagres.xdocreportxdocreport1.0.6org.apache.poipoi-ooxml-schemas3.14org.apache.poiooxml-schemas1.3com.itextpdf.toolxmlworker5.5.11com.itextpdfitext-asian5.2.0org.jsoupjsoup1.11.3 关于代码 package cn.hewie.pdf;import com.itextpdf.text.BaseColor;import com.itextpdf.text.Font;import com.itextpdf.text.FontProvider;import com.itextpdf.text.PageSize;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.tool.xml.XMLWorkerHelper;import org.apache.commons.lang3.StringUtils;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.converter.PicturesManager;import org.apache.poi.hwpf.converter.WordToHtmlConverter;import org.apache.poi.hwpf.usermodel.PictureType;import org.apache.poi.xwpf.converter.core.BasicURIResolver;import org.apache.poi.xwpf.converter.core.FileImageExtractor;import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.jsoup.Jsoup;import org.jsoup.nodes.Element;import org.jsoup.nodes.Entities;import org.jsoup.select.Elements;import org.w3c.dom.Document;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import java.io.*;import java.nio.charset.Charset;/** * 使用poi+itextpdf进行word转pdf * 先将word转成html,再将html转成pdf * * @author :hewie * @date :Created in 2023/2/27 22:41 */public class OfficeUtil { /** * 将doc格式文件转成html * * @param docPath doc文件路径 * @param imageDir doc文件中图片存储目录 * @return html */ public static String doc2Html(String docPath, String imageDir) { String content = null; ByteArrayOutputStream baos = null; try { HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(docPath)); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()); wordToHtmlConverter.setPicturesManager(new PicturesManager() { @Override public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) { File file = new File(imageDir + suggestedName); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(content); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (Exception e) { e.printStackTrace(); } } return imageDir + suggestedName; } }); wordToHtmlConverter.processDocument(wordDocument); Document htmlDocument = wordToHtmlConverter.getDocument(); DOMSource domSource = new DOMSource(htmlDocument); baos = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(baos); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "html"); serializer.transform(domSource, streamResult); } catch (Exception e) { e.printStackTrace(); } finally { try { if (baos != null) { content = new String(baos.toByteArray(), "utf-8"); baos.close(); } } catch (Exception e) { e.printStackTrace(); } } return content; } /** * 将docx格式文件转成html * * @param docxPath docx文件路径 * @param imageDir docx文件中图片存储目录 * @return html */ public static String docx2Html(String docxPath, String imageDir) { String content = null; FileInputStream in = null; ByteArrayOutputStream baos = null; try { // 1> 加载文档到XWPFDocument in = new FileInputStream(new File(docxPath)); XWPFDocument document = new XWPFDocument(in); // 2> 解析XHTML配置(这里设置IURIResolver来设置图片存放的目录) XHTMLOptions options = XHTMLOptions.create(); // 存放word中图片的目录 options.setExtractor(new FileImageExtractor(new File(imageDir))); options.URIResolver(new BasicURIResolver(imageDir)); options.setIgnoreStylesIfUnused(false); options.setFragment(true); // 3> 将XWPFDocument转换成XHTML baos = new ByteArrayOutputStream(); XHTMLConverter.getInstance().convert(document, baos, options); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (baos != null) { content = new String(baos.toByteArray(), "utf-8"); baos.close(); } } catch (Exception e) { e.printStackTrace(); } } return content; } /** * 使用jsoup规范化html * * @param html html内容 * @return 规范化后的html */ private static String formatHtml(String html) { org.jsoup.nodes.Document doc = Jsoup.parse(html); // 去除过大的宽度 String style = doc.attr("style"); if (StringUtils.isNotEmpty(style) && style.contains("width")) { doc.attr("style", ""); } Elements divs = doc.select("div"); for (Element div : divs) { String divStyle = div.attr("style"); if (StringUtils.isNotEmpty(divStyle) && divStyle.contains("width")) { div.attr("style", ""); } } // jsoup生成闭合标签 doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); return doc.html(); } /** * html转成pdf * * @param html html * @param outputPdfPath 输出pdf路径 */ public static void htmlToPdf(String html, String outputPdfPath) { com.itextpdf.text.Document document = null; ByteArrayInputStream bais = null; try { // 纸 document = new com.itextpdf.text.Document(PageSize.A4); // 笔 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfPath)); document.open(); // html转pdf bais = new ByteArrayInputStream(html.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(writer, document, bais, Charset.forName("UTF-8"), new FontProvider() { @Override public boolean isRegistered(String s) { return false; } @Override public Font getFont(String s, String s1, boolean embedded, float size, int style, BaseColor baseColor) { // 配置字体 Font font = null; try { // 方案一:使用本地字体(本地需要有字体)// BaseFont bf = BaseFont.createFont("c:/Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);// BaseFont bf = BaseFont.createFont("C:/Windows/Fonts/seguisym.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); // 方案二:使用jar包:iTextAsian,这样只需一个jar包就可以了 BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); font = new Font(bf, size, style, baseColor); font.setColor(baseColor); } catch (Exception e) { e.printStackTrace(); } return font; } }); } catch (Exception e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } if (bais != null) { try { bais.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) throws Exception { String basePath = "F:/test/pdf/"; String docPath = basePath + "index.doc"; String docxPath = basePath + "index.docx"; String pdfPath = basePath + "index.pdf"; String imageDir = "F:/test/pdf/image/"; // 测试doc转pdf// String docHtml = doc2Html(docPath, imageDir);// docHtml = formatHtml(docHtml);// htmlToPdf(docHtml, pdfPath); // 测试docx转pdf String docxHtml = docx2Html(docxPath, imageDir); docxHtml = formatHtml(docxHtml); docxHtml = docxHtml.replace("___", "张三"); htmlToPdf(docxHtml, pdfPath); }}

众所周知,word有多个版本。此demo中只考虑了doc和docx两种格式的处理。 另外,有几点需要注意一下。

因为word文件中很有可能会有图片,所以需要一个路径来将图片存储来下中转一下。如果不设置,pdf中将看不到图片哦~因为生成的html中,存在style设置width过大的问题(docx转html场景),这会导致在生成的pdf中,存在大量的空格(如果“纸”小了,很可能发现整个pdf都是空白的)。因此需要将width去掉,这里直接干掉了style了,有点暴力~转换后的模板很容易进行文字替换,例如:将用户名称填入

下面看一下效果吧,感觉还是不错的。 原始word如下:

转换成pdf如下:

关于坑

下面讲一讲遇到的几个问题吧!

1. 找不到方法,报错

Exception in thread “main” java.lang.NoSuchMethodError: org.apache.poi.POIXMLDocumentPart.getPackageRelationship()Lorg/apache/poi/openxml4j/opc/PackageRelationship;

这个原因排查了很长时间,后来发现是包版本原因。原先poi相关的几个jar包是3.17的,后来发现改成3.14后就可以了。

2. jsoup生成的标签不闭合,导致html转pdf失败,报错

com.itextpdf.tool.xml.exceptions.RuntimeWorkerException: Invalid nested tag p found, expected closing tag br.

这个问题在github上找到答案了。joup的老哥们认为有些标签,如、在h5标准中,是不需要闭合的。但是咱们的引入的解析器XMLWorker不这么认为,所以就报这样的错了。 所幸jsoup中可以设置,代码如下:

doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); 3. 转换后,中文都替换为空白了

这是因为没有对应的字体文件。这里有几种解决方案: 1) 使用系统自带的系统文件。缺点就是需要指定路径。如果是在linux环境部署的话,需要进行字体文件上传 2) 使用外部jar包

com.itextpdfitext-asian5.2.0

毫无疑问,这种方案比第一种方便多了。毕竟少了很多运维上的事了。

这两种方案都在代码中备注了。这里不再表述实现了。

4. 使用上述第一种方式解决中文字体问题,出错

simsun.ttc’ with ‘Identity-H’ is not recognized或者type of font{0} is not recognized

原因是参数不对。如windows系统,地址应为:“c:/Windows/Fonts/simsun.ttc,0 “,注意结尾的”,0” 详情戳:https://blog.csdn.net/zhangtongpeng/article/details/100173633

源码地址

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。