最近搞web项目,使用框架SpringMVC+iBatis实现,做到项目里面一个附件在线预览功能,试过无数的方法,最后得到了一个非常使用的方法,这方法也是我看过多篇博客总结前人的文章出来的,仅限参考。
我们先来看看效果图
第一步:
通过第三方软件openoffice将office文档ppt,pptx,doc,docx,xls,xlsx转换成pdf文档;
openoffice下载链接:http://www.openoffice.org/zh-cn/download/,
第二步:
JODConverter一个Java的OpenDocument 文件转换器,导入其相关的jar包
下载地址:http://download.csdn.net/download/a514224717/9974560
第三步:
进行安装文件,在进行项目开发前,必须启动openoffice,我这里不需要之前启动openoffice,启动openoffice写在代码中,使用代码进行启动;不过你唯一要改的就是你的openoffice安装路径,这里在后边我会说到的。
上面相关jar包导入后,而且openoffice也安装好后,就可以进行项目开发:
首先给出工具类,很重要:
package com.askingdee.htgl.common.utils;
import java.io.File;
import java.util.Date;
import java.util.regex.Pattern;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
/**
* 这是一个工具类,主要是为了使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx)
* 转化为pdf文件<br>
*
* @date 2017-09-11
* @author zt
*
*/
public class Office2PDF {
/**
* office中.doc格式
*/
public static final String OFFICE_DOC = "doc";
/**
* office中.docx格式
*/
public static final String OFFICE_DOCX = "docx";
/**
* office中.xls格式
*/
public static final String OFFICE_XLS = "xls";
/**
* office中.xlsx格式
*/
public static final String OFFICE_XLSX = "xlsx";
/**
* office中.ppt格式
*/
public static final String OFFICE_PPT = "ppt";
/**
* office中.pptx格式
*/
public static final String OFFICE_PPTX = "pptx";
/**
* pdf格式
*/
public static final String OFFICE_TO_PDF = "pdf";
public static void main(String[] args) {
Office2PDF office2pdf = new Office2PDF();
office2pdf.openOfficeToPDF("e:/test." + OFFICE_DOCX, "e:/test_" + new Date().getTime() + "." + OFFICE_TO_PDF);
office2pdf.openOfficeToPDF("e:/test." + OFFICE_PPTX, null);
}
/**
* 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件<br>
*
* @param inputFilePath
* 源文件路径,如:"e:/test.docx"
* @param outputFilePath
* 目标文件路径,如:"e:/test_docx.pdf"
* @return
*/
public boolean openOfficeToPDF(String inputFilePath, String outputFilePath) {
return office2pdf(inputFilePath, outputFilePath);
}
/**
* 根据操作系统的名称,获取OpenOffice.org 3的安装目录<br>
* 如我的OpenOffice.org 3安装在:C:/Program Files (x86)/OpenOffice.org 3<br>
*
* @return OpenOffice.org 3的安装目录
*/
public String getOfficeHome() {
String osName = System.getProperty("os.name");
if (Pattern.matches("Linux.*", osName)) {
return "/opt/openoffice.org4";
} else if (Pattern.matches("Windows.*", osName)) {
return "C:/Program Files (x86)/OpenOffice 4";
} else if (Pattern.matches("Mac.*", osName)) {
return "/Application/OpenOffice.org.app/Contents";
}
return null;
}
/**
* 连接OpenOffice.org 并且启动OpenOffice.org
*
* @return
*/
public OfficeManager getOfficeManager() {
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
// 获取OpenOffice.org 3的安装目录
String officeHome = getOfficeHome();
config.setOfficeHome(officeHome);
// 启动OpenOffice的服务
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start();
return officeManager;
}
/**
* 转换文件
*
* @param inputFile
* @param outputFilePath_end
* @param inputFilePath
* @param outputFilePath
* @param converter
*/
public void converterFile(File inputFile, String outputFilePath_end, String inputFilePath, String outputFilePath, OfficeDocumentConverter converter) {
File outputFile = new File(outputFilePath_end);
// 假如目标路径不存在,则新建该路径
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
converter.convert(inputFile, outputFile);
System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
}
/**
* 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件<br>
*
* @param inputFilePath
* 源文件路径,如:"e:/test.docx"
* @param outputFilePath
* 目标文件路径,如:"e:/test_docx.pdf"
* @return
*/
public boolean office2pdf(String inputFilePath, String outputFilePath) {
boolean flag = false;
OfficeManager officeManager = getOfficeManager();
// 连接OpenOffice
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
long begin_time = new Date().getTime();
if (null != inputFilePath) {
File inputFile = new File(inputFilePath);
// 判断目标文件路径是否为空
if (null == outputFilePath) {
// 转换后的文件路径
String outputFilePath_end = getOutputFilePath(inputFilePath);
if (inputFile.exists()) {// 找不到源文件, 则返回
converterFile(inputFile, outputFilePath_end, inputFilePath, outputFilePath, converter);
flag = true;
}
} else {
if (inputFile.exists()) {// 找不到源文件, 则返回
converterFile(inputFile, outputFilePath, inputFilePath, outputFilePath, converter);
flag = true;
}
}
officeManager.stop();
} else {
System.out.println("con't find the resource");
}
long end_time = new Date().getTime();
System.out.println("文件转换耗时:[" + (end_time - begin_time) + "]ms");
return flag;
}
/**
* 获取输出文件
*
* @param inputFilePath
* @return
*/
public String getOutputFilePath(String inputFilePath) {
String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
return outputFilePath;
}
/**
* 获取inputFilePath的后缀名,如:"e:/test.pptx"的后缀名为:"pptx"<br>
*
* @param inputFilePath
* @return
*/
public String getPostfix(String inputFilePath) {
return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
}
}
配置servert的xml
<!-- 预览附件Servlet -->
<servlet>
<servlet-name>YulanServlet</servlet-name>
<servlet-class>com.askingdee.htgl.common.servlet.YulanServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>YulanServlet</servlet-name>
<url-pattern>/a/servlet/YulanServlet/*</url-pattern>
</servlet-mapping>
YulanServlet代码
package com.askingdee.htgl.common.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.askingdee.htgl.common.config.Global;
import com.askingdee.htgl.common.utils.DateUtils;
import com.askingdee.htgl.common.utils.Office2PDF;
/**
* 附件预览Servlet
* @author ZT
* @version 2017-09-08
*/
public class YulanServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Logger logger = LoggerFactory.getLogger(getClass());
public void fileOutputStream(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String allfilenameFirst = request.getParameter("filename"); // 获得请求文件名
int startFileType = allfilenameFirst.lastIndexOf(".");
String fileType = (allfilenameFirst.substring(startFileType + 1)).toLowerCase();
String allfilename = allfilenameFirst.replace("/"+Global.PROJECT_NAME, "");
int start = allfilename.lastIndexOf("/");
String fileName = allfilename.substring(start + 1);
String path = allfilename.replace(fileName, "");
if(fileType.equals("doc")||fileType.equals("docx")||fileType.equals("xls")||fileType.equals("xlsx")||fileType.equals("ppt")||fileType.equals("pptx")){
logger.info("-----------预览doc/xls/ppt:" + allfilename + "-----------");
String realpathdir = request.getSession().getServletContext().getRealPath(allfilename);
Office2PDF office2pdf = new Office2PDF();
long tempFileName = new Date().getTime();
String realAllFilePath = allfilename.replace("/", "\\");
String dxxPath = realpathdir.replace(realAllFilePath, ""); //绝对路径
office2pdf.openOfficeToPDF(realpathdir, dxxPath+"/temp"+ DateUtils.getDate("yyyyMMdd") +"/" + tempFileName + ".pdf");
response.sendRedirect(request.getContextPath() + "/temp"+ DateUtils.getDate("yyyyMMdd") +"/" + tempFileName + ".pdf");//预览 By相对路径
}else {
logger.info("-----------预览pdf/jpg/png/gif:" + allfilename + "-----------");
String fileNameEncode = java.net.URLEncoder.encode(fileName.toString(),"utf-8");
response.sendRedirect(request.getContextPath() + path + fileNameEncode);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
fileOutputStream(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
fileOutputStream(request, response);
}
}
文件转换成pdf调用的方法
office2pdf.openOfficeToPDF(filePath, 你需要存储的路径+"/" + 文件名 +".pdf");
经过检查,office系列文档ppt,pptx,xls,xlsx,doc,docx都能够预览。