主頁(yè) > 知識(shí)庫(kù) > .NET實(shí)現(xiàn)在網(wǎng)頁(yè)中預(yù)覽Office文件的3個(gè)方法

.NET實(shí)現(xiàn)在網(wǎng)頁(yè)中預(yù)覽Office文件的3個(gè)方法

熱門(mén)標(biāo)簽:百度地圖怎樣做地圖標(biāo)注 400電話如何申請(qǐng)取消 昆明語(yǔ)音電銷(xiāo)機(jī)器人價(jià)格 征途美甲店地圖標(biāo)注 浦發(fā)電話機(jī)器人提醒還款 太原400電話上門(mén)辦理 電銷(xiāo)語(yǔ)音機(jī)器人型號(hào)參數(shù) 柳州電銷(xiāo)機(jī)器人公司 騰訊地圖標(biāo)注手機(jī)

近日公司要搞一個(gè)日常的文檔管理的東東,可以上傳、下載各種文件,如果是office文件呢還必須得支持預(yù)覽功能,其他的都好說(shuō)但是唯獨(dú)office預(yù)覽功能比較麻煩,但是不能不做,廢話不多說(shuō)了一步步來(lái)吧。分析了下網(wǎng)易郵箱的文件預(yù)覽功能,他用的是微軟的組件,最早叫Office online,現(xiàn)在分開(kāi)了叫Word online、Excel online ....等等,效果十分炫酷功能十分強(qiáng)大,但是查看了下對(duì)api的說(shuō)明發(fā)現(xiàn)對(duì)服務(wù)器的要求比較苛刻而且配置比較復(fù)雜不太適合。然后 又看了下騰訊用的是永中第三方組件,效果嘛自然比不上微軟的但是能用,綜合網(wǎng)上的一些資料大概也就那么幾種方式實(shí)現(xiàn)

1.使用Microsoft的Office組件將文件直接轉(zhuǎn)換為html文件(優(yōu)點(diǎn):代碼實(shí)現(xiàn)最簡(jiǎn)單,工作強(qiáng)度最小。缺點(diǎn):效果極差)

2.使用Microsoft的Office組件將文件轉(zhuǎn)換為PDF格式文件,然后再使用pdf2swf轉(zhuǎn)換為swf文件,也就是flash文件在使用FlexPaper展示出來(lái)(優(yōu)點(diǎn):預(yù)覽效果能接受,缺點(diǎn):代碼量大)

效果如圖:

3. 使用Office online(優(yōu)點(diǎn):表現(xiàn)完美,缺點(diǎn):不適合中小企業(yè)應(yīng)用)

綜合考慮決定使用第二種方法,經(jīng)過(guò)次次波折終于可以使用,但是有個(gè)問(wèn)題至今沒(méi)有得到解決,調(diào)用Office組件的時(shí)候有時(shí)候會(huì)出現(xiàn)如下異常:

檢索 COM 類(lèi)工廠中 CLSID 為 {000209FF-0000-0000-C000-000000000046} 的組件失敗,原因是出現(xiàn)以下錯(cuò)誤: 8000401a 因?yàn)榕渲脴?biāo)識(shí)不正確,系統(tǒng)無(wú)法開(kāi)始服務(wù)器進(jìn)程。請(qǐng)檢查用戶(hù)名和密碼。 (異常來(lái)自 HRESULT:0x8000401A),查閱無(wú)數(shù)資料還是不能解決,最讓人不可接受的的是office文件必須標(biāo)標(biāo)準(zhǔn)準(zhǔn)毫無(wú)容錯(cuò)能力,當(dāng)轉(zhuǎn)換ppt文件時(shí)竟然會(huì)彈出轉(zhuǎn)換進(jìn)度框??!

好吧!那么我們改進(jìn)它。

使用ASPOSE+pdf2swf+FlexPaper

關(guān)于ASPOSE大家可以到官網(wǎng)了解,這是款商業(yè)收費(fèi)產(chǎn)品但是免費(fèi)也可以使用

1、引用dll

