package com.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.el.base.old.control.PageHandle;
import com.el.resource.business.ResourceI;
import com.el.resource.business.ResourceImpl;
import com.el.util.dbutil.ExecuteSql;
public class ConvToOffice extends ExecuteSql implements Runnable{
private String id;
private String objid;
private String oldpath; //文件路径
private ExecuteSql es;
private static final Logger logger = Logger.getLogger(ConvToOffice.class);
ResourceI resource = new ResourceImpl();
ConvToOffice(String id,String objid,String oldpath,ExecuteSql es){
this.id = id;
this.oldpath = oldpath;
this.objid = objid;
this.es = es;
es.update(" update officeTrans set status = 1,addtime = now() where id ='"+id+"' ");
}
public void run() {
es.update(" update officeTrans set status = 2,starttime = now() where id ='"+id+"' ");
boolean b = true;
try {
if(!"".equals(oldpath)){
String docSourcePath = PageHandle.getViewKey("docSourcePath");
//转换成.pdf保存路径
String docPdfPath = PageHandle.getViewKey("docPdfPath");
//转换成.swf保存路径
String docSwfPath = PageHandle.getViewKey("docSwfPath");
String docImgPath = PageHandle.getViewKey("docImgPath");
//如果上传保存路径不存在,则递归创建目录
File d1 = new File(docSourcePath);
File d2 = new File(docPdfPath);
File d3 = new File(docSwfPath);
if(!d1.exists())
d1.mkdirs();
if(!d2.exists())
d2.mkdirs();
if(!d3.exists())
d3.mkdirs();
String fileName = oldpath;
//上传文件的后缀
String now = fileName.substring(0,fileName.lastIndexOf("."));
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//转换后.swf,名称与源文件一致
String saveSwf = now + ".swf";
int count = 0;
String savePdf = fileName;
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
if(os.startsWith("win") || os.startsWith("Win")){
boolean result = false;
if(!"pdf".equalsIgnoreCase(suffix)){
savePdf = now + ".pdf";
if("txt".equalsIgnoreCase(suffix)){
String saveOdt = now + ".doc";
File odtFile = new File(docSourcePath + saveOdt);
copyFile(new File(docSourcePath+fileName),odtFile);
result = OpenOfficeUtil.office2pdf(docSourcePath + odtFile, docPdfPath + savePdf);
}else{
result = OpenOfficeUtil.office2pdf(docSourcePath + fileName, docPdfPath + savePdf);
}
//转换成功,再将.pdf ----> .swf
if(result){
String imagePath = docImgPath + now +".jpg";
try {
if(!"pdf".equalsIgnoreCase(suffix)){
OpenOfficeUtil.pdf2swf(new File(docPdfPath + savePdf),new File(docSwfPath + saveSwf));
ImageTool.getPDFImg((docPdfPath + savePdf), imagePath, 0.5f);
}else{
File f = new File(docSourcePath + fileName);
logger.info(f);
OpenOfficeUtil.pdf2swf(f,new File(docSwfPath + saveSwf));
ImageTool.getPDFImg((docSourcePath + fileName), imagePath, 0.5f);
}
resource.ResourcePhoto((now+".jpg"), objid);
} catch (Exception e) {
b = false;
e.printStackTrace();
}
}else{
b = false;
}
}else{
b = false;
}
}else{
b = false;
}
}else{
b = false;
}
} catch (IOException e) {
b = false;
e.printStackTrace();
}
if(b){
es.update(" update officeTrans set status = 3,endtime = now() where id ='"+id+"' ");
}else{
es.update(" update officeTrans set status = 4,endtime = now() where id ='"+id+"' ");
}
}
private void copyFile(File sourceFile, File targetFile) throws IOException {
// TODO Auto-generated method stub
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
byte[] b = new byte[1024*5];
int len;
while((len = inBuff.read(b)) != -1){
outBuff.write(b, 0, len);
}
outBuff.flush();
inBuff.close();
outBuff.close();
output.close();
input.close();
}
}
package com.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
/**
* openOffice转换格式用
*/
public class OpenOfficeUtil {
private static OfficeManager officeManager;
private static String openOfficeHome = null;
private static String swfTools = null;
private static String office = null;
private static int openOfficePort;
private static String languagedir = null;
//加载配置文件
static{
InputStream in = OpenOfficeUtil.class.getResourceAsStream("/config/openoffice.properties");
Properties p = new Properties();
try {
p.load(in);
openOfficeHome = p.getProperty("openOfficeHome");
openOfficePort = Integer.parseInt(p.getProperty("openOfficePort"));
swfTools = p.getProperty("swfTools");
office = p.getProperty("office");
languagedir = p.getProperty("xpdf.path");
} catch (IOException e) {
e.printStackTrace();
}
}
//打开openOffice服务器
public static void startService() {
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
try {
System.out.println("启动office转换服务");
configuration.setOfficeHome(openOfficeHome); //设置OpenOffice.org安装目录
configuration.setPortNumbers(openOfficePort); // 设置转换端口,默认为8100
configuration.setTaskExecutionTimeout(1000 * 60 * 5L); //设置任务执行超时为5分钟
configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L); //设置任务队列超时为24小时
officeManager = configuration.buildOfficeManager();
officeManager.start(); //启动服务
} catch (Exception ce) {
System.out.println("office转换服务启动失败!详细信息:" + ce);
}
}
//关闭openOffice服务器
public static void stopService() {
System.out.println("关闭office转换服务");
if (officeManager != null) {
officeManager.stop();
}
}
/**
* 将Office文档转换为PDF. 运行该函数需要基于OpenOffice
* @param sourceFile office源文件
* @param targetFile pdf目标文件
* @return -1:找不到源文件或配置错误; 0:则表示操作成功; 1:转换失败;
*/
public static int office2PDF(String sourceFile, String targetFile) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return -1; //找不到源文件, 则返回-1
}
//如果目标路径不存在, 则新建该路径
File outputFile = new File(targetFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
//启动OpenOffice的服务
startService();
//转换
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
converter.convert(inputFile, outputFile);
System.out.println("转换成功!");
return 0;
}catch (Exception e) {
e.printStackTrace();
}finally{
//关闭连接和openOffice服务进程
try{
stopService();
}catch(Exception e){
e.printStackTrace();
}
}
return 1;
}
/**
* 通过swfTools将pdf转换成swf
* #TODO linux下有bug
*/
public static boolean pdf2swf(File pdfFile,File swfFile) throws Exception {
Runtime r = Runtime.getRuntime();
Properties prop = System.getProperties();
boolean b = true;
String os = prop.getProperty("os.name");
//windows(测试)
if(os.startsWith("win") || os.startsWith("Win")){
List<String> commend = new ArrayList<String>();
commend.add(swfTools);
commend.add(pdfFile.getPath());
commend.add("-o");
commend.add(swfFile.getPath());
commend.add("-T");
commend.add("9");
commend.add("-s");
commend.add("languagedir="+languagedir);
try {
System.out.println("开始执行:"+commend.toString());
ProcessBuilder builder = new ProcessBuilder(commend);
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();
//read the standard output
BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line="";
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
int ret = p.waitFor();
System.out.println("the return code is " + ret);
stdout.close();
System.out.println("swf转换成功!!");
} catch (Exception e) {
b = false;
e.printStackTrace();
throw e;
}
}else{ //other
try {
//linux下需要格式不一致(空格)
String str = swfTools + " " + pdfFile.getPath()+ " -o "+ swfFile.getPath() + " -T 9 ";
Process p = r.exec(str);
} catch (IOException e) {
b = false;
e.printStackTrace();
throw e;
}
}
return b;
}
/**
*
* @param officePath 文档路径(包含pdf)
* @param pdfPath pdf文件路径
* @param swfPath swf文件路径
* @return
*/
public static boolean office2swf(String officePath,String pdfPath,String swfPath){
Runtime r = Runtime.getRuntime();
BufferedReader br = null;
boolean officeResult = false;
boolean pdfResult = false;
try {
String str = office + " " + officePath +" "+ pdfPath + " " + swfPath + " " + swfTools;
Process p = r.exec(str);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
if(line.trim().equals("1")){
officeResult = true;
}
if(line.trim().equals("2")){
pdfResult = true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
String suffix = officePath.substring(officePath.lastIndexOf(".") + 1).toLowerCase();
if(!suffix.equals("pdf")){
if(officeResult && pdfResult){
return true;
}else{
return false;
}
}else{
if(pdfResult){
return true;
}else{
return false;
}
}
}
public static boolean office2pdf(String officePath,String pdfPath) {
Runtime r = Runtime.getRuntime();
BufferedReader br = null;
boolean officeResult = false;
try {
String str = office + " " + officePath +" "+ pdfPath ;
Process p = r.exec(str);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
if(line.trim().equals("1")){
officeResult = true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return officeResult;
}
//测试
public static void main(String[] args) {
String sourcePath = "D:\\Program Files\\apache-tomcat-7.0.55\\webapps\\www\\resource\\information\\source\\123456.ppt";
String destFile = "D:\\Program Files\\apache-tomcat-7.0.55\\webapps\\www\\resource\\information\\pdf\\123456.pdf";
office2pdf(sourcePath, destFile);
try {
pdf2swf(new File(destFile), new File("C:\\Users\\Administrator\\Desktop\\wang\\out\\"+System.currentTimeMillis()+".swf"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
FreeMarker配置
viewBasePath=D:\Program Files\apache-tomcat-7.0.55\webapps\www
上传文档原文件保存路径
docSourcePath=D:\Program Files\apache-tomcat-7.0.55\webapps\www\resource\information\source\
转换成.pdf文件保存路径
docPdfPath=D:\Program Files\apache-tomcat-7.0.55\webapps\www\resource\information\pdf\
转换后.swf文件保存路径
docSwfPath=D:\Program Files\apache-tomcat-7.0.55\webapps\www\resource\information\swf\
文档封面图片路径
docImgPath=D:/Program Files\apache-tomcat-7.0.55\webapps\www\resource\information\images\
#openOffice 安装目录
openOfficeHome=D:\OpenOffice 4
#openOffice 端口(默认)
openOfficePort=8100
office = C:/SWFTools/office2pdf.exe
#swfTools工具位置
swfTools=D:/swfTools/pdf2swf.exe
swfTools=C:/SWFTools/pdf2swf.exe
#swfTools需要载入的languagedir
xpdf.path=C:/xpdf/xpdf-chinese-simplified
#linux下需将swfTools命令注册到环境变量
#swfTools=pdf2swf