web文档在线阅览

之前遇到很多各种文档在线阅览的需求,也有不少朋友经常问我这种需求的实现方案,大致试了一下网上的一些比较主流的推荐方案,但都不尽如人意,这里有一个比较全面的总结,需要的朋友可以根据自己的需求到这里查看, Office在线预览及PDF在线预览的实现方式大集合。本文选择功能比较强大,实现比较简单的一种方案,Aspose组件把Office及其PDF文档转换成HTML,然后进行查看。

  Aspose组件在处理Office及其PDF文档方面非常的强大,据说可以在没有安装Microsoft Office的机器上工作,所有的Aspose组件都是独立,不需要微软公司的授权,一般服务器或者普通电脑都装了office,这里也没有亲自在没有安装office的电脑上测试过,所以感兴趣的朋友可以自行测试。对应不同的文档,Aspose提供了不同的组件,如Aspose.Word、Aspose.Cells、Aspose.Slides、Aspose.Pdf等不同的组件用来处理Word/Excel/PPT/PDF等几种文档。Aspose支持的文档格式也非常丰富:Doc,Docx,RTF,HTML,OpenDocument,Excel,Ppt,PDF,XPS,EPUB和其他格式,同时支持不同文档类型之间的相互转换,允许创建,修改,提取,复制,分割,加入,和替换文件内容。但是也是收费软件,所以大家在使用的时候一定要慎重考虑,这里纯粹讨论它的功能效果。本文重点讨论文档在线阅览,对不同的文件类型,我们调用不同的组件可以将文档转换成image或者HTML。

  将文档转换成image查看的场景可能不是很多,所以这里只展示一下将word文档转换成Image的场景,其他如:Excel,PPT,PDF等转换成image查看的场景大家可以根据Aspose相关组件自行转换。其核心代码如下:


public ActionResult GetDocumentData(string filePath, string sessionID)
        {
            // Common.SetWordsLicense();
            List<string> result = new List<string>();
            try
            {
                string documentFolder = AsposeWord.CreateTempFolders(filePath, sessionID);
                Aspose.Words.Document doc = new Aspose.Words.Document(filePath);
                Aspose.Words.Saving.ImageSaveOptions options = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg);
                options.PageCount = 1;
                for (int i = 0; i < doc.PageCount; i++)
                {
                    options.PageIndex = i;
                    doc.Save(string.Format(@"{0}\{1}.png", documentFolder, i), options);
                }
                result.Add(Common.Success);
                result.Add(doc.PageCount.ToString());
                var appPath = System.Web.HttpContext.Current.Server.MapPath("~");
                result.Add(documentFolder.Replace(appPath, "/").Replace("\\", "/"));
            }
            catch (Exception ex)
            {
                result.Clear();
                result.Add(Common.Error + ": " + ex.Message);
            }
            return Content(JsonConvert.SerializeObject(result));
        }

最终效果图

更多的开发者可能更喜欢将文档转换成HTML进行阅览,我们来看一下将office文档文档转换成html进行阅览的核心代码,根据文件的后缀名判断是用那种Aspose组件进行转换,然后对应创建该文件的HTML文档。

public ActionResult GetAsposeOfficeFiles(string filePath, string sessionID, int pageIndex)
        {
            var pageView = false;
            var viewUrl = string.Empty;
            var result = new List<string>();
            var fileInfo = new FileInfo(filePath);

            var hostName = HttpUtility.UrlPathEncode(filePath.Replace("\\", "//"));
            var webPath = Path.Combine(Common.PageDocumentDir, string.Format("Office/{0}.html", sessionID));
            var generateFilePath = Server.MapPath(webPath);
            try
            {
                if (fileInfo.Extension == ".xls" || fileInfo.Extension == ".xlsx" || fileInfo.Extension == ".doc"
                 || fileInfo.Extension == ".docx" || fileInfo.Extension == ".ppt" || fileInfo.Extension == ".pptx")
                {
                    #region 动态第一次生成文件
                    if (!System.IO.File.Exists(generateFilePath))
                    {
                        if (fileInfo.Extension == ".doc" || fileInfo.Extension == ".docx")
                        {
                            Document doc = new Document(filePath);
                            doc.Save(generateFilePath, Aspose.Words.SaveFormat.Html);
                        }
                        else if (fileInfo.Extension == ".xls" || fileInfo.Extension == ".xlsx")
                        {
                            Workbook workbook = new Workbook(filePath);
                            workbook.Save(generateFilePath, Aspose.Cells.SaveFormat.Html);
                        }
                        else if (fileInfo.Extension == ".ppt" || fileInfo.Extension == ".pptx")
                        {
                            using (Aspose.Slides.Presentation pres = new Aspose.Slides.Presentation(filePath))
                            {
                                var a = pres.Slides.Count;
                                HtmlOptions htmlOpt = new HtmlOptions();
                                htmlOpt.HtmlFormatter = HtmlFormatter.CreateDocumentFormatter("", false);
                                pres.Save(generateFilePath, Aspose.Slides.Export.SaveFormat.Html, htmlOpt);
                            }
                        }
                    }
                    #endregion
                    viewUrl = webPath;
                } 43             }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            result.Add(false.ToString());
            result.Add(viewUrl);
            result.Add(pageView.ToString());
            result.Add(pageIndex.ToString());
            return Content(JsonConvert.SerializeObject(result));
        }

