OpenOfice将offic转为pdf并且在web显示
1、将office首先要安装OpenOfice,傻瓜式安装就好了,之后可以使用下列代码将word转为pdf。这个需要导入jodconverter-2.2.2里的 ja r包
- import java.io.File;
import java.io.FileNotFoundException;import java.io.IOException;import java.net.ConnectException;import org.junit.Test;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.OpenOfficeDocumentConverter;publicclassOfficeChangeToPDF{/*** 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice下载地址为* http://www.openoffice.org/** <pre>** 方法示例:* String sourcePath = "F:\\office\\source.doc";* String destFile = "F:\\pdf\\dest.pdf";* Converter.office2PDF(sourcePath, destFile);* </pre>** @param sourceFile* 源文件, 绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc,* .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc* @param destFile* 目标文件. 绝对路径. 示例: F:\\pdf\\dest.pdf* @return 操作成功与否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置错误; 如果返回 0,* 则表示操作成功; 返回1, 则表示转换失败*/publicint office2PDF(String sourceFile,String destFile){try{File inputFile =newFile(sourceFile);if(!inputFile.exists()){return-1;// 找不到源文件, 则返回-1}// 如果目标路径不存在, 则新建该路径File outputFile =newFile(destFile);if(!outputFile.getParentFile().exists()){outputFile.getParentFile().mkdirs();}StringOpenOffice_HOME="C:\\Program Files (x86)\\OpenOffice 4";// 这里是OpenOffice的安装目录,// 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的// 如果从文件中读取的URL地址最后一个字符不是 '\',则添加'\'if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='\\'){OpenOffice_HOME+="\\";}// 启动OpenOffice的服务,也可以一直开启,那就不需要运行一次开启一次,提高效率String command =OpenOffice_HOME+"program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";Process pro =Runtime.getRuntime().exec(command);// connect to an OpenOffice.org instance running on port 8100OpenOfficeConnection connection =newSocketOpenOfficeConnection("127.0.0.1",8100);connection.connect();// convertDocumentConverter converter =newOpenOfficeDocumentConverter(connection);converter.convert(inputFile, outputFile);// close the connectionconnection.disconnect();// 关闭OpenOffice服务的进程pro.destroy();return0;}catch(FileNotFoundException e){e.printStackTrace();return-1;}catch(ConnectException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}return1;}@Testpublicvoid toPDF(){int office2pdf = office2PDF("C:\\Users\\HP\\Desktop\\xx.doc","C:\\Users\\HP\\Desktop\\xx.PDF");System.out.println(office2pdf);}}
2、要实现在web端预览pdf需要pdfobject插件,然后使用如下代码
<!DOCTYPE html><html><head><title>网页嵌入pdf浏览器</title><scripttype="text/javascript"src="./js/pdfobject.min.js"></script><styletype="text/css">.pdfobject-container { height:600px;}.pdfobject { border:1px solid #666; }</style></head><body><divid="example1"></div><scripttype="text/javascript">PDFObject.embed("./pdf/ELM-Chinese-Brief.pdf","#example1");</script></body></html>
附件列表

浙公网安备 33010602011771号