一、问题
在linux服务器使用aspose.word转换word文件为pdf的时候显示中文乱码,但是在windows本地环境上使用可以正常转换
二、原因
由于linux服务器缺少对应的字库导致文件转换出现乱码的
三、解决
1、第一种方案(参考以下)
aspose转pdf乱码问题_aspose word转pdf 乱码-CSDN博客
Word模板替换,并转PDF格式输出,Linux服务器乱码问题解决_poi-tl word转pdf乱码-CSDN博客
Linux系统Word转换图片或PDF,字体出现乱码_linux word转pdf中文乱码-CSDN博客
2、第二种方案
先去windows字体库,在目录:C:\Windows\Fonts下,将需要的字体拷贝到项目中对应的模块resources下
然后在word转PDF方法中指定字体的位置路径
@Slf4j
public class Word2PdfAsposeUtil {
private static boolean getLicense() {
boolean result = false;
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("license.xml")) {
// License的包路径必须为com.aspose.words.License
License license = new License();
license.setLicense(in);
result = true;
} catch (Exception e) {
log.info(e.getMessage());
}
return result;
}
public static void doc2pdf(OutputStream outputStream, HttpServletResponse response, String pdfName) throws IOException {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
OutputStream out = response.getOutputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ByteArrayInputStream byteArrayInputStream = null;
try {
long old = System.currentTimeMillis();
response.setCharacterEncoding("utf-8");
response.setHeader(
"Content-Disposition",
"attachment;filename=".concat(URLEncoder.encode(pdfName + ".pdf", StandardCharsets.UTF_8)));
response.setContentType("application/pdf");
byteArrayOutputStream = (ByteArrayOutputStream) outputStream;
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//解决Linux缺失字体乱码问题
OsInfo osInfo = SystemUtil.getOsInfo();
if(osInfo.isLinux()){
FontSettings.setFontsFolder(Objects.requireNonNull(Word2PdfAsposeUtil.class.getClassLoader().getResource("fonts")).toURI().getPath(), true);
}
Document doc = new Document(byteArrayInputStream); // Address是将要被转化的word文档
doc.save(out, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
IOUtils.copy(byteArrayInputStream, out);
// EPUB, XPS, SWF 相互转换
long now = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
log.info(e.getMessage());
}finally {
if (out != null) {
try {
out.flush();
PoitlIOUtils.closeQuietlyMulti(out, outputStream, byteArrayOutputStream, byteArrayInputStream);
} catch (IOException e) {
log.info(e.getMessage());
}
}
}
}
}