2、編寫(xiě)轉(zhuǎn)換幫助類(lèi)

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Cells;
using Aspose.Words;
using Aspose.Slides;
using System.Text.RegularExpressions;
using System.IO;

namespace Souxuexiao.Common
{
    /// summary>
    /// 第三方組件ASPOSE Office/WPS文件轉(zhuǎn)換
    /// Writer:Helen Joe
    /// Date:2014-09-24
    /// /summary>
    public class AsposeUtils
    {
        /// summary>
        /// PFD轉(zhuǎn)換器位置
        /// /summary>
        private static string _EXEFILENAME = System.Web.HttpContext.Current != null
                ? System.Web.HttpContext.Current.Server.MapPath("/pdf2swf/pdf2swf.exe")
                : System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\pdf2swf\\pdf2swf.exe");

        #region 1.01 Wrod文檔轉(zhuǎn)換為PDF文件 +ConvertDocToPdF(string sourceFileName, string targetFileName)
        /// summary>
        /// Wrod文檔轉(zhuǎn)換為PDF文件
        /// /summary>
        /// param name="sourceFileName">需要轉(zhuǎn)換的Word全路徑/param>
        /// param name="targetFileName">目標(biāo)文件全路徑/param>
        /// returns>轉(zhuǎn)換是否成功/returns>
        public static bool ConvertDocToPdF(string sourceFileName, string targetFileName)
        {
            Souxuexiao.API.Logger.error(string.Format("Wrod文檔轉(zhuǎn)換為PDF文件:sourceFileName={0},targetFileName={1}", sourceFileName, 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)
            {
                Souxuexiao.API.Logger.error(string.Format("Wrod文檔轉(zhuǎn)換為PDF文件執(zhí)行ConvertDocToPdF發(fā)生異常原因是:{0}",ex.Message));
            }
            return System.IO.File.Exists(targetFileName);
        }
        #endregion

        #region 1.02 Excel文件轉(zhuǎn)換為HTML文件 +(string sourceFileName, string targetFileName, string guid)
        /// summary>
        /// Excel文件轉(zhuǎn)換為HTML文件
        /// /summary>
        /// param name="sourceFileName">Excel文件路徑/param>
        /// param name="targetFileName">目標(biāo)路徑/param>
        /// returns>轉(zhuǎn)換是否成功/returns>
        public static bool ConvertExcelToHtml(string sourceFileName, string targetFileName)
        {
            Souxuexiao.API.Logger.info(string.Format("準(zhǔn)備執(zhí)行Excel文件轉(zhuǎn)換為HTML文件,sourceFileName={0},targetFileName={1}",sourceFileName,targetFileName));
            try
            {
                using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                {
                    Aspose.Cells.Workbook workbook = new Workbook(stream);
                    workbook.Save(targetFileName, Aspose.Cells.SaveFormat.Html);
                }
            }
            catch (Exception ex)
            {
                Souxuexiao.API.Logger.error(string.Format("Excel文件轉(zhuǎn)換為HTML文件ConvertExcelToHtml異常原因是:{0}", ex.Message));
            }
            return System.IO.File.Exists(targetFileName);
        }
        #endregion

        #region 1.03 將PowerPoint文件轉(zhuǎn)換為PDF +ConvertPowerPointToPdf(string sourceFileName, string targetFileName)
        /// summary>
        /// 將PowerPoint文件轉(zhuǎn)換為PDF
        /// /summary>
        /// param name="sourceFileName">PPT/PPTX文件路徑/param>
        /// param name="targetFileName">目標(biāo)文件路徑/param>
        /// returns>轉(zhuǎn)換是否成功/returns>
        public static bool ConvertPowerPointToPdf(string sourceFileName, string targetFileName)
        {
            Souxuexiao.API.Logger.info(string.Format("準(zhǔn)備執(zhí)行PowerPoint轉(zhuǎn)換PDF,sourceFileName={0},targetFileName={1}",sourceFileName,targetFileName));
            try
            {
                using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                {
                    Aspose.Slides.Pptx.PresentationEx pptx = new Aspose.Slides.Pptx.PresentationEx(stream);
                    pptx.Save(targetFileName, Aspose.Slides.Export.SaveFormat.Pdf);
                }
            }
            catch (Exception ex)
            {
                Souxuexiao.API.Logger.error(string.Format("將PowerPoint文件轉(zhuǎn)換為PDFConvertExcelToHtml異常原因是:{0}", ex.Message));
            }
            return System.IO.File.Exists(targetFileName);
        }
        #endregion

        #region 2.01 讀取pdf文件的總頁(yè)數(shù) +GetPageCount(string pdf_filename)
        /// summary>
        /// 讀取pdf文件的總頁(yè)數(shù)
        /// /summary>
        /// param name="pdf_filename">pdf文件/param>
        /// returns>/returns>
        public static int GetPageCountByPDF(string pdf_filename)
        {
            int pageCount = 0;
            if (System.IO.File.Exists(pdf_filename))
            {
                try
                {
                    byte[] buffer = System.IO.File.ReadAllBytes(pdf_filename);
                    if (buffer != null buffer.Length > 0)
                    {
                        pageCount = -1;
                        string pdfText = Encoding.Default.GetString(buffer);
                        Regex regex = new Regex(@"/Type\s*/Page[^s]");
                        MatchCollection conllection = regex.Matches(pdfText);
                        pageCount = conllection.Count;
                    }
                }
                catch (Exception ex)
                {
                    Souxuexiao.API.Logger.error(string.Format("讀取pdf文件的總頁(yè)數(shù)執(zhí)行GetPageCountByPowerPoint函數(shù)發(fā)生異常原因是:{0}", ex.Message));
                }
            }
            return pageCount;
        }
        #endregion

        #region 2.02 轉(zhuǎn)換PDF文件為SWF格式 +PDFConvertToSwf(string pdfPath, string swfPath, int page)
        /// summary>
        /// 轉(zhuǎn)換PDF文件為SWF格式
        /// /summary>
        /// param name="pdfPath">PDF文件路徑/param>
        /// param name="swfPath">SWF生成目標(biāo)文件路徑/param>
        /// param name="page">PDF頁(yè)數(shù)/param>
        /// returns>生成是否成功/returns>
        public static bool PDFConvertToSwf(string pdfPath, string swfPath, int page)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" \"" + pdfPath + "\"");
            sb.Append(" -o \"" + swfPath + "\"");
            sb.Append(" -z");
            //flash version
            sb.Append(" -s flashversion=9");
            //禁止PDF里面的鏈接
            sb.Append(" -s disablelinks");
            //PDF頁(yè)數(shù)
            sb.Append(" -p " + "\"1" + "-" + page + "\"");
            //SWF中的圖片質(zhì)量
            sb.Append(" -j 100");
            string command = sb.ToString();
            System.Diagnostics.Process p = null;
            try
            {
                using (p = new System.Diagnostics.Process())
                {
                    p.StartInfo.FileName = _EXEFILENAME;
                    p.StartInfo.Arguments = command;
                    p.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(_EXEFILENAME);
                    //不使用操作系統(tǒng)外殼程序 啟動(dòng) 線程
                    p.StartInfo.UseShellExecute = false;
                    //p.StartInfo.RedirectStandardInput = true;
                    //p.StartInfo.RedirectStandardOutput = true;

                    //把外部程序錯(cuò)誤輸出寫(xiě)到StandardError流中(pdf2swf.exe的所有輸出信息,都為錯(cuò)誤輸出流,用 StandardOutput是捕獲不到任何消息的...
                    p.StartInfo.RedirectStandardError = true;
                    //不創(chuàng)建進(jìn)程窗口
                    p.StartInfo.CreateNoWindow = false;
                    //啟動(dòng)進(jìn)程
                    p.Start();
                    //開(kāi)始異步讀取
                    p.BeginErrorReadLine();
                    //等待完成
                    p.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                Souxuexiao.API.Logger.error(string.Format("轉(zhuǎn)換PDF文件為SWF格式執(zhí)行PDFConvertToSwf函數(shù)發(fā)生異常原因是:{0}", ex.Message));
            }
            finally
            {
                if (p != null)
                {
                    //關(guān)閉進(jìn)程
                    p.Close();
                    //釋放資源
                    p.Dispose();
                }
            }
            return File.Exists(swfPath);
        }
        #endregion
    }
}
Office格式轉(zhuǎn)換

