.net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览

转自源地址:http://www.cnblogs.com/GodIsBoy/p/4009252.html,有部分改动

使用Microsoft的Office组件将文件转换为PDF格式文件,然后再使用pdf2swf转换为swf文件,也就是flash文件在使用FlexPaper展示出来(优点:预览效果能接受,缺点:代码量大)

使用ASPOSE+pdf2swf+FlexPaper

关于ASPOSE大家可以到官网了解,这是款商业收费产品但是免费也可以使用

1、引用dll

这一步的前提是需要去 官网下载 组件

  下载之后,进行安装,然后在安装文件夹找到相应的 dll 库文件,然后引用到自己的项目中去

  比如我要是想Word的在想浏览功能,那么我需要下载的组件是 Aspose.Word,然后安装,最后找到 dll 引用

  

2. 编写相应的转换方法,AsposeUtil 中的方法可根据具体自己需要提取部分,可做相应修改调整后使用

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using Aspose.Cells;
  6 using Aspose.Words;
  7 using Aspose.Slides;
  8 using System.Text.RegularExpressions;
  9 using System.IO;
 10 
 11 namespace Souxuexiao.Common
 12 {
 13   /// <summary>
 14   /// 第三方组件ASPOSE Office/WPS文件转换
 15   /// Writer:Helen Joe
 16   /// Date:2014-09-24
 17   /// </summary>
 18   public class AsposeUtils
 19   {
 20     /// <summary>
 21     /// PFD转换器位置
 22     /// </summary>
 23     private static string _EXEFILENAME = System.Web.HttpContext.Current != null
 24         ? System.Web.HttpContext.Current.Server.MapPath("/pdf2swf/pdf2swf.exe")
 25         : System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\pdf2swf\pdf2swf.exe");
 26 
 27     #region 1.01 Wrod文档转换为PDF文件 +ConvertDocToPdF(string sourceFileName, string targetFileName)
 28     /// <summary>
 29     /// Wrod文档转换为PDF文件
 30     /// </summary>
 31     /// <param name="sourceFileName">需要转换的Word全路径</param>
 32     /// <param name="targetFileName">目标文件全路径</param>
 33     /// <returns>转换是否成功</returns>
 34     public static bool ConvertDocToPdF(string sourceFileName, string targetFileName)
 35     {
 36       Souxuexiao.API.Logger.error(string.Format("Wrod文档转换为PDF文件:sourceFileName={0},targetFileName={1}", sourceFileName, targetFileName));
 37       try
 38       {
 39         using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
 40         {
 41           Document doc = new Document(sourceFileName);
 42           doc.Save(targetFileName, Aspose.Words.SaveFormat.Pdf);
 43         }
 44       }
 45       catch (Exception ex)
 46       {
 47         Souxuexiao.API.Logger.error(string.Format("Wrod文档转换为PDF文件执行ConvertDocToPdF发生异常原因是:{0}",ex.Message));
 48       }
 49       return System.IO.File.Exists(targetFileName);
 50     }
 51     #endregion
 52 
 53     #region 1.02 Excel文件转换为HTML文件 +(string sourceFileName, string targetFileName, string guid)
 54     /// <summary>
 55     /// Excel文件转换为HTML文件 
 56     /// </summary>
 57     /// <param name="sourceFileName">Excel文件路径</param>
 58     /// <param name="targetFileName">目标路径</param>
 59     /// <returns>转换是否成功</returns>
 60     public static bool ConvertExcelToHtml(string sourceFileName, string targetFileName)
 61     {
 62       Souxuexiao.API.Logger.info(string.Format("准备执行Excel文件转换为HTML文件,sourceFileName={0},targetFileName={1}",sourceFileName,targetFileName));
 63       try
 64       {
 65         using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
 66         {
 67           Aspose.Cells.Workbook workbook = new Workbook(stream);
 68           workbook.Save(targetFileName, Aspose.Cells.SaveFormat.Html);
 69         }
 70       }
 71       catch (Exception ex)
 72       {
 73         Souxuexiao.API.Logger.error(string.Format("Excel文件转换为HTML文件ConvertExcelToHtml异常原因是:{0}", ex.Message));
 74       }
 75       return System.IO.File.Exists(targetFileName);
 76     } 
 77     #endregion
 78 
 79     #region 1.03 将PowerPoint文件转换为PDF +ConvertPowerPointToPdf(string sourceFileName, string targetFileName)
 80     /// <summary>
 81     /// 将PowerPoint文件转换为PDF
 82     /// </summary>
 83     /// <param name="sourceFileName">PPT/PPTX文件路径</param>
 84     /// <param name="targetFileName">目标文件路径</param>
 85     /// <returns>转换是否成功</returns>
 86     public static bool ConvertPowerPointToPdf(string sourceFileName, string targetFileName)
 87     {
 88       Souxuexiao.API.Logger.info(string.Format("准备执行PowerPoint转换PDF,sourceFileName={0},targetFileName={1}",sourceFileName,targetFileName));
 89       try
 90       {
 91         using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
 92         {
 93           Aspose.Slides.Pptx.PresentationEx pptx = new Aspose.Slides.Pptx.PresentationEx(stream);
 94           pptx.Save(targetFileName, Aspose.Slides.Export.SaveFormat.Pdf);
 95         }
 96       }
 97       catch (Exception ex)
 98       {
 99         Souxuexiao.API.Logger.error(string.Format("将PowerPoint文件转换为PDFConvertExcelToHtml异常原因是:{0}", ex.Message));
100       }
101       return System.IO.File.Exists(targetFileName);
102     } 
103     #endregion
104 
105     #region 2.01 读取pdf文件的总页数 +GetPageCount(string pdf_filename)
106     /// <summary>
107     /// 读取pdf文件的总页数
108     /// </summary>
109     /// <param name="pdf_filename">pdf文件</param>
110     /// <returns></returns>
111     public static int GetPageCountByPDF(string pdf_filename)
112     {
113       int pageCount = 0;
114       if (System.IO.File.Exists(pdf_filename))
115       {
116         try
117         {
118           byte[] buffer = System.IO.File.ReadAllBytes(pdf_filename);
119           if (buffer != null && buffer.Length > 0)
120           {
121             pageCount = -1;
122             string pdfText = Encoding.Default.GetString(buffer);
123             Regex regex = new Regex(@"/Types*/Page[^s]");
124             MatchCollection conllection = regex.Matches(pdfText);
125             pageCount = conllection.Count;
126           }
127         }
128         catch (Exception ex)
129         {
130           Souxuexiao.API.Logger.error(string.Format("读取pdf文件的总页数执行GetPageCountByPowerPoint函数发生异常原因是:{0}", ex.Message));
131         }
132       }
133       return pageCount;
134     }
135     #endregion
136 
137     #region 2.02 转换PDF文件为SWF格式 +PDFConvertToSwf(string pdfPath, string swfPath, int page)
138     /// <summary>
139     /// 转换PDF文件为SWF格式
140     /// </summary>
141     /// <param name="pdfPath">PDF文件路径</param>
142     /// <param name="swfPath">SWF生成目标文件路径</param>
143     /// <param name="page">PDF页数</param>
144     /// <returns>生成是否成功</returns>
145     public static bool PDFConvertToSwf(string pdfPath, string swfPath, int page)
146     {
147       StringBuilder sb = new StringBuilder();
148       sb.Append(" "" + pdfPath + """);
149       sb.Append(" -o "" + swfPath + """);
150       sb.Append(" -z");
151       //flash version
152       sb.Append(" -s flashversion=9");
153       //禁止PDF里面的链接
154       sb.Append(" -s disablelinks");
155       //PDF页数
156       sb.Append(" -p " + ""1" + "-" + page + """);
157       //SWF中的图片质量
158       sb.Append(" -j 100");
159       string command = sb.ToString();
160       System.Diagnostics.Process p = null;
161       try
162       {
163         using (p = new System.Diagnostics.Process())
164         {
165           p.StartInfo.FileName = _EXEFILENAME;
166           p.StartInfo.Arguments = command;
167           p.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(_EXEFILENAME);
168           //不使用操作系统外壳程序 启动 线程
169           p.StartInfo.UseShellExecute = false;
170           //p.StartInfo.RedirectStandardInput = true;
171           //p.StartInfo.RedirectStandardOutput = true;
172 
173           //把外部程序错误输出写到StandardError流中(pdf2swf.exe的所有输出信息,都为错误输出流,用 StandardOutput是捕获不到任何消息的...
174           p.StartInfo.RedirectStandardError = true;
175           //不创建进程窗口
176           p.StartInfo.CreateNoWindow = false;
177           //启动进程
178           p.Start();
179           //开始异步读取
180           p.BeginErrorReadLine();
181           //等待完成
182           p.WaitForExit();
183         }
184       }
185       catch (Exception ex)
186       {
187         Souxuexiao.API.Logger.error(string.Format("转换PDF文件为SWF格式执行PDFConvertToSwf函数发生异常原因是:{0}", ex.Message));
188       }
189       finally
190       {
191         if (p != null)
192         {
193           //关闭进程
194           p.Close();
195           //释放资源
196           p.Dispose();
197         }
198       }
199       return File.Exists(swfPath);
200     }
201     #endregion
202   }
203 }

