Java实现office文档与pdf文档的在线预览功能
最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完。压力略大。后面查找百度资料、以及在同事与网友的帮助下,四天多把它做完。查找资料发现我们要实现的过程就是把office转换成pdf,当然pdf就不用转换了。然后在pdf转换为swf文件,在浏览器实现预览swf文件。整个过程就是这样,看起来很简单,实际操作起来会出现各种问题。下面我就把自己写的这一小功能记录下来。
1、首先我们需要找到可以把office转换成pdf的方法,查找资料发现有openoffice这一软件可以把office转换成pdf,这一软件先下载下来,然后记住自己安装的在那个位置。然后在cmd环境下进入安装目录的program目录,输入打开openoffice的命令:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
输入完成之后在任务管理器可以看见soffice.bin的进程在任务管理器,这一服务就启动成功。当然在代码中转换office2pdf我们还需要一些架包。下载jodconverter-2.2.2架包,然后复制到lib目录下,引入架包就可以了。这个架包有如下包:
有一些项目重复的可以删除,根据实际情况自己处理。
2、我们需要找到转换pdf2swf的方法。查找资料发现swftools这个软件可以把pdf转换成swf文件。把它下下来安装好就可以了。
3、我们需要一个展示swf文件的容器,发现有flexpaper这个插件。而且展示效果还不错。所以我们需要下载这个插件。使用这个插件需要有三个js文件。分别是:jquery.js、flexpaper_flash.js、flexpaper_flash_debug.js。插件的名字是FlexPaperViewer.swf。
整个项目结如下:
准备工作完成下面开始编码.
转换类为DocConverter 的代码:
package com.cectsims.util; import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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; /**
* doc docx格式转换
*/
public class DocConverter {
private static final int environment = 1;// 环境 1:Windows 2:Linux
private String fileString;// (只涉及PDF2swf路径问题)
private String outputPath = "";// 输入路径 ,如果不设置就输出在默认 的位置
private String fileName;
private File pdfFile;
private File swfFile;
private File docFile; public DocConverter(String fileString) {
ini(fileString);
System.out.println("文件路径"+fileString);
} /**
* * 重新设置file
*
* @param fileString
* 32.
*/
public void setFile(String fileString) {
ini(fileString);
} /**
* * 初始化
*
* @param fileString
*
*/
private void ini(String fileString) {
this.fileString = fileString;
fileName = fileString.substring(0, fileString.lastIndexOf("."));
docFile = new File(fileString);
pdfFile = new File(fileName+ ".pdf");
swfFile = new File(fileName+ ".swf");
} /**
* 转为PDF
*
* @param file
*
*/
private void doc2pdf() throws Exception {
if (docFile.exists()) {
if (!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(docFile, pdfFile);
// close the connection
connection.disconnect();
System.out.println("****pdf转换成功,PDF输出: "+ pdfFile.getPath() + "****");
} catch (java.net.ConnectException e) {
e.printStackTrace();
System.out.println("****swf转换器异常,openoffice 服务未启动!****");
throw e;
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
System.out.println("****swf转换器异常,读取转换文件 失败****");
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else {
System.out.println("****已经转换为pdf,不需要再进行转化 ****");
}
} else {
System.out.println("****swf转换器异常,需要转换的文档不存在, 无法转换****");
}
} /** * 转换成 swf */
@SuppressWarnings("unused")
private void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1) {// windows环境处理
try {
Process p = r.exec("D:/Program/swfttools/pdf2swf.exe "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.out.print(loadStream(p.getInputStream()));
System.err.println("****swf转换成功,文件输出: "+swfFile.getPath() + "****");
if (pdfFile.exists()){
pdfFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
} else if (environment == 2) {// linux环境处理
try {
Process p = r.exec("pdf2swf" + pdfFile.getPath()+ " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.err.println("****swf转换成功,文件输出: "+ swfFile.getPath() + "****");
if (pdfFile.exists()) {
pdfFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
} else {
System.out.println("****pdf不存在,无法转换****");
}
} else {
System.out.println("****swf已经存在不需要转换****");
}
} static String loadStream(InputStream in) throws IOException {
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while ((ptr = in.read()) != -1) {
buffer.append((char) ptr);
}
return buffer.toString();
} /**
* * 转换主方法
*/
@SuppressWarnings("unused")
public boolean conver() {
if (swfFile.exists()) {
System.out.println("****swf转换器开始工作,该文件已经转换为 swf****");
return true;
}
if (environment == 1) {
System.out.println("****swf转换器开始工作,当前设置运行环境 windows****");
} else {
System.out.println("****swf转换器开始工作,当前设置运行环境 linux****");
}
try {
doc2pdf();
pdf2swf();
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println("文件存在吗?"+swfFile);
if (swfFile.exists()) {
System.out.println("存在");
return true;
} else {
System.out.println("不存在");
return false;
}
} /**
*返回文件路径
* @param
*/
public String getswfPath(){
if (this.swfFile.exists()){
String tempString = swfFile.getPath();
tempString = tempString.replaceAll("\\\\", "/");
System.out.println("最后文件路径为"+tempString);
return tempString;
} else {
return "文件不存在";
}
} /**
* 设置输出路径
*
* @param outputPath
*/
public void setOutputPath(String outputPath){
this.outputPath = outputPath;
if (!outputPath.equals("")) {
String realName = fileName.substring(fileName.lastIndexOf("/"),
fileName.lastIndexOf("."));
if (outputPath.charAt(outputPath.length()) == '/') {
swfFile = new File(outputPath + realName + ".swf");
} else {
swfFile = new File(outputPath + realName + ".swf");
}
}
}
}
调用转换类只需要传word、ptt、excel、pdf文件所在的路径参数就可以了。
展示在线预览的jsp代码如下:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String swfFilePath=session.getAttribute("swfpath").toString();
System.out.println("展示路径"+swfFilePath);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="Content-Type">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/flexpaper_flash.js"></script>
<script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>
<!-- <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/flexpaper.js"></script>
<script type="text/javascript" src="js/flexpaper_handlers.js"></script>-->
<style type="text/css" media="screen">
html,body{
height: 100%;
}
body{
margin: 0;
padding: 0;
overflow: auto;
}
#flashContent{
display: none;
}
</style>
<title>在线文档预览</title>
</head>
<body>
<div style="position: absolute; left:50px;top:10px;">
<a id="viewerPlaceHolder" style="width: 820px;height: 650px;display: block;"></a>
<script type="text/javascript">
var fp=new FlexPaperViewer('FlexPaperViewer','viewerPlaceHolder',{config:{SwfFile:escape('<%=swfFilePath%>'),Scale:1.2,
ZoomTransition:'easeOut',ZoomTime:0.5,ZoomInterval:0.2,FitPageOnLoad:false,FitWidthOnload:false,
FullScreenAsMaxWindow:false,ProgressiveLoading:false,MinZoomSize:0.2,MaxZoomSize:5,SearchMatchAll:false,
InitViewMode:'SinglePage',RenderingOrder : 'flash',ViewModeToolsVisible:true,ZoomToolsVisible:true,NavToolsVisible:true,CursorToolsVisible:true,
SearchToolsVisible:true,localeChain:'en_US'}});
</script>
</div>
</body>
</html>
其中可能会出现在线预览只能实现10页的情况,需要把RenderingOrder : 'flash',设置为flash才可以实现超过10页的在线预览。swfFilePat为转换后的文件所在路径。
转换后面的效果如下:
注意问题:
1、发现错误一般是openoffice服务没有开启。
2、Linux环境下会存在中文乱码的问题,是linux下不像windows支持那么多字体,需要安装多的字体,并且把字体所在位置链接到flexpaper所在位置。在使用pdf2swf加上参数-s languagedir=/usr/local/xpdf-chinese-simplified/。具体的一些参数请百度。
源代码已经在我的github上了,可以访问https://github.com/liaowp/OnlinePreview,也可以点击我博客的github标签。
如果有问题可以加QQ群咨询。178737461
Java实现office文档与pdf文档的在线预览功能的更多相关文章
- Java实现在线预览功能
java实现在线预览功能,需要用到 jacob.dll jacob.jar 预览pdf所需js pdfobject.min.js 将上传文件转为pdf保存. <div class=&qu ...
- pdf.js实现图片在线预览
项目需求 前段时间项目中遇到了一个模块,是关于在线预览word文档(PDF文件)的,所以,找了很多插件,例如,pdf.js,pdfobject.js框架,但是pdfobject.js框架对于IE浏览器 ...
- pdf word excel ppt 在线预览方案收集
https://www.idocv.com/docs.html http://www.cnblogs.com/wolf-sun/p/3569960.html http://coolwanglu.git ...
- pc或者微信上用pdf.js在线预览pdf和word
最近项目要求pdf和word可以在线预览功能,pc端还好解决,但是微信端就有点坑了,pc端原来的思路是将文件转成base64,然后用html格式显示 ,但是微信端不支持, 这种方式就pass掉了,谷歌 ...
- word文档在线预览解决方案
花了一整天在网上翻关于 “word文档在线预览解决方案” 相关的资料,感觉实现难度比较大还是用PDF来解决好了.. 下面列一下比较好的参考资料吧 参考资料 前端实现在线预览pdf.word.xls.p ...
- 基于CA认证(结合文档在线预览)的电子签章解决方案
分享一个基于CA认证(结合文档在线预览)的电子签章实现思路,恰巧是最近项目中遇到的,欢迎大家一起讨论. 一. 项目背景 在公司业务系统中,按照传统的签章方式,存在以下痛点: 1.成本高,体现在纸质合同 ...
- 浏览器在线预览pdf、txt、office文件
//使用文件预览的原因是:TMD微信浏览器屏蔽掉文件下载链接,只好折中使用文件在线预览功能//要点:1.office文件用微软的插件打开 http://view.officeapps.live.com ...
- java实现在线预览--poi实现word、excel、ppt转html
java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...
- java实现在线预览 - -之poi实现word、excel、ppt转html
简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office.office web 365(http://w ...
随机推荐
- Java设计模式之代理模式(Proxy)
前言: 最近在研究Retrofit开源框架的时候,其主要核心代码是通过注解标示参数,动态代理模式实现具体接口,反射机制进行参数解析,最终实现发送请求.其实之前在学习Xutils源码的时候,Xutils ...
- Android线程管理之ExecutorService线程池
前言: 上篇学习了线程Thread的使用,今天来学习一下线程池ExecutorService. 线程管理相关文章地址: Android线程管理之Thread使用总结 Android线程管理之Execu ...
- Hibernate(6)—— 一对多 和 多对多关联关系映射(xml和注解)总结
俗话说,自己写的代码,6个月后也是别人的代码……复习!复习!复习!涉及的知识点总结如下: One to Many 映射关系 多对一单向外键关联(XML/Annotation) 一对多单向外键关联(XM ...
- 完整记录一则Oracle 11.2.0.4单实例打PSU补丁的过程
本文记录了打PSU的全过程,意在体会数据库打PSU补丁的整个过程. 1.OPatch替换为最新版本2.数据库软件应用19121551补丁程序3.数据库应用补丁4.验证PSU补丁是否应用成功 1.OPa ...
- 使用java传参调用exe并且获取程序进度和返回结果的一种方法
文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 在某个项目中需要考虑使用java后台调用由C#编写的切图程序( ...
- 高仿QQ顶部控件之IOS SegmentView
经常会看到QQ上面有一个 消息和电话 的顶部面板,这个空间是IOS7的分段控制,android中没有这个控件,今天在威哥的微信公众号中成功gank到这个自定义控件的实现,下面跟着尝试一波. 首先是定义 ...
- CentOS7下mysql5.6修改默认编码
参考原文教程:Centos7下修改mysql5.6编码方式 解决网站中文显示问号 解决办法: 修改MySQL数据库字符编码为UTF-8,UTF-8包含全世界所有国家需要用到的字符,是国际编码. 具体操 ...
- Unity 3D json嵌套使用以及多种类型匹配
我们控制端要发送很多命令给终端设备,其中有速度,方向,开关门,开关灯....方法千万种,我只取一瓢.我还小,不知道其他人是怎么写的.我喜欢把有规律的东西放在一起写!为了我的强迫症! using Uni ...
- C#开发微信门户及应用(6)--微信门户菜单的管理操作
前面几篇继续了我自己对于C#开发微信门户及应用的技术探索和相关的经验总结,继续探索微信API并分享相关的技术,一方面是为了和大家对这方面进行互动沟通,另一方面也是专心做好微信应用的底层技术开发,把基础 ...
- SQLServer2005+获取表结构信息
SELECT d.name TableName, a.colorder FieldNo,a.name FieldName, (case when COLUMNPROPERTY( a.id,a.name ...