点击下载对应jar包
使用aspose将docx(支持多种文档类型)转化为pdf,以下为docx流转化为pdf文件或pdf流(不产生中间文件)
/**
* 验证License 若不验证则转化出的pdf文档会有水印产生
* @return
*/
private static boolean getLicense() {
boolean result = false;
InputStream is = null;
try {
is = WordUtils.class.getClassLoader().getResourceAsStream("aspose/license.xml");
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;
}
/**
* @param inputStream 需要被转换的word的流
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static boolean docxToPdf(InputStream inputStream, String pdfPath) {
FileOutputStream os = null;
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return false;
}
try {
File outputFile = new File(pdfPath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
os = new FileOutputStream(outputFile);
Document docx = new Document(inputStream);
// 支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,XPS, SWF 相互转换
docx.save(os, SaveFormat.PDF);
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* @param inputStream 需要被转换的word的流
* @return pdf流
*/
public static InputStream docxToPdf(InputStream inputStream) {
ByteArrayOutputStream os = null;
ByteArrayInputStream is = null;
// 验证License 若不验证则转化出的pdf文档会有水印产生
// if (!getLicense()) {
// throw new ResultException(500, "docx转pdf验证失败");
// }
//设置中文字体所在目录
OsInfo osInfo = SystemUtil.getOsInfo();
if(osInfo.isLinux()){
FontSettings fontSettings = new FontSettings();
fontSettings.setFontsFolder("/usr/share/fonts/chinese", true);
}
try {
os = new ByteArrayOutputStream();
Document docx = new Document(inputStream);
// 支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,XPS, SWF 相互转换
docx.save(os, SaveFormat.PDF);
is = new ByteArrayInputStream(os.toByteArray());
return is;
} catch (Exception e) {
throw new ResultException(500, "合同生成失败");
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
license.xml用来解决水印问题;linux上可能会中文乱码,因为linux没有对应的中文文件,上面代码设置了linux上中文文件所在的路径,只需将window上的中文文件拷贝到linux上即可。window上路径为C:\Windows\Fonts
参考1:https://blog.youkuaiyun.com/River_Frozen/article/details/105774825?spm=1001.2014.3001.5502
参考2:https://blog.youkuaiyun.com/Number_oneEngineer/article/details/122124096