位置:首页 » 文章/教程分享 » Java实现仿百度文库文档在线阅读

为了实现这个功能,我们需要用到如下软件,Java+FlexPaper+SwfTool+OpenOffice这四大件.

1、思路

我们将doc、ppt等文档格式通过openoffice转换成pdf的格式,然后用SWFTool工具将pdf切分成小块的swf文件或者大型的swf 文件或者图片格式也行.一般都采用小块swf或者小块图片格式,这样用户就能按需加载.比如我们的pdf文件有80M,用户打开预览页面加载的就是当前查 看页的前一页、当前页、后一页,当然这数字是可以通过调整配置去设置.所以用户可以很快的去打开页面进行预览而不是加载一个整体的文件.

2、环境的安装

1.安装OpenOffice,官网下载地址:下载地址,我是使用的最新版.具体安装方法自行百度.

2.启动OpenOffice服务,CMD命令进入OpenOffice安装目录下的program目录,键入如下命令

[plain] view plain copy
  1. /opt/openoffice4/program/soffice “-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager” -nologo -headless -nofirststartwizard &  

这个是启动office后台进行转换的一个服务,无图形界面.

3.下载JODConverter:下载地址,项目中主要使用lib目录下的jar包。

4.下载并安装SWFTools:下载地址,下载exe文件安装完成即可

5.下载FlexPlayer

下载地址

未使用最新版,使用1.5.1

6.下载相关的xpdf及字符集(处理中文文档字体的错误)

xpdf-3.02pl5-win32.zip
下载地址为
ftp://ftp.foolabs.com/pub/xpdf/xpdf-3.02pl5-win32.zip
xpdf-chinese-simplified.tar.gz
下载地址为
ftp://ftp.foolabs.com/pub/xpdf/xpdf-chinese-simplified.tar.gz
也可以去http://www.foolabs.com/xpdf/download.html查找你自己需要的字符集

您也可以去官网下载最新版本

1.解压xpdf-3.02pl5-win32.zip,解压后修改名称为xpdf,并将其考到c盘根目录下【路径可以随意指定,但是执行pdf2swf指令时要指定到当前目录】。
2.解压xpdf-chinese-simplified,将xpdf-chinese-simplified放置xpf目录下
3.修改xpdf-chinese-simplified目录下的add-to-xpdfrc文件

Add-to-xpdfrc代码

[plain] view plain copy
  1. #----- begin Chinese Simplified support package (2004-jul-27)    
  2. cidToUnicode        Adobe-GB1         /usr/local/share/xpdf/chinese-simplified/Adobe-GB1.cidToUnicode     
  3. unicodeMap            ISO-2022-CN    /usr/local/share/xpdf/chinese-simplified/ISO-2022-CN.unicodeMap     
  4. unicodeMap    EUC-CN        /usr/local/share/xpdf/chinese-simplified/EUC-CN.unicodeMap     
  5. unicodeMap    GBK     /usr/local/share/xpdf/chinese-simplified/GBK.unicodeMap     
  6. cMapDir     Adobe-GB1    /usr/local/share/xpdf/chinese-simplified/CMap     
  7. toUnicodeDir  /usr/local/share/xpdf/chinese-simplified/CMap     
  8. fontDir C:\WINDOWS\Fonts     
  9. #添加字体格式  
  10. displayCIDFontTT Adobe-GB1 /usr/local/share/xpdf/chinese-simplified/Fonts/simhei.ttf     
  11. #displayCIDFontTT   Adobe-GB1   /usr/..../gkai00mp.ttf    
  12. #----- end Chinese Simplified support package  

如果您未注释掉下面提供的类中的languagedir段,则会在转换的时候显示如下信息
表示成功添加了中文字体
输出信息

3.开发过程

1.添加JODConverter的jar包,同时也需要将所依赖的包添加进工程.

2.咱们需要一个转换的类

