关于FreeMarker生成word文档后转换为pdf得解决方法及常见问题
最近在做一个项目要求之前下载出的word简历直接变成pdf 格式进行展现。因为格式比较复杂,所以采用的时模板并用Freemarker填充的形式来实现的。
但是后续加了转pdf,看了很多种方式都不行(最常见的jaboc无法跨平台,linux不能用),最终各种折腾之后还是发现了一种方式,用aspose-words实现。
package com.test.util;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class Word2PdfUtil {
private InputStream license;
private InputStream fileInput;
private File outputFile;
/**
* 获取license
*
* @return
*/
public boolean getLicense(String docFile, String licenseFile, String pdfFile) {
boolean result = false;
try {
license = new FileInputStream(licenseFile);// 凭证文件
fileInput = new FileInputStream(docFile);// 待处理的文件
outputFile = new File(pdfFile);// 输出路径
License aposeLic = new License();
aposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean doc2Pdf(String docFile, String pdfFile, String licenseFile) {
// 验证License
if (!getLicense(docFile, licenseFile, pdfFile)) {
return false;
}
try {
long old = System.currentTimeMillis();
Document doc = new Document(fileInput);
FileOutputStream fileOS = new FileOutputStream(outputFile);
doc.save(fileOS, SaveFormat.PDF);
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + outputFile.getPath());
return true;
} catch (Exception e) {
e.printStackTrace();
return fasle;
}
}
}
转换pdf后可能会出现内容乱码问题,原因是可能事因为你的linux服务器没有中文字库。接下来就要这样操作:
1、找你的Windows字体库
Windows下字体库的位置为C:\Windows\fonts,这里面包含所有windows下可用的字体。
2、linux的字体库是 /usr/share/Fonts
在该目录下新建一个目录,比如目录名叫 windows,然后将 windows 字体库中你要的字体文件复制到新建的目录下(只需要复制*.ttc,和*.ttf的文件)
3、更改这些字体库的权限,可以右键,也可以用命令行
chmod 755 /usr/share/fonts/windows/*
4、然后进入Linux字体库:
cd /usr/share/fonts/windows/
5、接着根据当前目录下的字体建立scale文件
mkfontscale
6、接着建立dir文件:
mkfontdir
7、然后运行
fc -cache -fv
之后重启就可以生效啦!