使用FlexPaper实现PDF文件在线预览

一、文档在线阅读思路 
    1.用OpenOffice把PPT、Word、Excel、Text转换为pdf
   2.用SWFTool将生成的pdf转换成swf,然后利用FlexPlayer实现在线预览播放
二、准备工作
    1.安装OpenOffice,官网下载地址:http://www.openoffice.org/download/index.html,最新版为3.4.1,我使用的版本为3.3.0:http://pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2F%E8%BD%AF%E4%BB%B6%E5%B7%A5%E5%85%B7
   2.启动OpenOffice服务,CMD命令进入OpenOffice安装目录下的program目录,键入如下命令
        soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard

参考资料:http://blog.csdn.net/hbcui1984/article/details/5109169
    3.下载JODConverter:http://sourceforge.net/projects/jodconverter/files/,项目中主要使用lib目录下的jar包。
    4.下载并安装SWFTools:http://www.swftools.org/download.html,下载exe文件安装完成即可
    5.下载FlexPlayer
    http://pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2F%E8%BD%AF%E4%BB%B6%E5%B7%A5%E5%85%B7
    官网下载地址:http://flexpaper.devaldi.com/download/,版本为2.1.5,与1.5.1有较大差别,未使用最新版。

三、软件开发 
    1.新建web项目并引入jar包
        阅读JODConverter/lib目录下的DEPENDENCIES.txt可知需要添加哪些jar包

 

     新建OfficeOnline项目,引入相应jar包(使用的是cos进行文档上传,cos.jar需要另外下载),将FlexPaper_1.5.1_flash.zip解压后的js目录引入到项目中,FlexPaperViewer.swf也引入进来

 

 2.新建DocConverter.java
   注意:根据SWFTools安装路径不同需要修改pdf2swf()方法中pdf2swf.exe的路径,我安装的路径是在D盘
         main()测试中根据自己文档路径进行修改测试。

 

 
  1. package com.util;

  2.  
  3. import java.io.BufferedReader;

  4. import java.io.File;

  5. import java.io.IOException;

  6. import java.io.InputStream;

  7. import java.io.InputStreamReader;

  8.  
  9. import com.artofsolving.jodconverter.DocumentConverter;

  10. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;

  11. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;

  12. import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

  13.  
  14. public class DocConverter {

  15. private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)

  16. private String fileString;

  17. private String outputPath = "";// 输入路径,如果不设置就输出在默认位置

  18. private String fileName;

  19. private File pdfFile;

  20. private File swfFile;

  21. private File docFile;

  22.  
  23. public DocConverter(String fileString) {

  24. ini(fileString);

  25. }

  26.  
  27. /*

  28. * 重新设置 file @param fileString

  29. */

  30. public void setFile(String fileString) {

  31. ini(fileString);

  32. }

  33.  
  34. /*

  35. * 初始化 @param fileString

  36. */

  37. private void ini(String fileString) {

  38. this.fileString = fileString;

  39. fileName = fileString.substring(0, fileString.lastIndexOf("."));

  40. docFile = new File(fileString);

  41. pdfFile = new File(fileName + ".pdf");

  42. swfFile = new File(fileName + ".swf");

  43. }

  44.  
  45. /*

  46. * 转为PDF @param file

  47. */

  48. private void doc2pdf() throws Exception {

  49. if (docFile.exists()) {

  50. if (!pdfFile.exists()) {

  51. OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);

  52. try {

  53. connection.connect();

  54. DocumentConverter converter = new OpenOfficeDocumentConverter(connection);

  55. converter.convert(docFile, pdfFile);

  56. // close the connection

  57. connection.disconnect();

  58. System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");

  59. } catch (java.net.ConnectException e) {

  60. // ToDo Auto-generated catch block

  61. e.printStackTrace();

  62. System.out.println("****swf转换异常,openoffice服务未启动!****");

  63. throw e;

  64. } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {

  65. e.printStackTrace();

  66. System.out.println("****swf转换器异常,读取转换文件失败****");

  67. throw e;

  68. } catch (Exception e) {

  69. e.printStackTrace();

  70. throw e;

  71. }

  72. } else {

  73. System.out.println("****已经转换为pdf,不需要再进行转化****");

  74. }

  75. } else {

  76. System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");

  77. }

  78. }

  79.  
  80. /*

  81. * 转换成swf

  82. */

  83. private void pdf2swf() throws Exception {

  84. Runtime r = Runtime.getRuntime();

  85. if (!swfFile.exists()) {

  86. if (pdfFile.exists()) {

  87. if (environment == 1)// windows环境处理

  88. {

  89. try {

  90. // 这里根据SWFTools安装路径需要进行相应更改

  91. Process p = r.exec("d:/SWFTools/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");

  92. System.out.print(loadStream(p.getInputStream()));

  93. System.err.print(loadStream(p.getErrorStream()));

  94. System.out.print(loadStream(p.getInputStream()));

  95. System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");

  96. if (pdfFile.exists()) {

  97. pdfFile.delete();

  98. }

  99. } catch (Exception e) {

  100. e.printStackTrace();

  101. throw e;

  102. }

  103. } else if (environment == 2)// linux环境处理

  104. {

  105. try {

  106. Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");

  107. System.out.print(loadStream(p.getInputStream()));

  108. System.err.print(loadStream(p.getErrorStream()));

  109. System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");

  110. if (pdfFile.exists()) {

  111. pdfFile.delete();

  112. }

  113. } catch (Exception e) {

  114. e.printStackTrace();

  115. throw e;

  116. }

  117. }

  118. } else {

  119. System.out.println("****pdf不存在,无法转换****");

  120. }

  121. } else {

  122. System.out.println("****swf已存在不需要转换****");

  123. }

  124. }

  125.  
  126. static String loadStream(InputStream in) throws IOException {

  127. int ptr = 0;

  128. //把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改

  129. BufferedReader reader = new BufferedReader(new InputStreamReader(in));

  130. StringBuilder buffer = new StringBuilder();

  131. while ((ptr = reader.read()) != -1) {

  132. buffer.append((char) ptr);

  133. }

  134. return buffer.toString();

  135. }

  136.  
  137. /*

  138. * 转换主方法

  139. */

  140. public boolean conver() {

  141. if (swfFile.exists()) {

  142. System.out.println("****swf转换器开始工作,该文件已经转换为swf****");

  143. return true;

  144. }

  145.  
  146. if (environment == 1) {

  147. System.out.println("****swf转换器开始工作,当前设置运行环境windows****");

  148. } else {

  149. System.out.println("****swf转换器开始工作,当前设置运行环境linux****");

  150. }

  151.  
  152. try {

  153. doc2pdf();

  154. pdf2swf();

  155. } catch (Exception e) {

  156. // TODO: Auto-generated catch block

  157. e.printStackTrace();

  158. return false;

  159. }

  160.  
  161. if (swfFile.exists()) {

  162. return true;

  163. } else {

  164. return false;

  165. }

  166. }

  167.  
  168. /*

  169. * 返回文件路径 @param s

  170. */

  171. public String getswfPath() {

  172. if (swfFile.exists()) {

  173. String tempString = swfFile.getPath();

  174. tempString = tempString.replaceAll("\\\\", "/");

  175. return tempString;

  176. } else {

  177. return "";

  178. }

  179. }

  180.  
  181. /*

  182. * 设置输出路径

  183. */

  184. public void setOutputPath(String outputPath) {

  185. this.outputPath = outputPath;

  186. if (!outputPath.equals("")) {

  187. String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));

  188. if (outputPath.charAt(outputPath.length()) == '/') {

  189. swfFile = new File(outputPath + realName + ".swf");

  190. } else {

  191. swfFile = new File(outputPath + realName + ".swf");

  192. }

  193. }

  194. }

  195.  
  196. public static void main(String s[]) {

  197. DocConverter d = new DocConverter("E:/TDDOWNLOAD/test.doc");

  198. d.conver();

  199. }

  200. }


 

 

