1、引入aspose-words-jdk17-24.01.jar
链接:https://pan.baidu.com/s/1HpBzscKGk8NI5rz07d8-6w
提取码:qjha
<dependency>
<groupId>aspose</groupId>
<artifactId>aspose-words-jdk17</artifactId>
<version>24.01</version>
</dependency>
2、添加word操作工具类
package com.core.utils;
import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
public class AsposeUtil {
/**
* word转pdf
* inpath: 输入word的路径
* outpath: 输出pdf的路径
*/
public void word2Pdf2(String inpath,String outpath) throws Exception {
System.out.println("开始使用Aspose.words进行转换");
long old = System.currentTimeMillis();
File file = new File(outpath);
FileOutputStream os = new FileOutputStream(file);
//解决乱码
//如果是windows执行,不需要加这个
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Mac OS")) {
} else if (osName.startsWith("Windows")) {
} else { // assume Unix or Linux
//如果是linux执行,需要添加这个 ,如果还有乱码,可以把/usr/share/fonts/chinese路径下的所有文件拷贝到有问题的环境。并且再执行:source /etc/profile
// FontSettings.setFontsFolder("/usr/share/fonts/chinese",true);
}
Document doc = new Document(inpath);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, SaveFormat.PDF);
long now = System.currentTimeMillis();
System.out.println("Aspose.words转换结束,共耗时:" + ((now - old) / 1000.0) + "秒");
}
/**
* word转pdf
* @param path pdf输出路径
* @param wordInput word输入流
* @param wordName word文档的名称
*/
public void word2pdf(String path, InputStream wordInput, String wordName) throws FileNotFoundException {
//新建一个空白pdf文档
long old = System.currentTimeMillis();
File file = new File(path + wordName + ".pdf");
FileOutputStream os = new FileOutputStream(file);
//Address是将要被转化的word文档
Document doc = null;
try {
doc = new Document(wordInput);
} catch (Exception e) {
e.printStackTrace();
}
try {
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
}
long now = System.currentTimeMillis();
//转化用时
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
}
}
3、测试用例
@Test
public void test2() throws Exception {
AsposeUtil bean = new AsposeUtil();
bean.word2Pdf2("D:\\test\\test.docx","D:\\test\\test.pdf");
}