最近由于项目需要做一个文档上传并在线预览的功能,做了一些尝试,也遇到了一些困难,也查了不少资料。
下面把尝试的情况记录下来,也希望做过类似和想要做类似工作的小伙伴们能一起探讨下。
这里有几个网址可以让大家参考的:
http://blog.csdn.net/youthon/article/details/32717471
http://www.iteye.com/topic/1005741
我也是按照网上提供的思路先将office转换为pdf再生成swf
一、安装必要的软件支持
1)Openoffice
2)SWFTools(pdf生成swf用)
3)FlexPaper(前台预览用)
二、编写代码
创建一个工具类package servlet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
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;
public class Office2PDF {
/**
* 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice下载地址为
* http://www.openoffice.org/
* 方法示例:
* String sourcePath = "F:\\office\\2017-4-19165856.xls";
* String destFile = "F:\\pdf\\2017-4-19165856.pdf";
* Converter.office2PDF(sourcePath, destFile);
*
*
* @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, 则表示转换失败
*/
public static int office2PDF(String sourceFile, String destFile) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return -1;// 找不到源文件, 则返回-1
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);
// close the connection
connection.disconnect();
return 0;
} catch (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
/*public static void main(String[] args) {
System.out.println(Office2PDF.office2PDF("F:/sourceFile/2017-4-18145153.docx", "F:/pdfFile/2017-4-18145153.pdf"));
}*/
}
package servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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;
/*
* @author wsc
* 将MS的word,excel,ppt,d等转换成pdf,在用swfTools转换成swf,最后用flexPaper在网页中显示,实现在线预览功能
* 实现方式:Txt/Word/Excel/PPT=>PDF(OpenOffice+JodConverter)=>SWF(pdf2swf)=>FlexPaper浏览
* 服务器端需要安装的软件和引入的类包:(本人用的版本)jodconverter-2.2.2类包,Apache_OpenOffice_incubating_3.4.1_Win_x86_install_zh-CN.exe
* swftools-0.9.1.exe, FlexPaper_1.4.5_flash
*/
@SuppressWarnings("serial")
/*
* 这是一个servlet,运行它参见web.xml的部署,本例为http://127.0.0.1:8080/readonline/convertUtil
*/
public class ConvertServlet extends HttpServlet{
private File sourceFile; //转换源文件
private File pdfFile; //PDF目标文件
private File swfFile; //SWF目标文件
private Runtime r;
public void init() throws ServletException {
/*
* 文件夹名称不要有空格,否则容易转换出错,文件名为中文时貌似无效(待解决)
*/
sourceFile = new File("D:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/readonline/sourceFile/2017-4-18145153.docx");
pdfFile = new File("D:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/readonline/pdfFile/2017-4-18145153.pdf");
swfFile = new File("D:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/readonline/FlexPaper/swfFiles/2017-4-18145153.swf");
System.out.println("第一步:生成文件对象,准备转换");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println(sourceFile.exists());
/*
* 转换成pdf文件
* 项目执行需要启动OpenOffice服务,在系统命令窗口执行命令。
* cd C:\Program Files (x86)\OpenOffice.org 3\program
* soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
*/
if(sourceFile.exists()) {
if(!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
/*connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(sourceFile, pdfFile);
pdfFile.createNewFile();
connection.disconnect(); */
Office2PDF.office2PDF(sourceFile.toString(), pdfFile.toString());
System.out.println("第二步:转换为PDF格式 路径" + pdfFile.getPath());
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
System.out.println("读取文件失败");
throw e;
} catch (Exception e){
e.printStackTrace();
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("已转换为PDF,无需再次转换");
}
} else {
System.out.println("要转换的文件不存在");
}
/*
* 转换成swf文件
*/
r = Runtime.getRuntime();
if(!swfFile.exists()){
if(pdfFile.exists()) {
try {
//注意cmdString字符串之间的空格否则转化失败
String cmdString = "C:/Program Files/SWFTools/pdf2swf.exe -o \"" + swfFile.getPath() + "\" -t \"" + pdfFile.getPath() + "\"";
System.out.println(cmdString);
Process p = r.exec(cmdString);
p.waitFor();
swfFile.createNewFile();
System.out.println(swfFile.length());
System.out.println("第三步:转换为SWF格式 路径:" + swfFile.getPath());
System.out.println("第四步:转换为SWF格式 名称:" + swfFile.getName());
//下面这段代码保留pdf文件(根据用户需要)当执行两次以上的时候pdf文件会保留下来
if(pdfFile.exists()) {
//pdfFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("PDF文件不存在,无法转换");
}
} else {
System.out.println("已经转为SWF文件,无需再次转换");
}
/*
* HttpSession的设置,为了跳转的页面能拿到文件名,注意:session只在服务器开的时候有效
*/
HttpSession session = req.getSession(true);
System.out.println("这是什么文件:"+swfFile.getName());
session.setAttribute("fileName", swfFile.getName());
System.out.println(swfFile.getName());
resp.sendRedirect(req.getContextPath()+"/readFile.jsp");
System.out.println("跳转页面:"+req.getContextPath()+"/readFile.jsp");
System.out.println(session.getAttribute("fileName"));
}
}
convertUtil
servlet.ConvertServlet
convertUtil
/convertUtil
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
在线预览
<%
String filename=(String)session.getAttribute("fileName");//(String)request.getParameter("filename");
%>
测试FileName
用cmd进入openoffice的安装文件目录下
C:\Program Files (x86)\OpenOffice.org 3\program(有program文件夹的才是正确的安装文件目录,之前就在这卡了一下)
输入:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"
直接访问localhost:8089/readonline/convertUtil
经常遇到的报错:
java.net.ConnectException: connection failed: socket,host=127.0.0.1,port=8100,tcpNoDelay=1: java.net.ConnectException: Connection refused: connect
at com.artofsolving.jodconverter.openoffice.connection.AbstractOpenOfficeConnection.connect(AbstractOpenOfficeConnection.java:79)
at servlet.Office2PDF.office2PDF(Office2PDF.java:49)
at servlet.ConvertServlet.doPost(ConvertServlet.java:72)
at servlet.ConvertServlet.doGet(ConvertServlet.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
可以检查下是不是服务没有开启,或者是端口占用等。
FlexPaper遮挡div可以参考
http://blog.csdn.net/amino77/article/details/17994203
这时候有时可能会出现滚动条失效的问题,这是由于FlexPaper版本低的问题,可以找个高点的试试。