java实现Word转Pdf(Windows、Linux通用)
最近,需要实现在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的功能。

浙公网安备 33010602011771号