最近项目开发有个需求,用户上传文件可能是word、图片或者Pdf,传上去后统一转成pdf文件存入,并提供用户查看。经过网上各种查找,决定用openoffice的方式实现(openoffice怎么与java结合 百度都有,这里就不复制了)。以下是写了一个上传工具类,采用task-flow popup的方式调用,完成自动转换后,返回给调用者转换后的一个BlobDomain实例,具体步骤如下:
jspx页面:
<?xml version='1.0' encoding='UTF-8'?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:af="http://xmlns.oracle.com/adf/faces/rich" xmlns:tr="http://myfaces.apache.org/trinidad" xmlns:trh="http://myfaces.apache.org/trinidad/html"> <jsp:directive.page contentType="text/html;charset=UTF-8"/> <f:view> <af:document id="d1" title="请选择文件" initialFocusId="if2"> <af:resource type="javascript"> function setPanelHeight(){ clientHeight = document.documentElement.clientHeight; var tbProInfoItem = document.getElementById("pgl2"); tbProInfoItem.style.height=(clientHeight-35)+"px"; } </af:resource> <af:form id="f1" usesUpload="true"> <af:panelGroupLayout id="pgl1" layout="vertical" inlineStyle="min-height:0px; text-align:center;"> <af:panelGroupLayout id="pgl2" inlineStyle="text-align:center; width:95%;" halign="center" layout="horizontal"> <af:clientListener method="setPanelHeight()" type="load"/> <af:inputFile id="if2" value="#{FileUpload.file}" partialTriggers="cb1" binding="#{FileUpload.ifFile}" inlineStyle="margin-top: 25px;margin-bottom: 18px;" contentStyle="vertical-align:middle;line-height:18px;font-size:12px;height:23px;width:300px;"/> </af:panelGroupLayout> <trh:tableLayout id="tl1" width="100%"> <trh:rowLayout id="rl1"> <trh:cellFormat id="cf1" width="60%" height="30px;" valign="bottom" halign="left"> <af:outputText value="" id="ot1" partialTriggers="cb1" inlineStyle="width:300.0px; color:Red; font-size:12px;" binding="#{FileUpload.otMsg}"/> </trh:cellFormat> <trh:cellFormat id="cf2" width="40%" halign="right" valign="bottom"> <af:panelGroupLayout id="pgl3" layout="horizontal"> <af:commandButton text="上传" id="cb1" action="#{FileUpload.submit}"/> <af:commandButton text="取消" id="cb2" action="end"/> </af:panelGroupLayout> </trh:cellFormat> </trh:rowLayout> </trh:tableLayout> </af:panelGroupLayout> <af:poll id="p123" interval="60000" /> </af:form> <h:inputHidden id="init" binding="#{FileUpload.initPage}"/> </af:document> </f:view> </jsp:root>
managedbean:
package com.xxx.common.bean; import com.xxx.framework.common.MLogger; import com.xxx.framework.common.UIDGenerator; import com.xxx.util.Office2PDF; import com.xxx.util.Pic2PDF; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.faces.component.html.HtmlInputHidden; import oracle.adf.view.rich.component.rich.input.RichInputFile; import oracle.adf.view.rich.component.rich.output.RichOutputText; import oracle.adf.view.rich.context.AdfFacesContext; import oracle.jbo.domain.BlobDomain; import org.apache.log4j.Logger; import org.apache.myfaces.trinidad.model.UploadedFile; public class FileUpload { private RichInputFile ifFile; private RichOutputText otMsg; private HtmlInputHidden initPage; public FileUpload() { } /** * 记录系统日志 */ private static Logger logger = MLogger.getLogger(FileUpload.class); private UploadedFile _file; public void setFile(UploadedFile _file) { this._file = _file; } public UploadedFile getFile() { return _file; } public void setIfFile(RichInputFile ifFile) { this.ifFile = ifFile; } public RichInputFile getIfFile() { return ifFile; } public String submit() { AdfFacesContext afc = AdfFacesContext.getCurrentInstance(); Map pageMap=afc.getPageFlowScope(); String fileFlag=(String)pageMap.get("FileFlag"); BlobDomain blobDomain = null; Map resMap=new HashMap(); try { if("1".equals(fileFlag)){//直接传pdf this.upLoadPDF(blobDomain, resMap); }else if("2".equals(fileFlag)){//传图片 转 pdf this.pid2PDF(blobDomain, resMap); }else if("3".equals(fileFlag)){//传word 转 pdf this.word2PDF(blobDomain, resMap); }else{//不转pdf 直接存 this.upLoadAnyFile(blobDomain, resMap); } pageMap.put("returnMap", resMap); } catch (Exception e) { MLogger.logError(logger, "上传文件发生错误", e); this.setFile(null); otMsg.setValue(e.getMessage()); return null; } return "end"; } /** * pic 2 pdf * @param blobDomain * @param resMap * @throws Exception */ private void pid2PDF(BlobDomain blobDomain,Map resMap) throws Exception { OutputStream out = null; InputStream in=null; File inputFile = null; FileOutputStream fout =null; try { if (_file == null || _file.getLength() == 0) { throw new Exception("文件为空!"); } if (_file.getLength() > 52428800) { throw new Exception("文件过大,无法上传!"); } if (!_file.getFilename().endsWith(".jpg")) { throw new Exception("文件不是jpg格式!"); } blobDomain = new BlobDomain(); in = _file.getInputStream(); out = blobDomain.getBinaryOutputStream(); //定义文件名 String sourceFile=UIDGenerator.getUUID()+".jpg"; inputFile = new File(sourceFile); fout = new FileOutputStream(inputFile); byte[] buffer = new byte[1024 * 1024]; int byteRead = in.read(buffer); while (byteRead >= 0) { fout.write(buffer, 0, byteRead); fout.flush(); byteRead = in.read(buffer); } fout.close(); //调用转换接口 Pic2PDF.ToPdf(inputFile,out); String tempStr=this.getFile().getFilename(); resMap.put("FileName",tempStr.split("\\.")[0] ); resMap.put("FileBlob", blobDomain); } catch (Exception e) { MLogger.logError(logger, "上传文件发生错误", e); throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (fout != null) { fout.close(); } if (inputFile.exists()) { inputFile.delete(); } } } /** * upload pdf * @param blobDomain * @param resMap * @throws Exception */ private void upLoadPDF(BlobDomain blobDomain,Map resMap) throws Exception { OutputStream out = null; InputStream in=null; try { if (_file == null || _file.getLength() == 0) { throw new Exception("文件为空!"); } if (_file.getLength() > 52428800) { throw new Exception("文件过大,无法上传!"); } if (!_file.getFilename().endsWith(".pdf")) { throw new Exception("文件不是pdf格式!"); } blobDomain = new BlobDomain(); in = _file.getInputStream(); out = blobDomain.getBinaryOutputStream(); byte[] buffer1 = new byte[1024 * 1024]; int byteRead1 = in.read(buffer1); while (byteRead1 >= 0) { out.write(buffer1, 0, byteRead1); out.flush(); byteRead1 = in.read(buffer1); } String tempStr=this.getFile().getFilename(); resMap.put("FileName",tempStr.split("\\.")[0] ); resMap.put("FileBlob", blobDomain); } catch (Exception e) { MLogger.logError(logger, "上传文件发生错误", e); throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } /** * upload pdf * @param blobDomain * @param resMap * @throws Exception */ private void upLoadAnyFile(BlobDomain blobDomain,Map resMap) throws Exception { OutputStream out = null; InputStream in=null; try { if (_file == null || _file.getLength() == 0) { throw new Exception("文件为空!"); } if (_file.getLength() > 52428800) { throw new Exception("文件过大,无法上传!"); } blobDomain = new BlobDomain(); in = _file.getInputStream(); out = blobDomain.getBinaryOutputStream(); byte[] buffer1 = new byte[1024 * 1024]; int byteRead1 = in.read(buffer1); while (byteRead1 >= 0) { out.write(buffer1, 0, byteRead1); out.flush(); byteRead1 = in.read(buffer1); } String tempStr=this.getFile().getFilename(); resMap.put("FileName",tempStr.split("\\.")[0] ); resMap.put("FileBlob", blobDomain); } catch (Exception e) { MLogger.logError(logger, "上传文件发生错误", e); throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } /** * word 2 pdf * @param blobDomain * @param resMap * @throws Exception */ private void word2PDF(BlobDomain blobDomain,Map resMap) throws Exception { blobDomain=Office2PDF.word2PDF(this.getFile()); String tempStr=this.getFile().getFilename(); resMap.put("FileName",tempStr.split("\\.")[0] ); resMap.put("FileBlob", blobDomain); } public void setOtMsg(RichOutputText otMsg) { this.otMsg = otMsg; } public RichOutputText getOtMsg() { return otMsg; } private String fileName; public void setFileName(String fileName) { this.fileName = fileName; } public String getFileName() { return fileName; } public void setInitPage(HtmlInputHidden initPage) { this.initPage = initPage; } public HtmlInputHidden getInitPage() { return initPage; } }
Office2PDF.java
package com.xxx.util; import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter; import com.xxx.framework.common.MLogger; import com.xxx.framework.common.UIDGenerator; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import oracle.jbo.domain.BlobDomain; import org.apache.log4j.Logger; import org.apache.myfaces.trinidad.model.UploadedFile; public class Office2PDF { private static Logger logger = MLogger.getLogger(Office2PDF.class); public Office2PDF() { super(); } public static BlobDomain word2PDF(UploadedFile _file) throws Exception { OutputStream out = null; BlobDomain blobDomain = null; InputStream in=null; try { if (_file == null || _file.getLength() == 0) { throw new Exception("文件为空!"); } if (_file.getLength() > 52428800) { throw new Exception("文件为空!"); } if (!_file.getFilename().endsWith(".doc")) { throw new Exception("文件不是word2003格式!"); } blobDomain = new BlobDomain(); in = _file.getInputStream(); out = blobDomain.getBinaryOutputStream(); office2PDF(in,out); } catch (Exception e) { MLogger.logError(logger, "上传文件发生错误", e); throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } return blobDomain; } public static void office2PDF(InputStream in,OutputStream out) throws Exception { String sourceFile=UIDGenerator.getUUID()+".doc"; String destFile=UIDGenerator.getUUID()+".pdf"; File inputFile = new File(sourceFile); File outputFile = new File(destFile); try { FileOutputStream fout = new FileOutputStream(inputFile); byte[] buffer = new byte[1024 * 1024]; int byteRead = in.read(buffer); while (byteRead >= 0) { fout.write(buffer, 0, byteRead); fout.flush(); byteRead = in.read(buffer); } fout.close(); // connect to an OpenOffice.org instance running on port 8100 OpenOfficeConnection connection =null; connection = new SocketOpenOfficeConnection(8100); connection.connect(); // convert DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); // close the connection connection.disconnect(); FileInputStream fin=new FileInputStream(outputFile); byte[] buffer1 = new byte[1024 * 1024]; int byteRead1 = fin.read(buffer1); while (byteRead1 >= 0) { out.write(buffer1, 0, byteRead1); out.flush(); byteRead1 = fin.read(buffer1); } MLogger.logInfo(logger, "office2PDF---11"); } catch (Exception e) { throw e; } finally { if(inputFile!=null){ inputFile.delete(); MLogger.logInfo(logger, "office2PDF---inputFile.delete();"); } if(outputFile!=null){ outputFile.delete(); MLogger.logInfo(logger, "office2PDF---outputFile.delete();"); } } } }
下边是Linux 安装OpenOffice的步骤:
1.去官网 http://www.openoffice.org/ 下载对应版本
2.将安装包传到服务器上
3.进入安装包目录,执行命令
tar -xzvf Apache_OpenOffice_4.1.2_Linux_x86-64_install-rpm_zh-CN.tar.gz
cd /home/oracle/software/zh-CN/RPMS/
rpm –ivh *.rpm
cd desktop-integration/
rpm -ivh openoffice4.1.2-redhat-menus-4.1.2-9782.noarch.rpm
启动服务
/opt/openoffice4/program/soffice -headless -accept="socket,host=localhost,port=8100;urp;" -nofirststartwizard &
可能会需要开发端口
iptables -I INPUT -p tcp --dport 8100 -j ACCEPT
service iptables save
service iptables restart iptables