[java] view plain copy
  1. public class Converter2Swf {  
  2.     private File pdfFile;  
  3.     private File swfFile;  
  4.     private File docFile;  
  5.     private File originalFile;  
  6.     private static final String[] extArray = {"doc","docx","ppt","pptx","xls","xlsx","txt","rtf"};  
  7.   
  8.     public Converter2Swf(String fileString) {  
  9.         init(fileString);  
  10.     }  
  11.   
  12.     /* 
  13.      * 重新设置 file @param fileString 
  14.      */  
  15.     public void setFile(String fileString) {  
  16.         init(fileString);  
  17.     }  
  18.   
  19.     /* 
  20.      * 初始化 @param fileString 
  21.      */  
  22.     private void init(String fileString) {  
  23.         originalFile = new File(fileString);  
  24.         String fileName = FilenameUtils.getBaseName(fileString);  
  25.         String fileExt = FilenameUtils.getExtension(fileString);  
  26.   
  27.         if (Converter2Swf.can2Pdf(fileExt)) {  
  28.             docFile = new File(fileString);  
  29.             pdfFile = new File(fileName + ".pdf");  
  30.             swfFile = new File(fileName+new Date().getTime() + ".swf");  
  31.         } else if ("pdf".equals(fileExt)) {  
  32.             pdfFile = new File(fileString);  
  33.             swfFile = new File(fileName+new Date().getTime() + ".swf");  
  34.         }  
  35.     }  
  36.   
  37.     public static boolean can2Pdf(String ext) {  
  38.         for (String temp : extArray) {  
  39.             if(temp.equals(ext))  
  40.                 return true;  
  41.         }  
  42.         return false;  
  43.     }  
  44.   
  45.     public static boolean can2Swf(String ext) {  
  46.         if("pdf".equals(ext))  
  47.             return true;  
  48.         for (String temp : extArray) {  
  49.             if(temp.equals(ext))  
  50.                 return true;  
  51.         }  
  52.         return false;  
  53.     }  
  54.   
  55.     /* 
  56.      * 转为PDF @param file 
  57.      */  
  58.     private void doc2pdf() throws Exception {  
  59.         OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);  
  60.         connection.connect();  
  61.         DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
  62.         converter.convert(docFile, pdfFile);  
  63.         connection.disconnect();  
  64.     }  
  65.   
  66.     /* 
  67.      * 转换成swf 
  68.      */  
  69.     private int pdf2swf() throws Exception {  
  70.         int countFile = -1;  
  71.         int errorFlag = 0;  
  72.         String path = File.separator+FilenameUtils.getPath(swfFile.getPath());  
  73.         String filename = FilenameUtils.getBaseName(swfFile.getPath()) + "%." + FilenameUtils.getExtension(swfFile.getPath());  
  74.         String[] command = {"pdf2swf", pdfFile.getPath(), "-o", path + filename, "-T 9","-s","languagedir=/usr/local/share/xpdf/chinese-simplified"};  
  75.         ProcessBuilder proc = new ProcessBuilder(command);  
  76.         proc.redirectErrorStream(true);  
  77.         Process p = proc.start();  
  78.         String outlog = loadStream(p.getInputStream());  
  79.         if(StringUtils.contains(outlog,"FATAL"))  
  80.             errorFlag = 2;  
  81.         else if(StringUtils.contains(outlog,"ERROR"))  
  82.             errorFlag = 1;  
  83.         if(errorFlag == 1)  
  84.             System.err.println(outlog);  
  85.         else if (errorFlag == 2) {  
  86.             System.err.println(outlog);  
  87.             countFile = 0;  
  88.         } else {  
  89.             System.out.println(outlog);  
  90.             countFile = StringUtils.countMatches(outlog, FilenameUtils.getBaseName(pdfFile.getName()));  
  91.         }  
  92.         if (pdfFile.exists() && !pdfFile.getPath().equals(originalFile.getPath())) {  
  93.             pdfFile.delete();  
  94.         }  
  95.         return countFile;  
  96.     }  
  97.   
  98.     static String loadStream(InputStream in) throws IOException {  
  99.         int ptr = 0;  
  100.         BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
  101.         StringBuilder buffer = new StringBuilder();  
  102.         while ((ptr = reader.read()) != -1) {  
  103.             buffer.append((char) ptr);  
  104.         }  
  105.         return buffer.toString();  
  106.     }  
  107.   
  108.     /* 
  109.      * 转换主方法 
  110.      */  
  111.     public int conver() throws Exception {  
  112.         int countFile = -1;  
  113.         if (swfFile != null) {  
  114.             if (docFile != null && can2Pdf(FilenameUtils.getExtension(docFile.getPath())))  
  115.                 doc2pdf();  
  116.             if(pdfFile != null && can2Swf(FilenameUtils.getExtension(pdfFile.getPath())))  
  117.                countFile = pdf2swf();  
  118.         }  
  119.         return countFile;  
  120.     }  
  121.   
  122.     /* 
  123.      * 返回文件路径 @param s 
  124.      */  
  125.     public String getswfPath() {  
  126.         if (swfFile.exists()) {  
  127.             String tempString = swfFile.getPath();  
  128.             tempString = tempString.replaceAll("\\\\", "/");  
  129.             return tempString;  
  130.         } else {  
  131.             return "";  
  132.         }  
  133.     }  
  134.   
  135.     /* 
  136.      * 设置输出路径 
  137.      */  
  138.     public void setOutputPath(String outputPath) {  
  139.         File output = new File(outputPath);  
  140.         if(!output.exists())  
  141.             output.mkdirs();  
  142.         if (!outputPath.equals("")) {  
  143.             if (outputPath.charAt(outputPath.length() - 1) == '/') {  
  144.                 swfFile = new File(outputPath + FilenameUtils.getBaseName(swfFile.getPath()) + ".swf");  
  145.             } else {  
  146.                 swfFile = new File(outputPath + File.separator + FilenameUtils.getBaseName(swfFile.getPath()) + ".swf");  
  147.             }  
  148.         }  
  149.     }  
  150.   
  151.     public File getSwfFile() {  
  152.         return swfFile;  
  153.     }  
  154.   
  155.     public static void main(String s[]) {  
  156.         File file = new File("/home/michael/06142722_m3Sr.pdf");  
  157.         Converter2Swf d = new Converter2Swf(file.getPath());  
  158.         d.setOutputPath(RequestContext.root());  
  159.         int swfcount = 0;  
  160.         try {  
  161.             swfcount = d.conver();  
  162.         } catch (Exception e) {  
  163.             e.printStackTrace();  
  164.         }  
  165.     }  
  166. }  

