一、引入jar包
aspose-words-15.8.0-jdk16.jar
二、代码工具类
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class Word2Pdf {
static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
static final int wdFormatPDF = 17;// PDF 格式
public static void main(String[] args) {
word2pdf("C:\\test\\media\\2022-03-03.doc", "C:\\test\\media\\2022-03-03.pdf");
}
public static String word2pdf(String inPath, String outPath) {
if (!isWordLicense()) {
return null;
}
try {
String path = outPath.substring(0, outPath.lastIndexOf(File.separator));
File file = null;
file = new File(path);
if (!file.exists()) {//创建文件夹
file.mkdirs();
}
file = new File(outPath);// 新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(inPath); // Address是将要被转化的word文档
doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
} catch (Exception e) {
e.printStackTrace();
}
// EPUB, XPS, SWF 相互转换
return outPath;
}
/**
* @Description: 验证aspose.word组件是否授权:无授权的文件有水印和试用标记
*/
public static boolean isWordLicense() {
boolean result = false;
try {
// InputStream inputStream = new
// FileInputStream("D:\\Workspaces\\TestFilters\\lib\\license.xml");
// 避免文件遗漏
String licensexml = "<License>\n" + "<Data>\n" + "<Products>\n"
+ "<Product>Aspose.Total for Java</Product>\n" + "<Product>Aspose.Words for Java</Product>\n"
+ "</Products>\n" + "<EditionType>Enterprise</EditionType>\n"
+ "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
+ "<LicenseExpiry>20991231</LicenseExpiry>\n"
+ "<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n" + "</Data>\n"
+ "<Signature>\n"
+ "sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=\n"
+ "</Signature>\n" + "</License>";
InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes());
com.aspose.words.License license = new com.aspose.words.License();
license.setLicense(inputStream);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}