运行结果:

 

3.新建 documentUpload.jsp 

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  3. <html>

  4. <head>

  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  6. <title>文档在线预览系统</title>

  7. <style>

  8. body {

  9. margin-top: 100px;

  10. background: #fff;

  11. font-family: Verdana, Tahoma;

  12. }

  13.  
  14. a {

  15. color: #CE4614;

  16. }

  17.  
  18. #msg-box {

  19. color: #CE4614;

  20. font-size: 0.9em;

  21. text-align: center;

  22. }

  23.  
  24. #msg-box .logo {

  25. border-bottom: 5px solid #ECE5D9;

  26. margin-bottom: 20px;

  27. padding-bottom: 10px;

  28. }

  29.  
  30. #msg-box .title {

  31. font-size: 1.4em;

  32. font-weight: bold;

  33. margin: 0 0 30px 0;

  34. }

  35.  
  36. #msg-box .nav {

  37. margin-top: 20px;

  38. }

  39. </style>

  40. </head>

  41. <body>

  42. <div id="msg-box">

  43. <form name="form1" method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp">

  44. <div class="title">

  45. 请上传要处理的文件,过程可能需要几分钟,请稍候片刻。

  46. </div>

  47. <p>

  48. <input name="file1" type="file">

  49. </p>

  50. <p>

  51. <input type="submit" name="Submit" value="上传">

  52. </p>

  53. </form>

  54. </div>

  55. </body>

  56. </html>


   

 

