使用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. 文档在线预览系统

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


  •    

     

    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("


      ");

    49. }

    50. }

    51. %>

    52. Insert title here

  •  

     

    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. 文档在线预览系统

  •  

     

    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

    你可能感兴趣的:(程序员文章)