java中office文档的pdf转换

需安装open office插件

package com.jeecms.common.office2pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

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

/**
 * 将Office文档转换为PDF文档
 * @author BaiFL
 */
public class Office2PDF {

 /**
  * 环境变量下面的url.properties的绝对路径
  */
 private static final String URL_PATH = Thread.currentThread()
   .getContextClassLoader().getResource("").getPath().replace("%20", " ")
   + "com/jeecms/common/office2pdf/url.properties";

 /**
  * 将Office文档转换为PDF
  * @param sourceFile 源文件绝对路径
  *   包括.doc, .docx, .xls, .xlsx, .ppt, .pptx等
  * @return result 目标文件绝对路径
  */
 public static String office2PDF(String sourceFile) {
  //返回值
  String result = null;
  try {
   File inputFile = new File(sourceFile);
   if (!inputFile.exists()) {
    return null; //找不到源文件, 则返回-1
   }
   
   /**
    * 目标文件为原文件路径及原文件名.pdf,如果目标路径不存在, 则新建该路径
    * sourceFile:“source.doc”
    * targetFile:“source.pdf”
    */
   String targetFile = sourceFile.substring(0, sourceFile.lastIndexOf(".")) + ".pdf";
   File outputFile = new File(targetFile);
   if (!outputFile.getParentFile().exists()) {
    outputFile.getParentFile().mkdirs();
   }
   
   
   //从url.properties文件中读取OpenOffice的安装根目录
   Properties prop = new Properties();
   // 属性文件输入流
   FileInputStream fis = new FileInputStream(URL_PATH);
   // 将属性文件流装载到Properties对象中
   prop.load(fis);
   // 关闭流
   fis.close();

   //OpenOffice在windows/linux系统下的安装路径
   String OPENOFFICE_HOME = prop.getProperty("OPENOFFICE_HOME");
   
   if (OPENOFFICE_HOME == null){
    return null; //找不到安装路径
   }
   
   //检查安装路径是否以“/”结尾
   if (OPENOFFICE_HOME.charAt(OPENOFFICE_HOME.length() - 1) != '/') {
    OPENOFFICE_HOME += "/";
   }
   
   DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
   configuration.setOfficeHome(new File(OPENOFFICE_HOME));// 设置OpenOffice.org安装目录
   configuration.setPortNumbers(8100); // 设置转换端口,默认为8100
   configuration.setTaskExecutionTimeout(1000 * 60 * 1L);// 设置任务执行超时为1分钟
   configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时为24小时

   OfficeManager officeManager = configuration.buildOfficeManager();
   //启动服务
   officeManager.start();
   OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
   //执行转换
   converter.convert(inputFile, outputFile);
   if (officeManager != null) {
    officeManager.stop();
   }
   result = targetFile;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
  }
  return result;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值