.net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览
2015-09-17 11:31
811 查看
转自源地址: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. 编写相应的转换方法
另:项目使用,根据需要有一些的改动
这里还需要下载 swf 转换工具 swfTools 官网下载 安装,然后在安装目录找到 pdf2swf.exe,我是放在 项目的 bin 文件夹下面,其实可以自己放在任意的位置,只是使用的时候填好路径。
封装一个传参数的类:
转换的工具类:
(1). Word 转Pdf 的帮助类
(2). pdf转 swf 的帮助类
写了一个测试用的 ashx 一般处理程序
前台页面:
附:整个测试项目的文件结构
注:ppt转换PDF如果有问题,可再联系....
使用Microsoft的Office组件将文件转换为PDF格式文件,然后再使用pdf2swf转换为swf文件,也就是flash文件在使用FlexPaper展示出来(优点:预览效果能接受,缺点:代码量大)
使用ASPOSE+pdf2swf+FlexPaper
关于ASPOSE大家可以到官网了解,这是款商业收费产品但是免费也可以使用
1、引用dll
这一步的前提是需要去 官网下载 组件
下载之后,进行安装,然后在安装文件夹找到相应的 dll 库文件,然后引用到自己的项目中去
比如我要是想Word的在想浏览功能,那么我需要下载的组件是 Aspose.Word,然后安装,最后找到 dll 引用
2. 编写相应的转换方法
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 } }
另:项目使用,根据需要有一些的改动
这里还需要下载 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; } } }
前台页面:
<%@ 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如果有问题,可再联系....
相关文章推荐
- 任务计划
- 解释型语言和编译型语言
- Qt窗体之间相互传值的三种方式
- 怎么做战斗回放
- 一些经典的计算机书籍—基础篇
- 大众点评2015 在线笔试(1)
- MSPP
- Android-onInterceptTouchEvent()和onTouchEvent()总结---非常棒棒哒
- android添加wifi热点管理黑白名单
- springmvc导出excel并弹出下载框
- 十年北漂,一个软件“攻城狮”到职业养鸡人的心路历程
- SQL字符串操作汇总
- 大众点评2015 在线笔试(1)
- 矢量图和位图
- Spring中的ContextLoaderListener使用
- 完全不懂的哦,先记着吧。
- 将博客搬至CSDN
- Solr Multivalue field的索引和搜索
- hdu 4750 Count The Pairs(并查集+二分)
- jdbc操作数据库blob