最近公司需要以word為模版,填充數據,然后轉成pdf。做了一點點研究
1.使用xdocreport進行轉(優點效率高,缺點對word格式要求較大,適合對生成pdf要求不高的情況)
/**
* 將word文檔, 轉換成pdf
* 宋體:STSong-Light
*
* @param fontParam1 可以字體的路徑,也可以是itextasian-1.5.2.jar提供的字體,比如宋體"STSong-Light"
* @param fontParam2 和fontParam2對應,fontParam1為路徑時,fontParam2=BaseFont.IDENTITY_H,為itextasian-1.5.2.jar提供的字體時,fontParam2="UniGB-UCS2-H"
* @param tmp 源為word文檔, 必須為docx文檔
* @param target 目標輸出
* @throws Exception
*/
public void wordConverterToPdf(String tmp, String target, String fontParam1, String fontParam2) {
InputStream sourceStream = null;
OutputStream targetStream = null;
XWPFDocument doc = null;
try {
sourceStream = new FileInputStream(tmp);
targetStream = new FileOutputStream(target);
doc = new XWPFDocument(sourceStream);
PdfOptions options = PdfOptions.create();
//中文字體處理
options.fontProvider(new IFontProvider() {
public Font getFont(String familyName, String encoding, float size, int style, Color color) {
try {
BaseFont bfChinese = BaseFont.createFont(fontParam1, fontParam2, BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, size, style, color);
if (familyName != null)
fontChinese.setFamily(familyName);
return fontChinese;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
});
PdfConverter.getInstance().convert(doc, targetStream, options);
File file = new File(tmp);
file.delete(); //刪除word文件
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(doc);
IOUtils.closeQuietly(targetStream);
IOUtils.closeQuietly(sourceStream);
}
}
2.使用dom4j進行轉換,試了下效率較低,而且轉換質量還不如xdoreport,故沒有繼續。也可能是小弟沒研究清楚,代碼就不粘了
3.使用libreoffice來進行轉(效果好,格式便於控制,基本上轉出來的pdf和用libreoffice查看看到的word樣子已經非常接近了)
最開始網上查用jodconverter來調用openOffice或者libreoffice的服務來轉換,試了下也是速度極慢,轉一個2頁的word需要10s,確實不能忍。
然后想到既然jodconverter能調用,那我自己執行libreoffice命令轉換不可以嗎,之后發現這個思路可行。
步驟:
1.安裝libreoffice(linux還需要裝unoconv),目前我安裝的是5.3.3版本
2.黑窗口直接敲命令,windows:soffice --convert-to pdf example.docx linux: doc2pdf example.docx, windows需要添加path系統變量(C:\Program Files\LibreOffice 5\program),不然無法識別soffice命令
3.ok,既然可以這么玩,放到java項目就簡單了
public boolean wordConverterToPdf(String docxPath) throws IOException {
File file = new File(docxPath);
String path = file.getParent();
try {
String osName = System.getProperty("os.name");
String command = "";
if (osName.contains("Windows")) {
command = "soffice --convert-to pdf -outdir " + path + " " + docxPath;
} else {
command = "doc2pdf --output=" + path + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + docxPath;
}
String result = CommandExecute.executeCommand(command);
LOGGER.info("result==" + result);
if (result.equals("") || result.contains("writer_pdf_Export")) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return false;
}
代碼親試可用,歡迎吐槽
寫這篇文章后想到應該還有些其他的方法,比如用wps、office來進行轉化,若大蝦們有更合適的方式請賜教之
源碼地址:
https://github.com/AryaRicky/toPdfUtils.git