java生成自定义证书图片3 - 将word转成pdf格式

将doc指定内容替换成自定义数据之后,需要将docx文件转成pdf文件,便于下一步转成图片,工具类如下:

package com.x.certificate.doc;

import java.io.File;
import java.io.IOException;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

/** 
 * 用于docx文件的格式转换
 * @author xuhaojin
 * @version [版本号, 2020年3月22日]
 */
public class DocxConverter {

    /**
     * 使用libreoffice服务,将docx格式文件转成pdf格式文件
     * @param docxPath
     * @param pdfPath
     * @param libreOfficePath
     * @return
     * @throws IOException    参数
     * File    返回类型
     */
    public static File toPdfUsingLibreOffice(String docxPath, String pdfPath, String libreOfficePath)
            throws IOException {
        File pdf = new File(pdfPath);

        try {
            OfficeManager officeManager = getOfficeManager(libreOfficePath);
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
            converter.convert(new File(docxPath), pdf);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pdf;
    }

    public static OfficeManager getOfficeManager(String libreOfficePath) {
        OfficeManager officeManager = new DefaultOfficeManagerConfiguration().setOfficeHome(new File(libreOfficePath))
                .buildOfficeManager();
        officeManager.start();
        return officeManager;
    }

    public static void main(String[] args) throws IOException {
        String inputFile = "C:\\Users\\a1579\\Desktop\\custom.docx";
        String outputFile = "C:\\Users\\a1579\\Desktop\\custom.pdf";
        String librePath = "D:\\libreoffice";
        toPdfUsingLibreOffice(inputFile, outputFile, librePath);
    }

}

其中,需要指定一个已有的docx文件路径,以及生成pdf的路径。这个工具类依赖libreoffice的服务,需要在程序本地安装,指定libreoffice的路径。

libreoffice是一个开源的office工具,是openoffice的升级版,java有很多开源的库可以将docx转成pdf,但在我实践中发现,很多库转换后,docx的文本框以及内容会消失,所以最终选择了openoffice,完美地解决了这个问题。而且libreoffice既可以在windows安装,也可以在linux安装,方便在linux服务器中使用。

工具类中获取officeManager实例和启动服务的操作非常耗时,也就是代码中的getOfficeManager方法的内容,创建并其中office服务在我本地大概需要10秒左右,如果在服务器部署的项目中实际应用,可以在项目服务启动时只创建一个或几个(组成一个对象资源池),并启动这些officeManager,一直使用这些服务。

猜你喜欢

转载自www.cnblogs.com/xhj123/p/12585246.html