4.新建docUploadConvertAction.jsp

 

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

  2. <%@page import="java.io.*"%>

  3. <%@page import="java.util.Enumeration"%>

  4. <%@page import="com.oreilly.servlet.MultipartRequest"%>

  5. <%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>

  6. <%@page import="com.util.DocConverter"%>

  7. <%

  8. //文件上传采用cos组件上传,可更换为commons-fileupload上传,文件上传后,保存在upload文件夹

  9. //获取文件上传路径

  10. String saveDirectory = application.getRealPath("/") + "upload";

  11. //打印上传路径信息

  12. System.out.println(saveDirectory);

  13. //每个文件最大50m

  14. int maxPostSize = 50 * 1024 * 1024;

  15. //采用cos缺省的命名策略,重名后加1,2,3...如果不加dfp重名将覆盖

  16. DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();

  17. //response的编码为"UTF-8",同时采用缺省的文件名冲突解决策略,实现上传,如果不加dfp重名将覆盖

  18. MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "UTF-8", dfp);

  19. //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8");

  20. //输出反馈信息

  21. Enumeration files = multi.getFileNames();

  22. while (files.hasMoreElements()) {

  23. System.err.println("ccc");

  24. String name = (String) files.nextElement();

  25. File f = multi.getFile(name);

  26. if (f != null) {

  27. String fileName = multi.getFilesystemName(name);

  28. //获取上传文件的扩展名

  29. String extName = fileName.substring(fileName.lastIndexOf(".") + 1);

  30. //文件全路径

  31. String lastFileName = saveDirectory + "\\" + fileName;

  32. //获取需要转换的文件名,将路径名中的'\'替换为'/'

  33. String converfilename = saveDirectory.replaceAll("\\\\", "/") + "/" + fileName;

  34. System.out.println(converfilename);

  35. //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法

  36. DocConverter d = new DocConverter(converfilename);

  37. //调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;

  38. d.conver();

  39. //调用getswfPath()方法,打印转换后的swf文件路径

  40. System.out.println(d.getswfPath());

  41. //生成swf相对路径,以便传递给flexpaper播放器

  42. String swfpath = "upload" + d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));

  43. System.out.println(swfpath);

  44. //将相对路径放入sessio中保存

  45. session.setAttribute("swfpath", swfpath);

  46. out.println("上传的文件:" + lastFileName);

  47. out.println("文件类型" + extName);

  48. out.println("<hr>");

  49. }

  50. }

  51. %>

  52. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  53. <html>

  54. <head>

  55. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  56. <title>Insert title here</title>

  57. <style>

  58. body {

  59. margin-top: 100px;

  60. background: #fff;

  61. font-family: Verdana, Tahoma;

  62. }

  63.  
  64. a {

  65. color: #CE4614;

  66. }

  67.  
  68. #msg-box {

  69. color: #CE4614;

  70. font-size: 0.9em;

  71. text-align: center;

  72. }

  73.  
  74. #msg-box .logo {

  75. border-bottom: 5px solid #ECE5D9;

  76. margin-bottom: 20px;

  77. padding-bottom: 10px;

  78. }

  79.  
  80. #msg-box .title {

  81. font-size: 1.4em;

  82. font-weight: bold;

  83. margin: 0 0 30px 0;

  84. }

  85.  
  86. #msg-box .nav {

  87. margin-top: 20px;

  88. }

  89. </style>

  90. </head>

  91. <body>

  92. <div>

  93. <form name="viewForm" id="form_swf" action="documentView.jsp" method="POST">

  94. <input type='submit' value='预览' class='BUTTON SUBMIT' />

  95. </form>

  96. </div>

  97. </body>

  98. </html>

 

 