另:项目使用,根据需要有一些的改动

  这里还需要下载 swf 转换工具 swfTools  官网下载 安装,然后在安装目录找到 pdf2swf.exe,我是放在 项目的 bin 文件夹下面,其实可以自己放在任意的位置,只是使用的时候填好路径。

  

封装一个传参数的类:

    public class FlexPaper
    {
        public int ID { get; set; }

        public string SwfFileName { get; set; }

        public string PdfFile { get; set; }

        public string SwfFile { get; set; }
    }

转换的工具类:

  (1).  Word 转Pdf 的帮助类  

public class WordHelper
    {
        /// <summary>
        /// Wrod文档转换为PDF文件
        /// </summary>
        /// <param name="sourceFileName">需要转换的Word全路径</param>
        /// <param name="targetFileName">目标文件全路径</param>
        /// <returns>转换是否成功</returns>
        public static bool ConvertDocToPdF(string sourceFileName, string targetFileName)
        {
            try
            {
                using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                {
                    Document doc = new Document(sourceFileName);
                    doc.Save(targetFileName, Aspose.Words.SaveFormat.Pdf);
                }
            }
            catch (Exception ex)
            {
               
            }
            return System.IO.File.Exists(targetFileName);
        }

  (2). pdf转 swf 的帮助类

 public class FlexPaperEntity
    {
        public List<FlexPaper> GetSwfFile(FlexPaper fp)
        {
            //string TemporaryDirectory = "~/Temp/";
            //string fID = fp.ID.ToString();
            string filePdf = fp.PdfFile;// TemporaryDirectory + fID + ".pdf";

            string fileName = Guid.NewGuid().ToString();
            string fileswf = fp.SwfFile; //TemporaryDirectory + fileName + ".swf";

            using(System.Diagnostics.Process p =new System.Diagnostics.Process())
            {
                //获取 执行转换功能的文件路径
                p.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/bin/pdf2swf.exe");
                //p.StartInfo.Arguments = " -t " + HttpContext.Current.Server.MapPath(filePdf) + " -s flashversion=9 -o " + HttpContext.Current.Server.MapPath(fileswf);
                //转换命令
                p.StartInfo.Arguments = " -t " + filePdf + " -s flashversion=9 -o " +fileswf;
                //相应参数的设置
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.UseShellExecute = false;
                //开始执行
                p.Start();
                p.WaitForExit();
            }
            //返回保存的路径
            List<FlexPaper> oo = new List<FlexPaper>();
            oo.Add(new FlexPaper { SwfFile = "/Temp/" + fp.SwfFileName + ".swf" });
            return oo;
        }
    }

 写了一个测试用的 ashx 一般处理程序

   public class GetSwf : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //int fileID = Convert.ToInt32(context.Request["fileID"]);

            string docFile = context.Server.MapPath("~/Temp/129.doc");
            string pdfFile = context.Server.MapPath("~/Temp/129.pdf");

            WordHelper.ConvertDocToPdF(docFile, pdfFile);
            
            string fileName = Guid.NewGuid().ToString();
            string swfFile = context.Server.MapPath("~/Temp/" + fileName + ".swf");
            FlexPaper fp = new FlexPaper() {SwfFileName=fileName,  PdfFile = pdfFile, SwfFile = swfFile };
            FlexPaperEntity ent = new FlexPaperEntity();
            List<FlexPaper> lis = ent.GetSwfFile(fp);
            context.Response.Write(DataHelper.JsonSerialize(lis));
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

前台页面: js 相关文件可在此处下载

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PDF_Test.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style type="text/css">

        #flashContent{
            display:none;
        }


    </style>

    <script src="Scripts/jquery-1.8.3-min.js" type="text/javascript"></script>
    <script src="js/flexpaper_flash.js" type="text/javascript"></script>
    <script src="js/flexpaper_flash_debug.js" type="text/javascript"></script>
    <script src="js/swfobject/swfobject.js" type="text/javascript"></script>
   

    <script type="text/javascript">


        $.get("/GetSwf.ashx", { }, function (data) {
           
            $.each(data, function (i, item) {
                var script = "<script type="text/javascript">var swfFile='" + item.swfFile + "'</scr" + "ipt>";
                $('head').append(script);
            });
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.src = "/js/InsusDocumentView.js";
            $('head').append(s);
        }, "json");


    </script>



</head>
<body>
    <div style="position: absolute; left: 3px; top: 3px;" align="center">
        <div id="flashContent">
            <p>
                To view this page ensure that Adobe Flash Player version 10.0.0 or greater is installed.
            </p>
            <script type="text/javascript">
                var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://");
                document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='" + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>");
            </script>
        </div>
    </div>
</body>
</html>

 附:整个测试项目的文件结构

  注:ppt转换PDF如果有问题,可再联系....

  由于试用版限制只能转换5页文件,所以有可能的话就使用 aspose 破解版

原文地址:https://www.cnblogs.com/yougmi/p/4815836.html