tnblog
首页
视频
资源
登录

Asp.net MVC 利用(aspose+pdfobject.js) 实现在线预览office文档

8511人阅读 2019/8/3 21:11 总访问:62542 评论:2 收藏:1 手机
分类: GET新技能

Aspose.Total是Aspose公司旗下的最全的一套office文档管理方案,通过它,我们可以有计划地操纵一些商业中最流行的文件格式:Word, Excel, PowerPoint, Project,等office文档以及PDF文档。 pdfobejct是一种开源标准友好的JavaScript实用程序,用于将PDF文件嵌入到HTML文档中。

在这里我们将用到这两种来实现在线预览office文档,

pdfobejct可以去官网下载:https://pdfobject.com/

如果找不到的朋友呢,也可以从我的网盘中下载,一些需要的东西都放在里面打包好了。可以直接放在项目中引用。

链接: https://pan.baidu.com/s/1sl7yP68PW4KfbnP9nT8DXg 提取码: qtdw

在这里我们需要引用一下这三个

将需要的css和js下载好后,引用到页面,然后写页面代码

<link href="~/css/index.css" rel="stylesheet" />
<link href="~/Js/PopupDialog/sexylightbox.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Js/pdfobject/pdfobject.js"></script>
<script src="~/Js/index.js"></script>
<script src="~/Js/PopupDialog/jquery.easing.1.3.js"></script>
<script src="~/Js/PopupDialog/sexylightbox.v2.3.jquery.min.js"></script>
<script src="~/Js/zDialog/zDrag.js"></script>
<script src="~/Js/zDialog/zDialog.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div class="fileArea">
        <div>
            <img src="~/Images/word.png" />
            <a class="docViewDownload"
               onclick="viewDoc('wordtest.doc');">
                &nbsp;预&nbsp;览
            </a>
        </div>
        <div>
            <img src="~/Images/excel.png" />
            <a class="docViewDownload"
               onclick="viewDoc('exceltest.xls');">
                &nbsp;预&nbsp;览
            </a>
        </div>
        <div>
            <img src="~/Images/ppt.png" />
            <a class="docViewDownload"
               onclick="viewDoc('ppttest.pptx');">
                &nbsp;预&nbsp;览
            </a>
        </div>
        <div>
            <img src="~/Images/pdf.png" />
            <a class="docViewDownload"
               onclick="viewDoc('pdftest.pdf');">
                &nbsp;预&nbsp;览
            </a>
        </div>
    </div>

    <a id="hidePopupDialog" style="display:none"
       href="" rel="sexylightbox">预览</a>
</body>
</html>

onclick="viewDoc('wordtest.doc')中,写需要浏览的文档的名称以及格式。

然后在这里贴一下CSS和JS的代码,css和JS命名为index,在页面中有引用,当然也可以写在页面当中。

.fileArea {
  width:700px;
  height:700px;
}

.fileArea div {
    float: left;
    width: 121px;
    height: 150px;
}

.fileArea img {
    width: 121px;
    height: 121px;
}

.docViewDownload {
    float: left;
    cursor: pointer;
    width: 75px;
    height: 30px;
    display: block;
    line-height: 30px;
    margin-left: 22px;
    color: white;
    background-color: #63a1df;
}

/*遮罩层开始*/
.datagrid-mask {
    background: #999;
}

.datagrid-mask {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0.3;
    filter: alpha(opacity=30);
    display: none;
}

.datagrid-mask-msg {

}

.datagrid-mask-msg {
    position: absolute;
    top: 50%;
    margin-top: -20px;
    padding: 10px 5px 10px 30px;
    width: auto;
    height: 16px;
    border-width: 2px;
    border-style: solid;
    display: none;
    background: #fff;
    border: 1px solid #448abb;
    background: #fff url('/images/loading.gif') no-repeat scroll 5px center;
}
/*遮罩层结束*/
$(function () {
    SexyLightbox.initialize({ color: 'white' });
});

var viewDoc = function (fileName) {
    showLoading("body", "正在生成预览");
    //生成html文件  
    $.ajax({
        url: "/PreviewFiles/CourseViewOnLine?fileName=" + fileName,
        type: "GET",
        dataType: "json",
        success: function (data) {
            closeLoading();

            //alert(JSON.stringify(data));
            //alert(data[0].TempDocHtml);
            var diag = new Dialog();
            diag.Width = 1300;
            diag.Height = 600;
            diag.Title = "内容页为外部连接的窗口";
            diag.URL = data.TempDocHtml + "?ver=" + Math.random() * 10;
            diag.show();

            //$("#hidePopupDialog").attr('href', '' + data[0].TempDocHtml + '?TB_iframe=true&height=450&width=920');
            //$("#hidePopupDialog").click();
        },
        error: function () {
            closeLoading();
            alert('生成失败');
        }
    });
}
// 加载遮罩
var showLoading = function (elementTag, message) {
    var msg = message ? message : "加载数据,请稍候...";
    $("<div class=\"datagrid-mask\"></div>").css({
        display: "block", width: "100%",
        height: $(elementTag).height()
    }).appendTo(elementTag);
    $("<div class=\"datagrid-mask-msg\"></div>")
        .html(msg)
        .appendTo(elementTag).css({ display: "block", left: "30%", top: ($(elementTag).height() - 45) / 2 });
};