5.新建documentView.jsp

 

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

  2. <%

  3. String swfFilePath = session.getAttribute("swfpath").toString();

  4. %>

  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  6. <html>

  7. <head>

  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  9. <script type="text/javascript" src="js/jquery.js"></script>

  10. <script type="text/javascript" src="js/flexpaper_flash.js"></script>

  11. <script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>

  12. <style type="text/css" media="screen">

  13. html,body {

  14. height: 100%;

  15. }

  16.  
  17. body {

  18. margin: 0;

  19. padding: 0;

  20. overflow: auto;

  21. }

  22.  
  23. #flashContent {

  24. display: none;

  25. }

  26. </style>

  27. <title>文档在线预览系统</title>

  28. </head>

  29. <body>

  30. <div style="position: absolute; left: 50px; top: 10px;">

  31. <a id="viewerPlaceHolder" style="width: 820px; height: 650px; display: block"></a>

  32. <script type="text/javascript">

  33. var fp = new FlexPaperViewer(

  34. 'FlexPaperViewer',

  35. 'viewerPlaceHolder', { config : {

  36. SwfFile : escape('<%=swfFilePath%>'),//编码设置

  37. Scale : 0.6,

  38. ZoomTransition : 'easeOut',//变焦过渡

  39. ZoomTime : 0.5,

  40. ZoomInterval : 0.2,//缩放滑块-移动的缩放基础[工具栏]

  41. FitPageOnLoad : true,//自适应页面

  42. FitWidthOnLoad : true,//自适应宽度

  43. FullScreenAsMaxWindow : false,//全屏按钮-新页面全屏[工具栏]

  44. ProgressiveLoading : false,//分割加载

  45. MinZoomSize : 0.2,//最小缩放

  46. MaxZoomSize : 3,//最大缩放

  47. SearchMatchAll : true,

  48. InitViewMode : 'Portrait',//初始显示模式(SinglePage,TwoPage,Portrait)

  49.  
  50. ViewModeToolsVisible : true,//显示模式工具栏是否显示

  51. ZoomToolsVisible : true,//缩放工具栏是否显示

  52. NavToolsVisible : true,//跳页工具栏

  53. CursorToolsVisible : false,

  54. SearchToolsVisible : true,

  55. PrintPaperAsBitmap:false,

  56. localeChain: 'en_US'

  57. }});

  58. </script>

  59. </div>

  60. </body>

  61. </html>

 

 

FlexPaperViewer参数设置对应说明文档:http://flexpaper.devaldi.com/docs_parameters.jsp

6.部署后访问:http://localhost:8080/OfficeOnline/documentUpload.jsp

 

上传成功后预览:

7.若出现swf无法预览,请访问http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065将生成swf的文件夹设置为信任文件。
8.参考资料:http://blog.csdn.net/hil2000/article/details/8459940
               http://www.cnblogs.com/star-studio/archive/2011/12/09/2281807.html
      文件中文名乱码解决:http://blog.csdn.net/kunoy/article/details/7903258

 

四、其他优化
解决flexpaper搜索文字时不能高亮的问题:http://my.oschina.net/dianfusoft/blog/125450 
flexpaper去简介去水印等:http://blog.csdn.net/zengraoli/article/details/7827840

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值