最近,需要實現在linux服務器上將Word文檔轉成PDF文檔的功能,接手其他人項目使用的是Jacob,但是需要往jdk里面添加文件,所以想換一個方法實現,根據前者和相關資料決定使用的aspose,因此記錄一下使用這個第三方組件的步驟。
一、環境搭建
1、首先需要下載一個aspose插件jar包放進項目中,使用的IDEA,jar包可以在網盤下載:
鏈接:https://pan.baidu.com/s/1jISO-TPEyLgC8RTmMJGRQw 提取碼:9ju8
2、下載好所需要的jar包,idea需要引入jar包,從編譯的層面考慮將將jar包安裝到本地倉庫,解決編譯打包時出錯的問題。
A.首先確定 mvn -v 能否使用,將下載好的jar包放到項目外的本地文件夾。
B.其次執行mvn install 安裝本地jar包到本地倉庫,如下所示:
mvn install:install-file -DgroupId=com.aspose -DartifactId=aspose-words -Dversion=15.8.0 -Dpackaging=jar -Dfile=aspose-words-15.8.0-jdk16.jar
執行完成后可到本地倉庫查看是否有這個包存在即可。
3、在項目中添加本地倉庫的依賴:
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>15.8.0</version> </dependency>
二、工具類編寫和測試
1、在項目靜態資源路徑下添加一個license.xml文件,不然生成的pdf會有水印
<?xml version="1.0" encoding="UTF-8" ?> <License> <Data> <Products> <Product>Aspose.Total for Java</Product> <Product>Aspose.Words for Java</Product> </Products> <EditionType>Enterprise</EditionType> <SubscriptionExpiry>20991231</SubscriptionExpiry> <LicenseExpiry>20991231</LicenseExpiry> <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber> </Data> <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature> </License>
2、添加Word2PdfAsposeUtil工具類
public class Word2PdfAsposeUtil { public static boolean getLicense() { boolean result = false; InputStream is = null; try { Resource resource = new ClassPathResource("license.xml"); is = resource.getInputStream(); //InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml應放在..\WebRoot\WEB-INF\classes路徑下 License aposeLic = new License(); aposeLic.setLicense(is); result = true; } catch (Exception e) { e.printStackTrace(); }finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static boolean doc2pdf(String inPath, String outPath) { if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生 return false; } FileOutputStream os = null; try { long old = System.currentTimeMillis(); File file = new File(outPath); // 新建一個空白pdf文檔 os = new FileOutputStream(file); Document doc = new Document(inPath); // Address是將要被轉化的word文檔 doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, // EPUB, XPS, SWF 相互轉換 long now = System.currentTimeMillis(); System.out.println("pdf轉換成功,共耗時:" + ((now - old) / 1000.0) + "秒"); // 轉化用時 } catch (Exception e) { e.printStackTrace(); return false; }finally { if (os != null) { try { os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } return true; } public static void main(String[] arg){ String docPath = "D:\\report\\word\\交通態勢日報-2021-01-10.docx"; String pdfPath = "D:\\report\\word\\交通態勢日報-2021-01-10.pdf"; Word2PdfAsposeUtil.doc2pdf(docPath,pdfPath); } }
3、后續可直接調用該工具類的方法即可實現Word轉Pdf的功能。