该 类只是单独对文件进行转换成pdf swf,可以在用户上传的时候进行对文件的处理,也可以在用户上传完之后通过一定定时任务去处理,这样用户就不需要为了等待服务器的转换而浪费时间.该代 码是建立在linux基础上进行,如果您是要在window上进行处理则要稍稍修改代码
该代码这里进行切分是按页切分成小型的swf文件
如果不需要则command中的-T 9则行
该代码引入了中文字体库,否则在进行转换成swf的时候可能会出现一些缺少中文字体等错误,如果您不需要处理这种中文的错误,您也可以在command中去掉
languagedir=/usr/local/share/xpdf/chinese-simplified
通过执行这个类的main方法可以测试是否成功生成swf文件
3.如果您已经成功产生了如上的swf文件,则可以进行最后一步,在页面上调用FlexPaperViewer的swf文件显示就可以
[javascript] view plain copy
  1. <script type="text/javascript">  
  2.             var fp = new FlexPaperViewer(  
  3.                     '/js/flexpaper/FlexPaperViewer',  
  4.                     'viewerPlaceHolder', { config : {  
  5.                         SwfFile : '{$doc.swfurl(),$doc.swfcount()}',  
  6.                         Scale : 0.6,  
  7.                         ZoomTransition : 'easeOut',  
  8.                         ZoomTime : 0.5,  
  9.                         ZoomInterval : 0.2,  
  10.                         FitPageOnLoad : false,  
  11.                         FitWidthOnLoad : true,  
  12.                         FullScreenAsMaxWindow : false,  
  13.                         ProgressiveLoading : true,  
  14.                         MinZoomSize : 0.2,  
  15.                         MaxZoomSize : 5,  
  16.                         SearchMatchAll : false,  
  17.                         InitViewMode : 'Portrait',  
  18.   
  19.                         ViewModeToolsVisible : true,  
  20.                         ZoomToolsVisible : true,  
  21.                         NavToolsVisible : true,  
  22.                         CursorToolsVisible : true,  
  23.                         SearchToolsVisible : true,  
  24.   
  25.                         localeChain: 'zh_CN'  
  26.                     }});  
  27.         </script>  

这部分代码不同版本的flexpaper会稍有不同,具体细节参考官网的文档说明,如果您用的最新版的flexpaper,可能这样的配置或者调用方式有些不同.

$doc.swfurl()是代码的swf的url地址,而后面的$doc.swfcount()代表该文件转换成功生成的swf小文件个数.
需要注意的是我们的这个swfurl()方法返回的链接是必须不能带有空格之类的,所以我们在转换生成swf文件的时候最好采用时间来作为文件命名的一个 参照,这样就能避免出现空格的问题,同时对于大规模的部署这个应用,我们还得处理在Linux上,一个目录下文件不能超过10000个文件,所以我们可以 分成大大小小的目录去处理.

最后的效果可以参考