近日公司要搞一個平常的文檔管理的東東,能夠上傳、下載各類文件,若是是office文件呢還必須得支持預覽功能,其餘的都好說可是惟獨office預覽功能比較麻煩,可是不能不作,廢話很少說了一步步來吧。分析了下網易郵箱的文件預覽功能,他用的是微軟的組件,最先叫Office online,如今分開了叫Word online、Excel online ....等等,效果十分炫酷功能十分強大,可是查看了下對api的說明發現對服務器的要求比較苛刻並且配置比較複雜不太適合。而後 又看了下騰訊用的是永中第三方組件,效果嘛天然比不上微軟的可是能用,綜合網上的一些資料大概也就那麼幾種方式實現javascript
1.使用Microsoft的Office組件將文件直接轉換爲html文件(優勢:代碼實現最簡單,工做強度最小。缺點:效果極差)html
2.使用Microsoft的Office組件將文件轉換爲PDF格式文件,而後再使用pdf2swf轉換爲swf文件,也就是flash文件在使用FlexPaper展現出來(優勢:預覽效果能接受,缺點:代碼量大)java
效果如圖:api
3. 使用Office online(優勢:表現完美,缺點:不適合中小企業應用)服務器
綜合考慮決定使用第二種方法,通過次次波折終於可使用,可是有個問題至今沒有獲得解決,調用Office組件的時候有時候會出現以下異常:異步
檢索 COM 類工廠中 CLSID 爲 {000209FF-0000-0000-C000-000000000046} 的組件失敗,緣由是出現如下錯誤: 8000401a 由於配置標識不正確,系統沒法開始服務器進程。請檢查用戶名和密碼。 (異常來自 HRESULT:0x8000401A),查閱無數資料仍是不能解決,最讓人不可接受的的是office文件必須標標準準毫無容錯能力,當轉換ppt文件時居然會彈出轉換進度框!!ide
好吧!那麼咱們改進它。函數
使用ASPOSE+pdf2swf+FlexPaperflex
關於ASPOSE你們能夠到官網瞭解,這是款商業收費產品可是免費也可使用ui
一、引用dll
二、編寫轉換幫助類
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文件轉換 /// Writer:Helen Joe /// Date:2014-09-24 /// </summary> public class AsposeUtils { /// <summary> /// PFD轉換器位置 /// </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文檔轉換爲PDF文件 +ConvertDocToPdF(string sourceFileName, string targetFileName) /// <summary> /// Wrod文檔轉換爲PDF文件 /// </summary> /// <param name="sourceFileName">須要轉換的Word全路徑</param> /// <param name="targetFileName">目標文件全路徑</param> /// <returns>轉換是否成功</returns> public static bool ConvertDocToPdF(string sourceFileName, string targetFileName) { Souxuexiao.API.Logger.error(string.Format("Wrod文檔轉換爲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文檔轉換爲PDF文件執行ConvertDocToPdF發生異常緣由是:{0}",ex.Message)); } return System.IO.File.Exists(targetFileName); } #endregion #region 1.02 Excel文件轉換爲HTML文件 +(string sourceFileName, string targetFileName, string guid) /// <summary> /// Excel文件轉換爲HTML文件 /// </summary> /// <param name="sourceFileName">Excel文件路徑</param> /// <param name="targetFileName">目標路徑</param> /// <returns>轉換是否成功</returns> public static bool ConvertExcelToHtml(string sourceFileName, string targetFileName) { Souxuexiao.API.Logger.info(string.Format("準備執行Excel文件轉換爲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文件轉換爲HTML文件ConvertExcelToHtml異常緣由是:{0}", ex.Message)); } return System.IO.File.Exists(targetFileName); } #endregion #region 1.03 將PowerPoint文件轉換爲PDF +ConvertPowerPointToPdf(string sourceFileName, string targetFileName) /// <summary> /// 將PowerPoint文件轉換爲PDF /// </summary> /// <param name="sourceFileName">PPT/PPTX文件路徑</param> /// <param name="targetFileName">目標文件路徑</param> /// <returns>轉換是否成功</returns> public static bool ConvertPowerPointToPdf(string sourceFileName, string targetFileName) { Souxuexiao.API.Logger.info(string.Format("準備執行PowerPoint轉換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文件轉換爲PDFConvertExcelToHtml異常緣由是:{0}", ex.Message)); } return System.IO.File.Exists(targetFileName); } #endregion #region 2.01 讀取pdf文件的總頁數 +GetPageCount(string pdf_filename) /// <summary> /// 讀取pdf文件的總頁數 /// </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文件的總頁數執行GetPageCountByPowerPoint函數發生異常緣由是:{0}", ex.Message)); } } return pageCount; } #endregion #region 2.02 轉換PDF文件爲SWF格式 +PDFConvertToSwf(string pdfPath, string swfPath, int page) /// <summary> /// 轉換PDF文件爲SWF格式 /// </summary> /// <param name="pdfPath">PDF文件路徑</param> /// <param name="swfPath">SWF生成目標文件路徑</param> /// <param name="page">PDF頁數</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頁數 sb.Append(" -p " + "\"1" + "-" + page + "\""); //SWF中的圖片質量 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); //不使用操做系統外殼程序 啓動 線程 p.StartInfo.UseShellExecute = false; //p.StartInfo.RedirectStandardInput = true; //p.StartInfo.RedirectStandardOutput = true; //把外部程序錯誤輸出寫到StandardError流中(pdf2swf.exe的全部輸出信息,都爲錯誤輸出流,用 StandardOutput是捕獲不到任何消息的... p.StartInfo.RedirectStandardError = true; //不建立進程窗口 p.StartInfo.CreateNoWindow = false; //啓動進程 p.Start(); //開始異步讀取 p.BeginErrorReadLine(); //等待完成 p.WaitForExit(); } } catch (Exception ex) { Souxuexiao.API.Logger.error(string.Format("轉換PDF文件爲SWF格式執行PDFConvertToSwf函數發生異常緣由是:{0}", ex.Message)); } finally { if (p != null) { //關閉進程 p.Close(); //釋放資源 p.Dispose(); } } return File.Exists(swfPath); } #endregion } }
三、將pdf文件轉swf的轉換器放到站點根目錄下新建文件夾pdf2swf(我就是這麼配置的,您隨意)
四、配置FlexPaper
預覽頁面引用
<script src="/FlexPaper/js/swfobject.js" type="text/javascript"></script> <script type="text/javascript" src="/FlexPaper/js/flexpaper_flash.js"></script>
控件容器以及設置項
<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 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> <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是預覽文件的路徑
OK 大功告成 ,至於如何上傳,怎麼保存上傳的文件等等那些邏輯我這裏就省略了。。。。,可是有個建議,當用戶上傳文件以後調用轉換api生成預覽文件是個耗時的操做,
文件越大耗時越長,也就是說生成預覽文件的時候是須要時間的,所以我使用異步方式生成預覽文件。