先打个广告: .Net交流群:252713569
本人QQ :524808775 欢迎技术探讨,
近期公司要求上传的PPT和Word都需要可以在线预览..
小弟我是从来没有接触过这一块的东西 感觉很棘手..不过网络是强大的,还是让我找到了解决方案,记载一下.
要实现无任何插件的预览,swf文件是比较好的. PDF则需要有这个插件才能预览..那么转换的过程如下
以PPT 为例 : PPT →(由ASPOSE转换)→ PDF文件 →(由pdf2swf转换)→Swf文件 最终由EXTJS嵌入FlexPaper的形式展示
效果如下:
首先贴出后台处理文件的officeHelper代码(这里借鉴了别人的操作.)
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) { 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(@"/Types*/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进行展示,代码如下:
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; word-wrap: break-word; line-height: 18px; font-family: 'Courier New' !important;"><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;"><</span><span style="color: rgb(128, 0, 0); line-height: 1.5 !important;">script </span><span style="color: rgb(255, 0, 0); line-height: 1.5 !important;">src</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">="/FlexPaper/js/swfobject.js"</span><span style="color: rgb(255, 0, 0); line-height: 1.5 !important;"> type</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">="text/javascript"</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">></</span><span style="color: rgb(128, 0, 0); line-height: 1.5 !important;">script</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">></span> <span style="color: rgb(0, 0, 255); line-height: 1.5 !important;"><</span><span style="color: rgb(128, 0, 0); line-height: 1.5 !important;">script </span><span style="color: rgb(255, 0, 0); line-height: 1.5 !important;">type</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">="text/javascript"</span><span style="color: rgb(255, 0, 0); line-height: 1.5 !important;"> src</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">="/FlexPaper/js/flexpaper_flash.js"</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">></</span><span style="color: rgb(128, 0, 0); line-height: 1.5 !important;">script</span><span style="color: rgb(0, 0, 255); line-height: 1.5 !important;">></span>
</pre><pre name="code" class="html" style="background-color: rgb(255, 255, 255);"><span style="color:#333333;"><div style="margin:0 auto;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></span>
其中
document.getElementById("_filename").value是预览文件的路径,大家可以随意修改.
写在最后,这个转换的过程比较复杂,也比较耗时 测试7M左右的PPT需要1-2分钟转换,所以推荐在文件上传后第一次预览时进行异步转换,然后存在本地,第二次就直接拿上一次的进行显示.
版权声明:本文为博主原创文章,未经博主允许不得转载。