java實現在線文檔瀏覽
目前發現兩種方法:
1、使用openoffice將office轉換為pdf文檔,使用swfTools將pdf文檔轉換為swf文件,通過flexpaper插件展示;
2、webOffice插件,直接展示。
在這裏先說下第一種:
第一 office--->pdf
下載 openoffice 地址: https://share.weiyun.com/e78f8f6518e3a5534044b210102daebd 密碼: sM0YCz
然後在cmd環境下進入安裝目錄的program目錄,輸入打開openoffice的命令:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
輸入完成之後在任務管理器可以看見soffice.bin的進程在任務管理器,這一服務就啟動成功。當然在代碼中轉換office2pdf我們還需要一些架包。
下載jodconverter-2.2.2架包,然後復制到lib目錄下,引入架包就可以了。這個架包有如下包:
如果報錯 The type com.sun.star.lang.XEventListener cannot be resolved. It is indirectly referenced from required異常:
解決辦法:到官方網站下載jodconverter-2.2.2.zip,然後把lib文件夾下得所有jar包都拷進去,就可以了。
package com.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.ConnectException; 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; import com.winchannel.pluginclient.util.PropertiersUtil; /** * @author xx * @time xx */ public class ConvertPdf { /** * @param filePath 上傳文件所在文件夾的絕對路徑 * @param fileName 文件名稱 * @return 生成pdf路徑\文件名 */ public String beginConvert(String filePath, String fileName,String fastName) { final String DOC = ".doc"; final String DOCX = ".docx"; final String XLS = ".xls"; final String XLSX = ".xlsx"; final String PDF = ".pdf"; final String PPT=".ppt"; final String PPTX=".pptx"; final String TXT=".txt"; String fileExt = ""; if (null != fileName && fileName.indexOf(".") > 0) { int index = fileName.lastIndexOf("."); fileExt = fileName.substring(index).toLowerCase(); } String inputFile = filePath + File.separator + fileName; String outputFile = ""; int i = 0; //如果是office文檔,先轉為pdf文件 if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS) || fileExt.equals(XLSX)|| fileExt.equals(PPT) || fileExt.equals(PPTX)){ outputFile = filePath + File.separator + fastName + PDF; System.out.println("====源文件!===="+inputFile); System.out.println("====轉換後文件!===="+outputFile); i= office2PDF(inputFile, outputFile); } if(fileExt.equals(TXT)||fileExt.equals(".java")){ File input=new File(inputFile); ChangeFileCode changeFileCode = new ChangeFileCode(); String fileCode = changeFileCode.getFileEnCode(inputFile); if(fileCode!=null && !"".equals(fileCode)) { changeFileCode.setFileIn(input.getPath(), fileCode);//如果文件編碼為ANSI用GBK來讀,如果是UTF-8用UTF-8來讀 changeFileCode.setFileOut(input.getPath(), "UTF-8");//UTF-8則文件編碼為UTF-8, 如果為GBK,編碼為ANSI changeFileCode.start(); } inputFile=filePath + File.separator + fastName + ".odt"; input.renameTo(new File(inputFile)); outputFile=filePath + File.separator + fastName + PDF; System.out.println("====源文件!===="+inputFile); System.out.println("====轉換後文件!===="+outputFile); i=office2PDF(inputFile, outputFile); } if(fileExt.equals(PDF)){//如果是pdf不需要轉換 復制改名 outputFile = filePath + File.separator + fastName + PDF; i=copy(new File(inputFile),new File(outputFile)); } if(i==0){ return outputFile; }else{ return "0"; } } /** * 復制文件 */ private int copy(File fromFile, File toFile){ try { if (!fromFile.exists()){ System.out.println("====來源文件為空!===="); } if (!toFile.exists()){ System.out.println("====創建新文件!===="); toFile.createNewFile(); } FileInputStream fis = new FileInputStream(fromFile); System.out.println("fromFile :" + fromFile.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(toFile); System.out.println("toFile :" + toFile.getAbsolutePath()); int len = 0; byte[] buf = new byte[1024]; while((len = fis.read(buf)) != -1){ fos.write(buf,0,len); } fis.close(); fos.close(); } catch (Exception e) { System.out.println("====文件復制失敗===="); return -1; } return 0; } /** * office文檔轉pdf文件 * @param sourceFile office文檔絕對路徑 * @param destFile pdf文件絕對路徑 * @return */ public int office2PDF(String sourceFile, String destFile) { String OpenOffice_HOME = PropertiersUtil.getValue("base", "oo_home"); String host_Str =PropertiersUtil.getValue("base", "oo_host"); String port_Str = PropertiersUtil.getValue("base", "oo_port"); OpenOfficeConnection connection=null; Process pro =null; try { File inputFile = new File(sourceFile); if (!inputFile.exists()) { System.out.println("====找不到源文件===="+sourceFile); return -1; // 找不到源文件 } // 如果目標路徑不存在, 則新建該路徑 File outputFile = new File(destFile); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } //windows // 啟動OpenOffice的服務 String command = OpenOffice_HOME + "\\program\\soffice.exe -headless -accept=\"socket,host=" + host_Str + ",port=" + port_Str + ";urp;\""; //linux /* String command = openOffice_HOME + "/program/soffice --headless --accept=\"socket,host=" + host_Str + ",port=" + port_Str + ";urp;\" --nofirststartwizard &"; */ System.out.println("====command===="+command); pro = Runtime.getRuntime().exec(command); // 連接openoffice服務 connection = new SocketOpenOfficeConnection(host_Str, Integer.parseInt(port_Str)); connection.connect(); // 轉換 DocumentConverter converter = new OpenOfficeDocumentConverter(connection); try{ converter.convert(inputFile, outputFile); }catch (Exception e) { if(connection!=null){ connection.disconnect(); } if(pro!=null){ pro.destroy(); } System.out.println("====轉換異常!===="); } // 關閉連接和服務 connection.disconnect(); pro.destroy(); return 0; } catch (FileNotFoundException e) { System.out.println("====文件未找到===="); return -1; } catch (ConnectException e) { System.out.println("====OpenOffice服務監聽異常!===="); } catch (IOException e) { System.out.println("====IO異常!===="); } return 1; } public static void main(String[] args) throws IOException { ConvertPdf c=new ConvertPdf(); String filePath="E:\\"; String fileName="ddd.docx"; System.out.println(">>>"+c.beginConvert(filePath, fileName,"1")); } }
第二 pdf--->swf
下載 swftools 地址: https://share.weiyun.com/653b5ad04d9132347c3a72af9e5da6d1 密碼: 77NIZe
package com.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 將pdf文件轉成swf格式 */ public class ConvertSwf { private final Logger log = LoggerFactory.getLogger(ConvertSwf.class); /** * 將pdf文件轉換成swf文件 * @param sourceFile pdf文件絕對路徑 * @param outFile swf文件絕對路徑 * @param toolFile 轉換工具絕對路徑 */ public String convertPdf2Swf(String sourceFile, String outFile) { //linux // String TOOL = "pdf2swf"; //windows String TOOL = "D:\\Program Files (x86)\\SWFTools\\pdf2swf"; String command = TOOL +" "+ sourceFile + " -o " + outFile + " -s flashversion=9 "+ " -p 0-100"+" -s languagedir=/opt/xpdf-chinese-simplified/ "; try { Process process = Runtime.getRuntime().exec(command); log.info("===="+loadStream(process.getInputStream())+"===="); log.info("===="+loadStream(process.getErrorStream())+"===="); log.info("====轉換成功swf===="); } catch (Exception e) { e.printStackTrace(); } return ""; } 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(); } public static void main(String[] args) { ConvertSwf c = new ConvertSwf(); String filePath="E:\\"; String fileName="1.pdf"; c.convertPdf2Swf(filePath+fileName,filePath+"12.swf"); } }
第三 展示swf
下載 flexpaper 地址:https://share.weiyun.com/298067f3edba681973d89a9487ce78a0 密碼:NXwFPi
使用這個插件需要有三個js文件。分別是:jquery.js、flexpaper_flash.js、flexpaper_flash_debug.js。插件的名字是FlexPaperViewer.swf。
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> <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(‘http://localhost:8080/TestBaiDu/12.swf‘), 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>
註意問題:
1、在線預覽只能實現10頁的情況,需要把RenderingOrder : ‘flash‘,設置為flash才可以實現超過10頁的在線預覽。
2、發現錯誤一般是openoffice服務沒有開啟。
3、Linux環境下會存在中文亂碼的問題,是linux下不像windows支持那麽多字體,需要安裝多的字體,並且把字體所在位置鏈接到flexpaper所在位置。在使用pdf2swf加上參數-s languagedir=/usr/local/xpdf-chinese-simplified/
擴展:
<script type="text/javascript"> //判斷是否是觸屏(移動設備) $.get((!window.isTouchScreen) ? ‘/UI_flexpaper_desktop_flat.html‘ : ‘/UI_flexpaper_mobile_flat.html‘, function(toolbarData) { $(‘#documentViewer‘).FlexPaperViewer({ config : { //swf文件的分頁模式 //SwfFile : "/flex/view/{Paper_[*,0].swf,28}", //單swf文件模式 SwfFile : "/flex/view?name=Paper.swf", //JSONFile : ‘/flex/view?name=Paper.js‘, //pdf文件模式 //PDFFile : ‘/flex/view?name=Paper.pdf‘, //初始縮放比例 Scale : 0.6, //變焦模式一般都是‘easeOut‘ ZoomTransition : ‘easeOut‘, //變焦速度 ZoomTime : 0.5, //變焦間隔 ZoomInterval : 0.2, ///適應加載 FitPageOnLoad : true, //適應寬度加載 FitWidthOnLoad : false, FullScreenAsMaxWindow : false, ProgressiveLoading : true, //最小比例 MinZoomSize : 0.2, //做大比例 MaxZoomSize : 5, SearchMatchAll : true, //切換顯示模式:Two Page雙頁/Portrait單頁 InitViewMode : ‘Portrait‘, //加載方式 RenderingOrder : ‘flash‘, //顯示模式(單/雙頁)按鈕 ViewModeToolsVisible : true, //縮放條 ZoomToolsVisible : true, //頁面跳轉框 NavToolsVisible : true, //焦點按鈕 CursorToolsVisible : true, //搜索欄 SearchToolsVisible : true, //通過請求的方式獲取的導航欄(響應式) Toolbar : toolbarData, //底部工具欄(用於註釋的添加刪除等) BottomToolbar : ‘/UI_flexpaper_annotations.html‘, WMode : ‘window‘, //按鈕提示語言 localeChain : "zh_CN", } }); }); </script>
頁數跳轉:$FlexPaper("documentViewer").gotoPage(5); 適應控件寬度:$FlexPaper("documentViewer").fitWidth(); 適應控件高度:$FlexPaper("documentViewer").fitHeight(); 獲取當前頁數:$FlexPaper("documentViewer").getCurrPage(); 打印:$FlexPaper("documentViewer").printPaper(); 下一頁:$FlexPaper("documentViewer").nextPage(); 上一頁:$FlexPaper("documentViewer").prevPage(); 搜索:$FlexPaper("documentViewer").searchText(""); 切換顯示模式:Two Page雙頁/Portrait單頁 $FlexPaper("documentViewer").switchMode("Portrait");
SwfFile (字符串) |
flash文件FlexPaper應該開放 |
JSONFile (字符串) |
json文檔FlexPaper應該開放。 馬克的頁碼{頁面}如果你加載FlexPaper分裂模式(例如Paper.pdf_ {頁面} . js)。 這只適用於FlexPaper AdaptiveUI啟用。 |
IMGFiles (字符串) |
頁面的圖片FlexPaper應該開放。 與{頁面}標記頁碼(如Paper.pdf_ {頁面} . png })。 這只適用於FlexPaper AdaptiveUI啟用。 |
規模 (數量) |
應該使用的初始縮放因子。 應該是一個數量以上0(1 = 100%) |
ZoomTransition (字符串) |
時應該使用的縮放轉換放大FlexPaper。 它使用相同的過渡模式作為中間人。 默認值是easeOut。 一些例子:easenone easeout,線性,easeoutquad |
ZoomTime (數量) |
變焦的時候應該達到新的縮放因子。 應該是0或更大。 |
ZoomInterval (數量) |
縮放滑塊應該使用的間隔。 基本上每個之間的“一步”應該多大放大因子。 默認值是0.1。 應該是一個正數。 |
FitPageOnLoad (布爾) |
適合在初始加載的頁面。 同樣的效果使用適合頁面按鈕的工具欄。 |
FitWidthOnLoad (布爾) |
適合在初始加載寬度。 同樣的效果使用fit-width按鈕的工具欄。 |
localeChain (字符串) |
設置要使用的語言環境(語言)。 目前支持以下語言:
|
FullScreenAsMaxWindow (布爾) |
使用此設置為true,點擊全屏和FlexPaper將打開一個新的瀏覽器窗口最大化而不是使用真正的全屏。 這是首選設置當使用FlexPaper一樣閃光獨立的安全限制flash player禁用(出於安全原因)的大部分輸入控件在真正的全屏。 |
ProgressiveLoading (布爾) |
將逐步加載和顯示文檔設置為true時相對於之前下載完整的文檔顯示頁面。 文檔至少需要轉換為Flash版本9為此(- t 9國旗使用PDF2SWF)。 請註意,這個參數沒有影響FlexPaper鋅。 請使用分割頁面加載FlexPaper鋅的大型文檔。 |
MaxZoomSize (數量) |
設置最大允許縮放級別 |
MinZoomSize (數量) |
集的最小允許縮放級別 |
SearchMatchAll (布爾) |
當該值設置成真時,觀眾強調所有匹配文檔中執行搜索時。 |
InitViewMode (字符串) |
設置啟動視圖模式。 例如“肖像”或“TwoPage”。 |
PrintPaperAsBitmap (布爾) |
當該值設置成真時,觀眾將打印文檔作為一個位圖與矢量化 |
StartAtPage (數量) |
讓觀眾從一個特定的頁面 |
ViewModeToolsVisible (布爾) |
顯示或隱藏工具欄的視圖模式 |
ZoomToolsVisible (布爾) |
顯示或隱藏縮放工具欄的工具 |
NavToolsVisible (布爾) |
顯示或隱藏工具欄導航工具 |
CursorToolsVisible (布爾) |
光標顯示或隱藏工具欄的工具 |
SearchToolsVisible (布爾) |
顯示或隱藏工具欄的搜索工具 |
jsDirectory (字符串) |
集提供的javascript目錄的位置。 這只適用於FlexPaper AdaptiveUI啟用。 |
cssDirectory (字符串) |
設置css提供目錄的位置。 這只適用於FlexPaper AdaptiveUI啟用。 |
localeDirectory (字符串) |
設置語言環境提供目錄的位置。 這只適用於FlexPaper AdaptiveUI啟用。 |
感謝 :
https://www.cnblogs.com/warrior4236/p/5866310.html
https://www.cnblogs.com/liaoweipeng/p/4767660.html
http://blog.csdn.net/u010392801/article/details/49464657
http://blog.csdn.net/long5693525/article/details/50515610
java實現在線文檔瀏覽