3、將pdf文件轉(zhuǎn)swf的轉(zhuǎn)換器放到站點(diǎn)根目錄下新建文件夾pdf2swf(我就是這么配置的,您隨意)

4、配置FlexPaper

預(yù)覽頁(yè)面引用

 

復(fù)制代碼 代碼如下:

 script src="/FlexPaper/js/swfobject.js" type="text/javascript">/script>
script type="text/javascript" src="/FlexPaper/js/flexpaper_flash.js">/script>
 

控件容器以及設(shè)置項(xiàng)

復(fù)制代碼 代碼如下:

div style="margin:0 auto;width:980px;">
            div id="flashContent" style="display:none;">
                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 >img src='" + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' />/a>");
                /script>
            /div>
        script type="text/javascript">
            var _filename = document.getElementById("_filename").value;
            var swfVersionStr = "9.0.0";
            var xiSwfUrlStr = "playerProductInstall.swf";
            var flashvars = {
                SwfFile: escape(_filename),
                Scale: 0.6,
                ZoomTransition: "easeOut",
                ZoomTime: 0.5,
                ZoomInterval: 0.1,
                FitPageOnLoad: false,
                FitWidthOnLoad: true,
                PrintEnabled: true,
                FullScreenAsMaxWindow: false,
                ProgressiveLoading: true,

                PrintToolsVisible: true,
                ViewModeToolsVisible: true,
                ZoomToolsVisible: true,
                FullScreenVisible: true,
                NavToolsVisible: true,
                CursorToolsVisible: true,
                SearchToolsVisible: true,
                SearchMatchAll:true,

                localeChain: "zh_CN"
            };
            var params = {
                quality: "high",
                bgcolor: "#ffffff",
                allowscriptaccess: "sameDomain",
                allowfullscreen: "true"
            }
            var attributes = { id: "FlexPaperViewer", name: "FlexPaperViewer" };
            swfobject.embedSWF("/FlexPaper/FlexPaperViewer.swf", "flashContent", "980", "620", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes);
            swfobject.createCSS("#flashContent", "display:block;text-align:left;");
        /script>
        /div>

