java word轉pdf的幾種方法
阿新 • • 發佈:2018-11-01
轉載:https://blog.csdn.net/qwert678000/article/details/72770109
最近公司需要以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