此方法windows和linux都可用. 此方法只能转docx!!!!
导依赖
(此jar包pom文件正常下不下来,需要直接导jar包)
首先下好aspose.wordhttps://link.csdn.net/?target=https%3A%2F%2Fpan.baidu.com%2Fs%2F1bKYmXreiwaBwwGlPc1JESw(下载地址:提取码: i51v :不保证长期有效)aspose-words-15.8.0-jdk16.jar,网上搜下应该能找到,而且看了下,貌似相似的版本也是可以用的,直接搜一个maven仓库也能找到jar包下载(参考文章)。
1.如果是普通的工程直接添加到项目中目录下,右键Build Path->Add to Build Path。添加到项目中。
2.如果是maven工程,如果自己找到的maven版本能用就最好,不能用的话就用我下载地址提供的也可以,直接再CMD下运行下面的命令添加jar包到maven的本地仓库。(记得替换为自己的版本)
mvn install:install-file -Dfile=jar包的位置 -DgroupId=上面的groupId -DartifactId=上面的artifactId -Dversion=上面的version -Dpackaging=jar
<dependency> <groupId>com.aspose</groupId> <artifactId>words</artifactId> <version>15.8.0</version> <scope>system</scope> <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath> </dependency>
上代码
/** * aspose.words 这个只能转docx,不能转doc,但是在linux上运行是没问题的 */ public static void wordToPdf(String wordPath, String pdfPath) throws Exception { try { String s = "<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>"; ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes()); License license = new License(); license.setLicense(is); Document document = new Document(wordPath); document.save(pdfPath); } catch (Exception e) { throw new Exception("docx转pdf失败"); } }
至此结束!!!
遇到的问题
-
本地测试正常,Linux还是乱码
原因:
(1)Linux服务器上没有安装对应的中文字体,参考
(2)字体并不是被所有用户通用的
(3)没有构建字体索引,没有刷新字体路径缓存
解决:
百度Linux安装中文字体,之后,运行命令看看是否能看到中文字体 -
安装了中文字体还是乱码
原因:在Linux上运行Jar无法找到中文字体,可以在代码里面添加路径指向中文字体文件夹