//关闭遮罩
var closeLoading = function () {
    $('.datagrid-mask').remove();
    $('.datagrid-mask-msg').remove();
};

这里我们创建一个控制器,控制器名称随意,只要JS中URL地址和控制器名称改成一样的就行。

private bool PdfToHtml(string fileName, string tempFile, string saveDoc)
        {
            //---------------------读html模板页面到stringbuilder对象里---- 
            StringBuilder htmltext = new StringBuilder();
            using (StreamReader sr = new StreamReader(tempFile)) //模板页路径
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    htmltext.Append(line);
                }
                sr.Close();
            }

            fileName = fileName.Replace("\\", "/");
            //----------替换htm里的标记为你想加的内容 
            htmltext.Replace("$PDFFILEPATH", fileName);

            //----------生成htm文件------------------―― 
            using (StreamWriter sw = new StreamWriter(saveDoc, false,
                System.Text.Encoding.GetEncoding("utf-8"))) //保存地址
            {
                sw.WriteLine(htmltext);
                sw.Flush();
                sw.Close();

            }

            return true;
        }
        
        private bool OfficeDocumentToHtml(string sourceDoc, string saveDoc)
        {
            bool result = false;

            //获取文件扩展名
            string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
            switch (docExtendName)
            {
                case ".doc":
                case ".docx":
                    Aspose.Words.Document doc = new Aspose.Words.Document(sourceDoc);
                    doc.Save(saveDoc, Aspose.Words.SaveFormat.Html);

                    result = true;
                    break;
                case ".xls":
                case ".xlsx":
                    Workbook workbook = new Workbook(sourceDoc);
                    //workbook.Open(sourceDoc);
                    //workbook.Save(saveDoc, FileFormatType.AsposePdf);
                    workbook.Save(saveDoc, Aspose.Cells.SaveFormat.Html);


                    result = true;
                    break;
                case ".ppt":
                case ".pptx":
                    //templateFile = templateFile.Replace("/", "\\");
                    //string templateFile = sourceDoc;
                    //templateFile = templateFile.Replace("/", "\\");
                    PresentationEx pres = new PresentationEx(sourceDoc);
                    pres.Save(saveDoc, Aspose.Slides.Export.SaveFormat.Html);

                    result = true;
                    break;
                default:
                    break;
            }

            return result;
        }



        [HttpGet]
        public string CourseViewOnLine(string fileName) 
        {
            //DataTable dtlist = new DataTable();
            //dtlist.Columns.Add("TempDocHtml", typeof(string));
            string json = "";
            string fileDire = "/Files";
            string sourceDoc = Path.Combine(fileDire, fileName);
            string saveDoc = "";

            string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
            bool result = false;
            if (docExtendName == ".pdf")
            {
                //pdf模板文件
                string tempFile = Path.Combine(fileDire, "temppdf.html");
                saveDoc = Path.Combine(fileDire, "viewFiles/onlinepdf.html");
                result = PdfToHtml(
                      sourceDoc,
                       System.Web.HttpContext.Current.Server.MapPath(tempFile),
                      System.Web.HttpContext.Current.Server.MapPath(saveDoc));
            }
            else
            {
                saveDoc = Path.Combine(fileDire, "viewFiles/onlineview.html");
                result = OfficeDocumentToHtml(
                      System.Web.HttpContext.Current.Server.MapPath(sourceDoc),
                      System.Web.HttpContext.Current.Server.MapPath(saveDoc));
            }

            if (result)
            {
                json = "{\"TempDocHtml\":\"" + saveDoc.Replace("\\","/") + "\"}";
                //dtlist.Rows.Add(saveDoc);
            }

            return json;
        }

 string fileDire = "/Files";这里路径下就是浏览的文档路径,不要写错了,不然会无法预览。

这时要做的都做好了,我们调试项目看一下

然后随便点击一个看看效果

到这里预览文档就成功了


我们下次再见~



点个关注再走呗

评价
幼儿园抢饭第一名
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术