Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,496,113字

该文章投稿至Nemo社区   Java  板块 复制链接


OpenOffice2PDFUtil,使用OpenOffice转PDF

发布于 2016/11/01 11:34 2,469浏览 0回复 13,126

##昨天抽空做了下OpenOffice将office文档转PDF的操作,目前应该支持所有的office文件转化,不过可能个别的样式会有问题,所以。。。还是先记下来,留着备用。


====使用到的jar


<dependency>
    <groupId>com.artofsolving</groupId>
    <artifactId>jodconverter</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>com.artofsolving</groupId>
    <artifactId>jodconverter-core</artifactId>
    <version>3.0-beta-4</version>
</dependency>

=====源码

package com.nemo.utils;


import com.ict.web.commons.config.Global;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;

/**
 * 使用OpenOffice转换各种Office文档的工作
 * Created by Nemo on 2016/10/31
 */
public class OpenOffice2PDFUtil {

    /**
     * office中各种格式
     */
    private static final String[] OFFICE_POSTFIXS = { "doc", "docx", "xls", "xlsx", "ppt", "pptx" };
    private static ArrayList<String> Office_Formats = new ArrayList<String>();

    /**
     * pdf格式后缀定义
     */
    private static final String PDF_POSTFIX= "pdf";

    /**
     * 根据操作系统的名称,获取OpenOffice.org4的安装目录 如我的OpenOffice.org 4安装在:/opt/openoffice4
     */

    private static String getOfficeHome() {
        String osName = System.getProperty("os.name");

        //首先找配置,如果配置没有的话,则猜测一些默认路径
        String path = Global.getConfig("openOffice.homePath");
        if(path == null) {
            if (Pattern.matches("Linux.*", osName)) {
                return "/opt/openoffice4";
            } else if (Pattern.matches("Windows.*", osName)) {
                return "C:/Program Files/OpenOffice4";
            }
        }
        return path;
    }
    /**
     * 转换文件
     * @param inputFilePath
     * @param outputFilePath
     * @param converter
     */
    private static void converterFile(String inputFilePath, String outputFilePath,
                              OfficeDocumentConverter converter) {
        File inputFile=new File(inputFilePath);
        File outputFile = new File(outputFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        converter.convert(inputFile, outputFile);
    }

    /**
     * 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件
     *
     * @param inputFilePath
     *            源文件路径,如:"/home/nemo/test.docx"
     * @param outputFilePath
     *            如果指定则按照指定方法,如果未指定(null)则按照源文件路径自动生成目标文件路径,如:"/home/nemo/test_docx.pdf"
     * @return
     */
    private static boolean openOffice2Pdf(String inputFilePath, String outputFilePath) throws Exception {
        boolean flag = false;

        /*
         * 连接OpenOffice 并且启动OpenOffice
         */
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();

        // 获取OpenOffice4的安装目录
        String officeHome = getOfficeHome();
        config.setOfficeHome(officeHome);

        // 启动OpenOffice的服务
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();

        // 连接OpenOffice
        OfficeDocumentConverter converter = new OfficeDocumentConverter(
                officeManager);

        try {
            File inputFile = new File(inputFilePath);
            Collections.addAll(Office_Formats, OFFICE_POSTFIXS);
            if ((null != inputFilePath) && (inputFile.exists())) {
                // 判断目标文件路径是否为空
//                if (Office_Formats.contains(getPostfix(inputFilePath))) {
                    if (null == outputFilePath) {
                        // 转换后的文件路径
                        String outputFilePath_new = generateDefaultOutputFilePath(inputFilePath);
                        converterFile(inputFilePath, outputFilePath_new, converter);
                        flag = true;

                    } else {
                        converterFile(inputFilePath, outputFilePath, converter);
                        flag = true;
                    }
//                }

            } else {
                System.out.println("con't find the resource");
            }
        }catch (Exception e){
          //防止异常不能再往下关闭服务,服务必须关闭,否则下次调用可能会有问题
            officeManager.stop();
            return false;
        }

        officeManager.stop();
        return flag;
    }

    /**
     * 如果未设置输出文件路径则按照源文件路径和文件名生成输出文件地址。例,输入为 /home/nemo/fee.xlsx 则输出为/home/nemo/fee_xlsx.pdf
     */
    private static String generateDefaultOutputFilePath(String inputFilePath) {
        String outputFilePath = inputFilePath.replaceAll("."
                + getPostfix(inputFilePath), "_" + getPostfix(inputFilePath)
                + ".pdf");
        return outputFilePath;
    }

    /**
     * 获取inputFilePath的后缀名,如:"/home/nemo/test.pptx"的后缀名为:"pptx"
     */
    private static String getPostfix(String inputFilePath) {
        String[] p = inputFilePath.split("\\.");
        if (p.length > 0) {// 判断文件有无扩展名
            // 比较文件扩展名
            return p[p.length - 1];
        } else {
            return null;
        }
    }

    /**
     * 对外提供的获取PDF的方法,只需要传入一个需要转化的文件路径和文件名称即可,这里会直接返回生成的PDF文件路径
     * @param filePath
     * @return  返回新文件的地址
     */
    public static String getPDF(String filePath,String fileName){
        if(fileName==null) {
            return null;
        }

    //拼接新后缀
        String outFileName = fileName + "." + PDF_POSTFIX;
        if(fileName.lastIndexOf(".")!=-1){
           outFileName = fileName.substring(0,fileName.lastIndexOf("."))+fileName.substring(fileName.lastIndexOf("."),fileName.length()).replace(".","_") + "." +PDF_POSTFIX;
        }

        String outFilePath = filePath + "/temp/"; //转换后的文件存储路径
        File outFile = new File(outFilePath + outFileName);
        if(outFile.exists()){//如果该文件已经转换过,则直接返回即可
            return outFilePath + outFileName;
        }else {
            try {
                boolean result = openOffice2Pdf(filePath + fileName, outFilePath + outFileName);
                if(!result) return filePath + fileName;
            }catch (Exception e){
                return filePath + fileName;
            }
            return outFilePath + outFileName;
        }
    }

    public static void main(String[] args) {

        try {
            String result = getPDF("/home/nemo/pdf/","ta.docx");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
本文标签
 {{tag}}
点了个评