最后就是通过Iframe调用生成的HTML查看效果:

$.ajax({
        type: "POST",
        url: "/commons/Aspose/GetAsposeOfficeFiles",
        data: '{ filePath: "' + filePath + '" , sessionID: "' + guid() + '", pageIndex: "' + pageIndex + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            //var officeInternetView = result[0];
            var viewUrl = result[1];
            var pageView = result[2];
            var tempPage = result[3];

            var paging = $("#paging");
            if (pageView === "True") {
                paging[0].style.display = "block";
                $("#page-nav")[0].value = tempPage;
            } else {
                paging[0].style.display = "none";
            }
            $("#CurrentDocumentPage").attr("src", viewUrl);
        },


对于比较大(如大于5M)的pdf文档一般都有数百页的内容了,对于这样的“大”文档一次性转换成HTML文档相对比较慢,所以我们通常会考虑到按指定页来转换,根据页码转换需要的哪一页,这样转换非常快,而且可以随意指定要查看那一页:

else if (fileInfo.Extension == ".pdf")
                {
                    if (pageIndex == 0 && fileInfo.Length / 1024 / 1024 < 2)
                    {
                        var pdfDocument = new Aspose.Pdf.Document(filePath);
                        pdfDocument.Save(generateFilePath, Aspose.Pdf.SaveFormat.Html);
                    }
                    else if (pageIndex == 0)
                    {
                        pageIndex++;
                        pageView = true;
                        var pdfDocument = new Aspose.Pdf.Document(filePath);
                        Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document();
                        newDocument.Pages.Add(pdfDocument.Pages[pageIndex]);
                        newDocument.Save(generateFilePath, Aspose.Pdf.SaveFormat.Html);

                    }
                    else if (pageIndex == -1)
                    {
                        pageView = true;
                        var pdfDocument = new Aspose.Pdf.Document(filePath);
                        Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document();
                        newDocument.Pages.Add(pdfDocument.Pages[pdfDocument.Pages.Count]);
                        newDocument.Save(generateFilePath, Aspose.Pdf.SaveFormat.Html);
                        pageIndex = pdfDocument.Pages.Count;
                    }
                    else
                    {
                        pageView = true;
                        var pdfDocument = new Aspose.Pdf.Document(filePath);
                        if (pageIndex > 0 && pageIndex < pdfDocument.Pages.Count)
                        {
                            Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document();
                            newDocument.Pages.Add(pdfDocument.Pages[pageIndex]);
                            newDocument.Save(generateFilePath, Aspose.Pdf.SaveFormat.Html);
                        }
                        else
                        {
                            Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document();
                            newDocument.Pages.Add(pdfDocument.Pages[pdfDocument.Pages.Count]);
                            newDocument.Save(generateFilePath, Aspose.Pdf.SaveFormat.Html);
                            pageIndex = pdfDocument.Pages.Count;
                        }
                    }
                    viewUrl = webPath;

上传文件:

public ActionResult UploadFile()
        {
            HttpFileCollectionBase files = Request.Files;
            HttpPostedFileBase file = files["file1"];
            if (file != null && file.ContentLength > 0)
            {
                string fileName = file.FileName;
                if (fileName.LastIndexOf("\\", StringComparison.Ordinal) > -1)
                {
                    fileName = fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1);
                }
                string path = Server.MapPath(Common.DataDir);
                try
                {
                    file.SaveAs(path + fileName);
                    ViewBag.message = "上传成功!";
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            return RedirectToAction("Index", "../Home");
        }

下载

function DownloadFile(row) {
$.get("/commons/Aspose/DownloadFile?filePath=" + encodeURI(row.FullName),
function (result) {
location.href = result;
});
}

public string DownloadFile(string filePath, string sessionID)
{
var appPath = System.Web.HttpContext.Current.Server.MapPath("~");
var result = filePath.Replace(appPath, "/").Replace("\\", "/");
return result;
}

注意:在线阅览中,细心的朋友可能已经注意到了我的代码中有一个sessionID,每次阅览文件都会创建一个名为sessionID的文件夹,我想这一定不是大家所期望的,那用意何在在呢?实际上同一个文件我们只需要一次生成HTML文件就可以了,无需每次阅览都都重复生成这些文件。实际项目中,我们期望每上传一个文件就创建一个唯一的标示,这个标示跟对应文件之间建立某种关系,在线阅览的时候就根据这个唯一标识创建对应的HTML文件就可以了,这样,同一个文件在下一次阅览的时候先根据这个标示去检查对应的HTML文件是否存在,如果存在直接阅览就OK了,如果不存在,则先创建HTML文件,再进行阅览,另外时间比较仓促,本文的demo考虑不周,测试不足,可能有些小小的bug,大家在用的时候自行完善。

  一般这样的需求,比较完善一点就需要有文件上传,在线阅览,文件下载,文件删除,在线编辑等功能,前面几个功能也算是有比较完善的解决方案了,最后一个在线编辑还没有合适的解决方案,如果哪位朋友在web在线编辑方面有比较好的解决方案,请告诉我一下,接下来会花一定时间研究一下web在线编辑,可视化等,还望大家多多支持,有新的成果一定第一时间与大家分享。  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值