java 将Office文档转换为PDF

import com.shineyoo.manager.util.common.config.Global;

import org.jodconverter.JodConverter;
import org.jodconverter.office.LocalOfficeManager;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;

public class PdfConverterUtils {

public static final Logger LOGGER = LoggerFactory.getLogger(PdfConverterUtils.class);

/**
 * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice
 * <pre>
 * 方法示例:
 * String sourcePath = "D:\\office\\source.doc";
 * String destFile = "D:\\pdf\\dest.pdf";
 * Converter.office2PDF(sourcePath, destFile);
 * </pre>
 *
 * @param sourceFile 源文件, 绝对路径. 可以是Office2003-2007全部格式的文档, 包括.doc,
 *                   .docx, .xls, .xlsx, .ppt, .pptx等. 示例: D:\\office\\source.doc
 * @param destFile   目标文件. 绝对路径. 示例: D:\\pdf\\dest.pdf
 * @return 操作成功与否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置错误; 如果返回 0,
 * 则表示操作成功; 返回1, 则表示转换失败
 */
public static int office2PDF(String sourceFile, String destFile) {
    File inputFile = new File(sourceFile);
    if (!inputFile.exists()) {
        return -1;// 找不到源文件, 则返回-1
    }
    // 如果目标路径不存在, 则新建该路径
    File outputFile = new File(destFile);
    if (!outputFile.getParentFile().exists()) {
        outputFile.getParentFile().mkdirs();
    }
    // Create an office manager using the default configuration.
    // The default port is 2002. Note that when an office manager
    // is installed, it will be the one used by default when
    // a converter is created.
    final LocalOfficeManager officeManager;

    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        officeManager = LocalOfficeManager.install();
    } else {
        officeManager = LocalOfficeManager.builder()
                .officeHome(Global.getConfig("office.home.linux"))
                .portNumbers(Integer.parseInt(Global.getConfig("openOfficePort")))
                .install()
                .build();
    }

    try {
        officeManager.start();
        JodConverter.convert(inputFile)
                .to(outputFile)
                .execute();

        return 0;
    } catch (OfficeException e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        OfficeUtils.stopQuietly(officeManager);
    }

    return 1;
}

public static void main(String[] args) throws FileNotFoundException {

// int i=PdfConverterUtils.office2PDF("/home/1234.docx","/home/result-pdf/"+Math.random()+".pdf");
// int b=PdfConverterUtils.office2PDF("/home/test1.xlsx","/home/result-pdf/"+Math.random()+".pdf");
// int c=PdfConverterUtils.office2PDF("/home/5678.pptx","/home/result-pdf/"+Math.random()+".pdf");
//
// System.out.println(“转变换结果----------- docx=”+i+" xlsx="+b+" “+” pptx="+c);
// office2PDF(“E:/1.doc”, “E:/1.pdf”);
office2PDF(“C:\Users\lip\Desktop\history\1.docx”, “C:\Users\lip\Desktop\1.pdf”);
}
}

猜你喜欢

转载自blog.csdn.net/qq_27319683/article/details/84848889