使用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包版本!我只在以下確定的版本上測試成功了。

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.14</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-scratchpad</artifactId>
	<version>3.14</version>
</dependency>
<dependency>
	<groupId>fr.opensagres.xdocreport</groupId>
	<artifactId>xdocreport</artifactId>
	<version>1.0.6</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml-schemas</artifactId>
	<version>3.14</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>ooxml-schemas</artifactId>
	<version>1.3</version>
</dependency>
<dependency>
	<groupId>com.itextpdf.tool</groupId>
	<artifactId>xmlworker</artifactId>
	<version>5.5.11</version>
</dependency>

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>

關於代碼

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 2020/2/27 22:41
 */
public class TestPoi {

    /**
     * 將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路徑
     */
    private static void htmlToPdf(String html, String outputPdfPath) {
        com.itextpdf.text.Document document = null;
        try {
            // 紙
            document = new com.itextpdf.text.Document(PageSize.A4);
            // 筆
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfPath));
            document.open();
            // html轉pdf
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(html.getBytes()),
                    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);
                                // 方案二:使用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();
            }
        }
    }

    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如下:
原始word.png

轉換成pdf如下:
轉換後pdf.png

關於坑

下面講一講遇到的幾個問題吧!

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包

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>

毫無疑問,這種方案比第一種方便多了。畢竟少了很多運維上的事了。

這兩種方案都在代碼中備註了。這裏不再表述實現了。

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

源碼地址

本文源碼地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章