用aspose实现word(doc、docx格式)转pdf做文件预览;
1、引入依赖jar包;
public class WordToPdfUtil {
/**
* @Description 获取office授权认证,否则会有水印
* @param
*/
public static boolean getLicense()
{
boolean result = false;
try {
InputStream is = WordToPdfUtil.class.getClassLoader().getResourceAsStream("classpath:static.pdf/wordlicense.xml"); // wordlicense.xml应放在..\WebRoot\WEB-INF\classes路径下
com.aspose.words.License aposeLic = new com.aspose.words.License();
aposeLic.setLicense(is);
result = true;
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @Description 转化pdf
* @param Address
*/
public static void word2pdf(String Address,String targetFileName)
{
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
//FontSettings.setFontsFolder("/home/worker", false);
try {
File file = new File(targetFileName); //新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(Address); //Address是将要被转化的word文档
doc.save(os, SaveFormat.PDF); //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
os.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] agrs)
{
word2pdf("C:\\Intel\\1.docx","C:\\Intel\\1.pdf");
}
}
2、上述方式在linux系统下可能会产生字体乱码的问题,原因是word文档中部分选择的字体仅在windows支持,在linux下没有对应的字体,因此需要安装我们所需要的字体到linux系统下;
字体文件的后缀为ttf、ttc(下载的字体一般是ttc或ttf格式的,系统显示这都是TrueType类型的字体。ttf格式的字体可以正常使用,但ttc的字体只有一些常用的汉字,而许多不常用的汉字就没有(选择字体以后依然以宋体显示))
Linux系统安装Windows字体步骤如下:
1.复制字体
在“C:\Windows\Fonts”目录下找到所要安装字体,这里以“simsun.ttf”为例。如果安装的字体找不到,就去网上下载。
2.上传字体至CentOS系统
在/usr/share/fonts目录下建立一个子目录,比如/winFonts。上传“simsun.ttf”字体至此目录。
3.进入此目录安装
cd /usr/share/fonts/winFonts
运行以下命令建立字体索引信息,更新字体缓存::
sudo mkfontscale
sudo mkfontdir
sudo fc-cache -fv
执行以下命令让字体生效
source /etc/profile
4.问题与解决
如果安装失败可以尝试更改权限:
cd /usr/share/fonts/winFonts
chmod 755 *.ttf
若提示 “ mkfontscale: command not found”,用yum安装:
yum install mkfontscale
提示 “ fc-cache: command not found”
yum install fontconfig
若需要重启服务器:
reboot
查看已安装的字体:
fc-list
作者:irokay
来源:CSDN
原文:https://blog.csdn.net/irokay/article/details/50539579
版权声明:本文为博主原创文章,转载请附上博文链接!