关于FreeMarker生成word文档后转换为pdf得解决方法及常见问题

关于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

之后重启就可以生效啦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值