一、在项目中引入Aspose-Words依赖
下载地址:/s/1nvbJwnv
建议将jar包下载下来并上传到自己公司的私服里去
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
二、项目中基于Aspose-Words封装工具类实现Word转换Pdf
直接上示例代码
package com.demo.utils;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Word 转 Pdf 帮助类
*
* 备注:需要引入 aspose-words-15.8.
*/
public class PdfUtil {
private static boolean getLicense() {
boolean result = false;
try {
InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param wordPath 需要被转换的word全路径带文件名
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static void doc2pdf(String wordPath, String pdfPath) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return;
}
try {
long old = System.currentTimeMillis();
//新建一个pdf文档
File file = new File(pdfPath);
FileOutputStream os = new FileOutputStream(file);
//Address是将要被转化的word文档
Document doc = new Document(wordPath);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, SaveFormat.PDF);
long now = System.currentTimeMillis();
os.close();
//转化用时
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}
以下是文件,需要放置在正确的相对路径下
<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>
三、使用须知
当文档中含有中文字符时,该段代码的执行需要调用操作系统的本地字体库支持,否则所有中文字符都将乱码
该段代码如果想要在Linux服务器上完美运行,需要给Linux服务器安装中文字体库
如何在Linux环境安装Windows字体库,将在本人的另一篇文章里详细讲解
Java使用或Aspose-Words实现Word转换Pdf在Linux服务器上的中文乱码问题