利用微软的平台进行Office文档的在线查看

一直以来,都希望找一个合适的Office文档查看的控件或者解决方案,这样客户在使用系统的时候,可以直接查看预览一些文档,而不需要安装Office,或者下载到本地在查看。

一个偶然的机会,在网上搜到微软自己提供了一个在线服务,可以实现把Office文档转换为在线的内容进行查看,大家可以通过下面的链接地址大致看看:http://blogs.office.com/2013/04/10/office-web-viewer-view-office-documents-in-a-browser/ 。

使用浏览器直接查看Office文档的链接地址格式如下所示:

http://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2fvideo.ch9.ms%2fbuild%2f2011%2fslides%2fTOOL-532T_Sutter.pptx

这个链接分为了两部分,一部分是http://view.officeapps.live.com/op/view.aspx?src=,后面那个是具体的文档地址,用URLEncode进行处理的链接地址。

非常酷的效果,使用这个服务唯一的要求就是你的网站是部署在互联网上的,这样服务才可以调用你的文档地址然后进行展示。

这个是使用微软的预览Office服务,当然你可以部署自己的Office预览服务,也就是需要安装Office Web Apps服务(系统要求为Windows Server 2012)

一般情况下,Office Web Apps要与其他应用配合使用,如下图所示(看起来还是很复杂的,这些东西好像也要独立安装在不同的机器):

clip_image035

好在微软给我们提供了在线的Office文档预览服务,其实好像Google Doc Viewer也是可以的,但是已经不可使用了。这样,我们就可以利用公开的接口地址实现Office文档的在线预览了。

以常用的Excel文档为例,它可以提供了完美的在线预览效果。

 

我们还注意到上面有一排菜单,可以展开进行相关功能的操作,尤其是文档的下载和打印很吸引。

 

这样我们就可以在我们的文档预览操作页面上进行集成了,下面是我在我的《基于MVC4+EasyUI的Web开发框架》集成的一个例子,对Office文档进行查看

 感觉效果还不错吧。

Word文档也是可以顺利进行预览,但是就没有打印和下载的功能了,不过预览的效果还是很不错的。

 

2、把Office文档生成HTML文件后进行查看

上面说了,使用在线的Office预览服务来查看Office文档,如果我们的管理系统是在局域网内跑的应用,那么我们就是用不了了,那么我们如果需要使用这种在线预览Office文档的服务,应该如何操作呢?

虽然自行搭建Office Web Apps服务应用可以解决这个问题,但是一般来说,搭建这样的平台环境,太过繁琐和昂贵了,有没有更好的方式实现Office文档的查看呢?

有的,下面我来介绍一下,如何使用Aspose组件把Office文档生成HTML,然后进行查看的做法。

对应不同的Office文档,Aspose提供了不同的组件,如Aspose.Word、Aspose.Cells、Aspose.Slides等不同的组件用来处理Word/Excel/PPT等几种文档。

我们知道,Aspose组件在处理Office文档方面非常的强大,但是也是收费软件,所以需要可以购买支持,但是我们这里纯粹讨论它的功能效果。

对不同的文件类型,我们调用不同的组件进行HTML的转换就可以了,核心部分代码如下所示。

复制代码
                            if (ext == "doc" || ext == "docx")
                            {
                                Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                                doc.Save(generateFilePath, Aspose.Words.SaveFormat.Html);
                            }
                            else if (ext == "xls" || ext == "xlsx")
                            {
                                Workbook workbook = new Workbook(templateFile);
                                workbook.Save(generateFilePath, SaveFormat.Html);
                            }
                            else if (ext == "ppt" || ext == "pptx")
                            {
                                templateFile = templateFile.Replace("/", "\\");
                                PresentationEx pres = new PresentationEx(templateFile);
                                pres.Save(generateFilePath, Aspose.Slides.Export.SaveFormat.Html);
                            }
复制代码

这样,我们第一次使用的时候,判断目录里面是否有对应的HTML文件了,如果没有,就使用上面的代码生成就可以了,查看的时候,就返回对应的路径给客户端进行查看文件就可以了。

下面是几个文档的效果截图,供参考。

 

3、集成在线和本地生成文件两者的预览方式

我们在做项目的时候,往往不知道具体的应用是部署在公网(互联网)的环境,还是在局域网的环境,因此要求我们很多功能需要有一定的弹性,如果能够使用公网网的,利用公网微软的Office预览功能,呈现出来的效果比使用aspose组件生成的效果更好,有时候使用aspose组件生成的文档,格式可能有一些不太一样(虽然总体还好)。

因此,如果能够根据需要,对两者能够配置一下,进行切换,应该是比较理想的方案。

下面是我根据需要对它们两者的预览方案进行了集成,通过一个变量进行切换,当然,变量可以写到配置文件里面,这样以后也可以不同修改代码就可以自由切换了。

复制代码
                bool officeInternetView = false;//是否使用互联网在线预览
                string hostName = HttpUtility.UrlPathEncode("http://www.iqidi.com/");//可以配置一下,如果有必要

                if (ext == "xls" || ext == "xlsx" || ext == "doc" || ext == "docx" || ext == "ppt" || ext == "pptx")
                {
                    if (officeInternetView)
                    {
                        //返回一个微软在线浏览Office的地址,需要加上互联网域名或者公网IP地址
                        viewUrl = string.Format("http://view.officeapps.live.com/op/view.aspx?src={0}{1}", hostName, filePath);
                    }
                    else
                    {
                        #region 动态第一次生成文件
                        //检查本地Office文件是否存在,如不存在,先生成文件,然后返回路径供查看
                        string webPath = string.Format("/GenerateFiles/Office/{0}.htm", info.ID);
                        string generateFilePath = Server.MapPath(webPath);
                        if (!FileUtil.FileIsExist(generateFilePath))
                        {
                            string templateFile = BLLFactory<FileUpload>.Instance.GetFilePath(info);
                            templateFile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, templateFile.Replace("\\", "/"));

                            if (ext == "doc" || ext == "docx")
                            {
                                Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                                doc.Save(generateFilePath, Aspose.Words.SaveFormat.Html);
                            }
                            else if (ext == "xls" || ext == "xlsx")
                            {
                                Workbook workbook = new Workbook(templateFile);
                                workbook.Save(generateFilePath, SaveFormat.Html);
                            }
                            else if (ext == "ppt" || ext == "pptx")
                            {
                                templateFile = templateFile.Replace("/", "\\");
                                PresentationEx pres = new PresentationEx(templateFile);
                                pres.Save(generateFilePath, Aspose.Slides.Export.SaveFormat.Html);
                            }
                        }
                        #endregion
                        viewUrl = webPath;
                    }
                }
                else
                {
                    viewUrl = filePath;
                }
复制代码

最后,我在附件管理模块里面实现所有文档的显示,对Office文档和图片文档都可以进行预览,以及其他文档进行下载的操作。

后面进一步介绍一下Web框架上的附件管理模块的操作功能。

在线阅读 一、 功能所需工具 下载工具 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; /** * Title: * desc: 档案Action类 * Copyright: Copyright(c)shundesoft 2011 * company:济南舜德竟天软件有限公司 * @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页面代码如下: <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/'), 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] </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
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值