document.getElementById("_filename").value是預(yù)覽文件的路徑
 
OK  大功告成  ,至于如何上傳,怎么保存上傳的文件等等那些邏輯我這里就省略了。。。。,但是有個(gè)建議,當(dāng)用戶(hù)上傳文件之后調(diào)用轉(zhuǎn)換api生成預(yù)覽文件是個(gè)耗時(shí)的操作,

文件越大耗時(shí)越長(zhǎng),也就是說(shuō)生成預(yù)覽文件的時(shí)候是需要時(shí)間的,因此我使用異步方式生成預(yù)覽文件。

您可能感興趣的文章:
  • 詳解高效而穩(wěn)定的企業(yè)級(jí).NET Office 組件Spire(.NET組件介紹之二)
  • asp.net中調(diào)用Office來(lái)制作3D統(tǒng)計(jì)圖的實(shí)例代碼
  • WinForm中如何預(yù)覽Office文件

標(biāo)簽:德陽(yáng) 張家界 白山 新疆 江蘇 蘭州 天門(mén) 陽(yáng)泉

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《.NET實(shí)現(xiàn)在網(wǎng)頁(yè)中預(yù)覽Office文件的3個(gè)方法》,本文關(guān)鍵詞  .NET,實(shí),現(xiàn)在,網(wǎng)頁(yè),中,預(yù)覽,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《.NET實(shí)現(xiàn)在網(wǎng)頁(yè)中預(yù)覽Office文件的3個(gè)方法》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于.NET實(shí)現(xiàn)在網(wǎng)頁(yè)中預(yù)覽Office文件的3個(gè)方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章