JAVA 使用 com.aspose.words將word轉換PDF等
因為公司前端需要線上檢視word和PDF,後臺上傳需求將word等檔案轉換為PDF,原本使用的是liboffice進行轉換,後來部署到伺服器端之後,發現並不是很適合,由此找到com.aspose.words。直接貼程式碼,大部分程式碼複製百度。
public class WordToPdf { private static final Logger logger = LoggerFactory.getLogger(WordToPdf.class); /** * 獲取license * * @return */ private static boolean getLicense() { boolean result = false; try { // 憑證 String licenseStr = "<License>\n" + " <Data>\n" + " <Products>\n" + " <Product>Aspose.Total for Java</Product>\n" + " <Product>Aspose.Words for Java</Product>\n" + " </Products>\n" + " <EditionType>Enterprise</EditionType>\n" + " <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" + " <LicenseExpiry>20991231</LicenseExpiry>\n" + " <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" + " </Data>\n" + " <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" + "</License>"; InputStream license = new ByteArrayInputStream( licenseStr.getBytes("UTF-8")); License asposeLic = new License(); asposeLic.setLicense(license); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * Word 轉換 Pdf * @param inPath * @param outPath */ public static void doc2pdf(String inPath, String outPath) { if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文件會有水印產生 logger.debug("doc2pdf,解析水印失敗,請重試"); return; } try { long old = System.currentTimeMillis(); File file = new File(outPath); // 新建一個pdf文件 FileOutputStream os = new FileOutputStream(file); Document doc = new Document(inPath); // Address是將要被轉化的word文件 logger.debug("開始解析word文件"+inPath); doc.save(os, com.aspose.words.SaveFormat.PDF);// 全面支援DOC, DOCX, // OOXML, RTF HTML, // OpenDocument, // PDF, EPUB, XPS, // SWF 相互轉換 long now = System.currentTimeMillis(); os.close(); logger.debug("轉換成功,共耗時:"+((now - old) / 1000.0) + "秒"); } catch (Exception e) { logger.debug("doc2pdf", new Object[] { "1082", "轉換失敗,請重試", MsgLevel.D }); e.printStackTrace(); } } }