【OfficeOnline】文档在线预览之解决方案(一)

引言

在项目中,实现Office文档在线预览并不复杂。我们可以选择使用第三方Office文档预览服务,这种方式既方便又高效,能满足我们的各种需求。但是,如果你希望自己能够深入地了解和掌控这个过程,首先需要了解Office文档在线预览的实现原理。

一、文档预览服务

在线Office文档预览服务:现在有许多优质的在线Office文档服务可供选择,例如USDOC等,它们提供了便捷的文档在线预览和编辑功能。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
版本修改记录: V2.2.0.2修改: 修改了HttpPost相对路径的一些问题。 V2.2.0.0增加: [id(0x00010041), helpstring("Get Rev Index")] HRESULT GetRevCount( [out,retval] long * pbool); [id(0x00010042), helpstring("Get Rev Index Info")] HRESULT GetRevInfo([in] long lIndex, [in] long lType, [out,retval] BSTR* pbool); [id(0x00010043), helpstring("Set Doc Prop")] HRESULT SetValue([in] BSTR strValue, [in] BSTR strName, [out,retval] long* pbool); [id(0x00010044), helpstring("Set Doc Variable")] HRESULT SetDocVariable([in] BSTR strVarName, [in] BSTR strValue,[in] long lOpt, [out,retval] long* pbool); [id(0x00010045), helpstring("Save page To Doc")] HRESULT SetPageAs([in] BSTR strLocalFile, [in] long lPageNum, [in] long lType,[out,retval] long* pbool); ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- LoadDso.js var s = "" s += "" s += "" document.write(s) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 接口文档: /* 1.新建 */ //新建Word document.all.FramerControl1.CreateNew("Word.Document"); //新建Excel document.all.FramerControl1.CreateNew("Excel.Sheet"); /* 2.打开文件 */ //打开制定的本地文件 document.all.FramerControl1.Open("C:\\TestBook.xls"); //制定用Word来打开c:\plain.txt文件 document.all.FramerControl1.Open("C:\\Plain.txt",false, "Word.Document"); //打开服务器文件 document.all.FramerControl1.Open "https://secureserver/test/mytest.asp?id=123",true, "Excel.Sheet", "MyUserAccount", "MyPassword"); //打开服务器文件 document.all.FramerControl1.Open("http://localhost/1.doc", true); /* 3.保存文件 */ //到本地 document.all.FramerControl1.Save("c:\\1.doc",true); //服务器 /*增加Http协议Post上传接口,可以Post一个动态页面(jsp,asp,php...),由动态页面负责解析数据 bool HttpInit(); bool HttpAddPostString(BSTR strName, BSTR strValue); bool HttpAddPostCurrFile(BSTR strFileID, BSTR strFileName); BSTR HttpPost(BSTR bstr); */ //初始化Http引擎 document.all.FramerControl1.HttpInit(); //增加Post变量 document.all.FramerControl1.HttpAddPostString("RecordID","20060102200"); document.all.FramerControl1.HttpAddPostString("UserID","李局长"); //上传打开的文件 document.all.FramerControl1.HttpAddPostCurrFile("FileData", "文档名.doc"); //执行上传动作 document.all.FramerControl1.HttpPost("http://xxxx.com/uploadfile.asp"); /* 4.修订留痕 */ //进入留痕状态 document.all.FramerControl1.SetTrackRevisions(1); //进入非留痕状态 document.all.FramerControl1.SetTrackRevisions(0); //接受当前修订 document.all.FramerControl1.SetTrackRevisions(4); /* 5.设置当前用户 */ document.all.FramerControl1.SetCurrUserName("张三"); /* 6.设置当前时间(笔迹留痕会显示("Like 2006:02:07 11:11:11") */ document.all.FramerControl1.SetCurrTime("2006:02:07 11:11:11"); /* 7.设置和创建书签,此功能比较强大,设置书签数据、添加书签和添加红头文件就靠他了 SetFieldValue(BSTR strFieldName, BSTR strValue, BSTR strCmdOrSheetName) strFieldName:书签名 strValue:要设置的值 strCmdOrSheetName: 命令 ::ADDMARK:: 添加BookMark ::DELMARK:: 删除这个BookMark ::GETMARK:: 定位到这个BookMark ::FILE:: 插入的是文件 ::JPG:: 插入的是图片 一般来说:WORD中书签是做好的,可以通过此接口把外界数据设置进书签中去。 */ //在当前WORD位置插入标签,标签名为"book1",数值为"test" document.all.FramerControl1.SetFieldValue("book1","test","::ADDMARK::"); //设置书签"Time",数值为"2006-03-16 22:22:22" document.all.FramerControl1.SetFieldValue("Time","2006-03-16 22:22:22",""); //在书签位置"hongtou",插入红头文件"http://222.222.222.222/hongtou1.doc" 这样,红头就自动插进去了 document.all.FramerControl1.SetFieldValue("hongtou","http://222.222.222.222/hongtou1.doc","::FILE::"); /* 8.设置菜单显示情况 BOOL SetMenuDisplay(long lMenuFlag) lMenuFlag为以下数值的组合 #define MNU_NEW 0x01 #define MNU_OPEN 0x02 #define MNU_CLOSE 0x04 #define MNU_SAVE 0x08 #define MNU_SAVEAS 0x16 #define MNU_PGSETUP 0x64 #define MNU_PRINT 0x256 #define MNU_PROPS 0x32 #define MNU_PRINTPV 0x126 */ //只有“新建”菜单可用 document.all.FramerControl1..SetMenuDisplay(1); //只有“打开”菜单可用 document.all.FramerControl1.SetMenuDisplay(2); //只有“打开”和“新建”菜单可用 document.all.FramerControl1.SetMenuDisplay(3); /* 9.保护文档和解保护文档 lProOrUn:1:保护文档;0:解除保护 lProType: wdNoProtection = -1, wdAllowOnlyRevisions = 0, wdAllowOnlyComments = 1, wdAllowOnlyFormFields = 2 strProPWD:密码 */ //完全保护文档,密码为"pwd" document.all.FramerControl1.ProtectDoc(1,1,"pwd"); //解除文档保护 document.all.FramerControl1.ProtectDoc(0,1,"pwd"); /* 10.显示或隐藏修订内容 ShowRevisions(long nNewValue) nNewValue = 0 则隐藏修订 = 1 则显示修订 */ //显示修订留痕 document.all.FramerControl1.ShowRevisions(1); //隐藏修订留痕 document.all.FramerControl1.ShowRevisions(0); /* 11.插入合并文件, strFieldPath 文件路径,可以是http,ftp的路径 pPos = 0 //当前鼠标位置 1;文件开头 2;文件末尾 pPos的第4位为1的时候,代表插入的是图片 InSertFile(BSTR strFieldPath, long lPos) */ //文件头部插入文件 document.all.FramerControl1.InSertFile("http://XX.com/XX.doc",1); //文件尾部插入文件 document.all.FramerControl1.InSertFile("http://XX.com/XX.doc",2); //当前光标位置插入文件 document.all.FramerControl1.InSertFile("http://XX.com/XX.doc",0); //文件头部插入图片 document.all.FramerControl1.InSertFile("http://XX.com/XX.jpg",9); //文件尾部插入图片 document.all.FramerControl1.InSertFile("http://XX.com/XX.jpg",10); //当前光标位置插入图片 document.all.FramerControl1.InSertFile("http://XX.com/XX.jpg",8); /* 0x31. 文档另存为 HRESULT SaveAs([in] VARIANT strFileName, [in] VARIANT dwFileFormat, [out,retval] long* pbool); 参数: strFileName:文件本地路径,如c:\\11.doc dwFileFormat: 文件格式 dwFileFormat的数值为: Excel: Type enum XlFileFormat { xlAddIn = 18, xlCSV = 6, xlCSVMac = 22, xlCSVMSDOS = 24, xlCSVWindows = 23, xlDBF2 = 7, xlDBF3 = 8, xlDBF4 = 11, xlDIF = 9, xlExcel2 = 16, xlExcel2FarEast = 27, xlExcel3 = 29, xlExcel4 = 33, xlExcel5 = 39, xlExcel7 = 39, xlExcel9795 = 43, xlExcel4Workbook = 35, xlIntlAddIn = 26, xlIntlMacro = 25, xlWorkbookNormal = -4143, xlSYLK = 2, xlTemplate = 17, xlCurrentPlatformText = -4158, xlTextMac = 19, xlTextMSDOS = 21, xlTextPrinter = 36, xlTextWindows = 20, xlWJ2WD1 = 14, xlWK1 = 5, xlWK1ALL = 31, xlWK1FMT = 30, xlWK3 = 15, xlWK4 = 38, xlWK3FM3 = 32, xlWKS = 4, xlWorks2FarEast = 28, xlWQ1 = 34, xlWJ3 = 40, xlWJ3FJ3 = 41, xlUnicodeText = 42, xlHtml = 44 }; Word: Type enum WdSaveFormat { wdFormatDocument = 0, wdFormatTemplate = 1, wdFormatText = 2, wdFormatTextLineBreaks = 3, wdFormatDOSText = 4, wdFormatDOSTextLineBreaks = 5, wdFormatRTF = 6, wdFormatUnicodeText = 7, wdFormatEncodedText = 7, wdFormatHTML = 8 }; PPT: enum PpSaveAsFileType { ppSaveAsPresentation = 1, ppSaveAsPowerPoint7 = 2, ppSaveAsPowerPoint4 = 3, ppSaveAsPowerPoint3 = 4, ppSaveAsTemplate = 5, ppSaveAsRTF = 6, ppSaveAsShow = 7, ppSaveAsAddIn = 8, ppSaveAsPowerPoint4FarEast = 10, ppSaveAsDefault = 11, ppSaveAsHTML = 12, ppSaveAsHTMLv3 = 13, ppSaveAsHTMLDual = 14, ppSaveAsMetaFile = 15, ppSaveAsGIF = 16, ppSaveAsJPG = 17, ppSaveAsPNG = 18, ppSaveAsBMP = 19 }; */ /* 0x32. 删除本地文件 HRESULT DeleteLocalFile([in] BSTR strFilePath); 参数: strFileName:文件本地路径,如c:\\11.doc */ /* 0x33.创建临时文件 HRESULT GetTempFilePath([out,retval] BSTR* strValue); 返回: 临时文件的路径地址。使用完后,用DeleteLocalFile 删除 */ /* 0x34.设置文档显示模式 HRESULT ShowView([in] long dwViewType, [out,retval] long * pbool); dwViewType的可取值为: enum WdViewType { wdNormalView = 1, wdOutlineView = 2, wdPrintView = 3, wdPrintPreview = 4, wdMasterView = 5, //这个是大纲 wdWebView = 6 }; */ //大纲模式 document.all.FramerControl1.ShowView(5); /* 0x39:下载远程文件 HRESULT DownloadFile( [in] BSTR strRemoteFile, [in] BSTR strLocalFile, [out,retval] BSTR* strValue); 参数: strRemoteFile:远程路径地址,http or Ftp strLocalFile: 本地保存地址,if strLocalFile == NULL then Create Temp File and return TempFile's Path */ /* 0x40:增加Http上传时候的,附加其他文件 HRESULT HttpAddPostFile([in] BSTR strFileID, [in] BSTR strFileName, [out,retval] long* pbool); 参数: strFileID:文件的ID,供服务器端页面解析 strFileName: 本地文件地址 */ /* 0x41,0x42.获取详细的修订信息。 GetRevCount( [out,retval] long * pbool); GetRevInfo([in] long lIndex, [in] long lType, [out,retval] BSTR* pbool); 例子如下 */ var vCount; vCount = document.all.FramerControl1.GetRevCount(); alert(vCount); var vOpt = 0; var vDate; for(var i=1; i<= vCount; i++){ vOpt = document.all.FramerControl1.GetRevInfo(i,2); if("1" == vOpt){ vOpt = "插入"; }else if("2" == vOpt){ vOpt = "删除"; }else{ vOpt = "未知操作"; } vDate = new String(document.all.FramerControl1.GetRevInfo(i,1)); vDate = parseFloat(vDate); alert(vDate); dateObj = new Date(vDate); alert(dateObj.getYear() + "年" + dateObj.getMonth() + 1 + "月" + dateObj.getDate() +"日" + dateObj.getHours() +"时" + dateObj.getMinutes() +"分" + dateObj.getSeconds() +"秒" ); alert("用户:"+document.all.FramerControl1.GetRevInfo(i,0) + "\r\n操作:" + vOpt + "\r\n内容:" + document.all.FramerControl1.GetRevInfo(i,3)); } /* 0x43.设置基本信息: HRESULT SetValue([in] BSTR strValue, [in] BSTR strName, [out,retval] long* pbool); 1.设置文件只读密码 SetValue("password","::DOCPROP:PassWord"); 2.设置文件修改密码 SetValue("password","::DOCPROP:WritePW"); 返回值: 0 正确 -1:不支持此命令,请确定您的第二个参数没有传错 -127:异常 */ //设置文件只读密码 document.all.FramerControl1.SetValue("password","::DOCPROP:PassWord"); //设置文件修改密码 document.all.FramerControl1.SetValue("password","::DOCPROP:WritePW"); /* 0x44.设置文档变量,这个很少能用到 HRESULT SetDocVariable([in] BSTR strVarName, [in] BSTR strValue,[in] long lOpt, [out,retval] long* pbool); strVarName: 变量名 strVlaue:变量值 lOpt: 操作类型, 按位 第一位为1: 表示update域关联的 第二位为1: 表示如果没有这个变量则添加 第三位为1: 未来支持 return: 0:OK -127:异常 */ /* 0x45: 分页保存 HRESULT SetPageAs([in] BSTR strLocalFile, [in] long lPageNum, [in] long lType,[out,retval] long* pbool); strLocalFile:本地路径 lPageNum:页数 */
在线阅读 一、 功能所需工具 下载工具 OpenOffice http://zh.openoffice.org/new/zh_cn/downloads.html JodConverter http://dldx.csdn.net/fd.php?i=992314146801277&s=08dbee95a6e2dda1a95aa8cbf4df197b Swftools(pdf2swf) http://dldx.csdn.net/fd.php?i=389133735472350&s=2f7430ad3c00cca78ada8b4671a50b24 FlexPaper http://flexpaper.googlecode.com/files/FlexPaper_1.4.5_flash.zip 二、 搭建所需环境及实现 第一步:安装OpenOffice。从上述下载地址得到可执行安装文件,直接双击执行,安装过程较为人性化,只需选择下一步即可。此处注意下安装路径,文件转换之前需在Windows命令行窗口打开安装根目录,然后执行开启服务命令。 第二步:解压JodConverter。解压目录结构如下图: 打开lib文件夹, 将其中的jar包复制到Web工程的WebRoot/WEB-INF/lib下。 第三步:安装Swftools。从下载的压缩包中解压得到可执行安装文件,直接双击执行。该转换工具用来将pdf文件转换成swf文件。改工具既可以安装使用实现文件转换,也拷贝安装后Program Files下的Swftools文件夹放到工程中,以绿色软件方式来使用。转换命令将在FileConverterUtil.java中特别指明。 第四步:使用Flexpaper。Flexpaper就是一个播放swf文件的播放器。解压后目录如下: 其中Paper.swf、所有的txt文件、php文件夹和example文件夹都可以删掉。清理完之后,新建readFile.jsp(jsp页面代码在后面附加),然后将flexpaper文件夹拷贝到WebRoot下即可。 FileConverterUtil.java代码如下: package com.sdjt.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; 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; /** * <p>Title: </p> * <p>desc: 档案Action类 * <p>Copyright: Copyright(c)shundesoft 2011</p> * <p>company:济南舜德竟天软件有限公司</p> * @author 温中伟 * @date 2011-10-14 * @version 1.0 * @since */ public class FileConverterUtil{ /** * 实现文件格式转换 * @param sourceFilePath //源文件路径 * @param fullFileName //源文件名称 * @param converterFlag //源文件转换标志 * @throws Exception */ public String convertFile(String sourceFilePath, String fullFileName, String swfToolsPath, String converterFlag) throws Exception{ File sourceFile; //转换源文件 File pdfFile; //PDF媒介文件 File swfFile; //SWF目标文件 File createPath; //创建文件存放目录 Runtime rt; //转换命令执行类 String converFileName = ""; //转换之后的SWF文件名称 String middleFilePath = sourceFilePath.substring(0, sourceFilePath.length()-1); String filePath = (middleFilePath.substring(0, middleFilePath.lastIndexOf("\\"))).substring(0, (middleFilePath.substring(0, middleFilePath.lastIndexOf("\\"))).lastIndexOf("\\")); String fileName = PinYinUtil.getPinYinFirstOrAllLetter(fullFileName.substring(0, fullFileName.lastIndexOf(".")), false)[0]; String fileType = fullFileName.substring(fullFileName.lastIndexOf(".")+1); String folderName = middleFilePath.substring(middleFilePath.lastIndexOf("\\")+1); if(converterFlag.equals("1")){ converFileName = folderName+"/"+fileName+".swf"; }else{ if(fileType.equals("pdf")){ //PDF格式文件处理方式 rt = Runtime.getRuntime(); sourceFile = new File(sourceFilePath+fullFileName); //创建SWF文件存放目录 createPath = new File(filePath+"\\swfFiles\\"+folderName); if(!createPath.isDirectory()){ createPath.mkdir(); } swfFile = new File(filePath+"/swfFiles/"+folderName+"/"+fileName+".swf"); Process p = rt.exec(swfToolsPath+"/pdf2swf.exe " + sourceFile.getPath() + " -o " + swfFile.getPath() + " -T 9"); //缓冲区读入内容清理 clearCache(p.getInputStream(), p.getErrorStream()); converFileName = folderName+"/"+fileName+".swf"; }else{ //非PDF格式文件处理方式 if(isLegal(fileType.toUpperCase())){ sourceFile = new File(sourceFilePath+fullFileName); pdfFile = new File(filePath+"/swfFiles/"+folderName+"/"+fileName+".pdf"); swfFile = new File(filePath+"/swfFiles/"+folderName+"/"+fileName+".swf"); //获取连接对象 OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100); //取得连接 connection.connect(); //创建文件格式转换对象 DocumentConverter converter = new OpenOfficeDocumentConverter(connection); //实现文件格式转换 converter.convert(sourceFile, pdfFile); //生成已转换的PDF文件 pdfFile.createNewFile(); //释放连接 connection.disconnect(); rt = Runtime.getRuntime(); //执行PDF文件转换成SWF文件命令 Process p = rt.exec(swfToolsPath+"/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9"); //缓冲区读入内容清理 clearCache(p.getInputStream(), p.getErrorStream()); //删除中转PDF文件 if(pdfFile.exists()){ pdfFile.delete(); } converFileName = folderName+"/"+fileName+".swf"; } } } return converFileName; } /** * 清理缓冲区 * @param isi * @param ise */ public void clearCache(InputStream isi, InputStream ise){ try { final InputStream is1 = isi; //启用单独线程清空InputStream缓冲区 new Thread(new Runnable() { public void run() { BufferedReader br = new BufferedReader(new InputStreamReader(is1)); try { while(br.readLine() != null) ; } catch (IOException e) { e.printStackTrace(); } } }).start(); //读入ErrorStream缓冲 BufferedReader br = new BufferedReader(new InputStreamReader(ise)); //保存缓冲输出结果 StringBuilder buf = new StringBuilder(); String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } //循环等待进程结束 while(line != null) buf.append(line); is1.close(); ise.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 判断所转换文件类型是否合法 * @param getFileType //文件格式 * @param fileLegalFlag //是否合法标志 false:非法 true:合法 */ public boolean isLegal(String getFileType){ boolean fileLegalFlag = false; if(getFileType.equals("TXT")){ fileLegalFlag = true; }else if(getFileType.equals("DOC")||getFileType.equals("DOCX")){ fileLegalFlag = true; }else if(getFileType.equals("PPT")||getFileType.equals("PPTX")){ fileLegalFlag = true; }else if(getFileType.equals("XLS")||getFileType.equals("XLSX")){ fileLegalFlag = true; } return fileLegalFlag; } } readFile.jsp页面代码如下: <%@ page language="java" import="java.lang.String" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String getFilePath = request.getParameter("recFileName"); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en" xml:lang="en"> <head> <title>在线阅读</title> <style type="text/css" media="screen"> html, body { height:100%; } body { margin:0; padding:0; overflow:auto; } #flashContent { display:none; } </style> [removed][removed] </head> <body> <div <a id="viewerPlaceHolder" [removed] var fp = new FlexPaperViewer( 'FlexPaperViewer', 'viewerPlaceHolder', { config : { SwfFile : escape('../smsdocument/swfFiles/<%=getFilePath%>'), Scale : 0.6, ZoomTransition : 'easeOut', ZoomTime : 0.5, ZoomInterval : 0.2, FitPageOnLoad : true, FitWidthOnLoad : false, PrintEnabled : false, FullScreenAsMaxWindow : false, ProgressiveLoading : true, MinZoomSize : 0.2, MaxZoomSize : 5, SearchMatchAll : false, InitViewMode : 'Portrait', ViewModeToolsVisible : true, ZoomToolsVisible : true, NavToolsVisible : true, CursorToolsVisible : true, SearchToolsVisible : true, localeChain: 'zh_CN' }}); [removed] </div> </body> </html> Struts配置文件: OpenOffice服务启动命令: cd C:\Program Files\OpenOffice.org 3\program soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard 需注意的问题 转换TXT时内容中文乱码问题 反编译jodconverter-2.2.2.jar,反编译好的已经放在在线阅读文件夹下。Jodconverter-2.2.1.jar不出现TXT乱码问题,但是不支持office2007格式的文件转换。 Flexpaper不支持中文路径 中文名称的文件转换成了汉语拼音.swf 参考资料 http://topic.csdn.net/u/20110712/18/4daf5746-e64e-434d-aeb0-77b05f6c9903.html http://www.cnblogs.com/qinpeifeng107/archive/2011/08/29/2158879.html http://blog.csdn.net/liuyuhua0066/article/details/6603493 http://blog.csdn.net/lyq123333321/article/details/6546104 http://www.cnblogs.com/compass/articles/2046311.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值