.net 实现Office文件预览 Word PPT Excel 2015-01-23 08:47 63人阅读 评论(0) 收藏
先打个广告: .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(@"/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进行展示,代码如下:
<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;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></span>
其中
document.getElementById("_filename").value是预览文件的路径,大家可以随意修改.
写在最后,这个转换的过程比较复杂,也比较耗时 测试7M左右的PPT需要1-2分钟转换,所以推荐在文件上传后第一次预览时进行异步转换,然后存在本地,第二次就直接拿上一次的进行显示.
版权声明:本文为博主原创文章,未经博主允许不得转载。
.net 实现Office文件预览 Word PPT Excel 2015-01-23 08:47 63人阅读 评论(0) 收藏的更多相关文章
- 利用ssh传输文件 分类: 服务器搭建 Raspberry Pi 2015-04-12 18:47 58人阅读 评论(0) 收藏
在linux下一般用scp这个命令来通过ssh传输文件. 1.从服务器上下载文件 scp username@servername:/path/filename /var/www/local_dir(本 ...
- Android中的数据存储(二):文件存储 2017-05-25 08:16 35人阅读 评论(0) 收藏
文件存储 这是本人(菜鸟)学习android数据存储时接触的有关文件存储的知识以及本人自己写的简单地demo,为初学者学习和使用文件存储提供一些帮助.. 如果有需要查看SharedPreference ...
- 随机带权选取文件中一行 分类: linux c/c++ 2014-06-02 00:11 344人阅读 评论(0) 收藏
本程序实现从文件中随即选取一行,每行被选中的概率与改行长度成正比. 程序用一次遍历,实现带权随机选取. 算法:假设第i行权重wi(i=1...n).读取到文件第i行时,以概率wi/(w1+w2+... ...
- .net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览
转自源地址:http://www.cnblogs.com/GodIsBoy/p/4009252.html,有部分改动 使用Microsoft的Office组件将文件转换为PDF格式文件,然后再使用pd ...
- 在word中使用notepad++实现代码的语法高亮 分类: C_OHTERS 2013-09-22 10:38 2273人阅读 评论(0) 收藏
转载自:http://blog.csdn.net/woohello/article/details/7621651 有时写文档时需要将代码粘贴到word中,但直接粘贴到word中的代码虽能保持换行与缩 ...
- Javascript图片预加载详解 分类: JavaScript HTML+CSS 2015-05-29 11:01 768人阅读 评论(0) 收藏
预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布 ...
- visual studio2010复制粘贴源代码到Word时乱码问题 分类: C# 2014-11-28 09:25 687人阅读 评论(0) 收藏
问题描述: visual studio2010 拷贝源代码的时候,在windows自带的写字板和word2010上,粘贴的时候中文字符都会变成乱码. 如: "该用户已经被成功添加" ...
- TinyXML2读取和创建XML文件 分类: C/C++ 2015-03-14 13:29 94人阅读 评论(0) 收藏
TinyXML2是simple.small.efficient C++ XML文件解析库!方便易于使用,是对TinyXML的升级改写!源码见本人上传到CSDN的TinyXML2.rar资源:http: ...
- ubuntu常用文件搜索命令 分类: linux 学习笔记 ubuntu 2015-07-05 15:40 84人阅读 评论(0) 收藏
1.find find [搜索路径] [搜索关键字] 比如查找/test中文件名为t5.tmp的文件: 查找根目录下大于100M的文件 注意,这里的204800单位是块,1块=512字节 在根目录下查 ...
随机推荐
- 推荐几个Android自定义的进度条(转载)
CustomLoading ElasticDownload Circle-Progress-View lzyzsdCircleProgress SquareProgressBar materialis ...
- AJAX学习随笔
AJAX名为“啊,贾克斯”,听着挺怪的哈. 主要的技术就是XMLHttpRequest对象和Javascript 度娘的解答: AJAX即“AsynchronousJavascriptAndXML”( ...
- Android Support Library
title: Android Support Library tags: Support Library,支持库 grammar_cjkRuby: true --- DATE: 2016-5-13. ...
- iOS开发系列—Objective-C之基础概览
概览 前面我们已经用了几章内容进行C语言介绍,当然要通过几篇文章完整的介绍C语言的知识是不太现实的,例如C语言的文件操作.内存申请等我们都没有重点介绍,当然核心知识点基本都已经提到了,后面有时间我们会 ...
- AutoMapper 最佳实践
AutoMapper 是一个基于命名约定的对象->对象映射工具. 只要2个对象的属性具有相同名字(或者符合它规定的命名约定),AutoMapper就可以替我们自动在2个对象间进行属性值的映射.如 ...
- 招聘.NET开发人员(截止于2015-06-15)
文章更新 2015-06-15 01:00AM: 感谢各位的支持,简历和解决方案接收截止.2015-06-08 08:30AM: 已经收到一些简历和解决方案,正在筛选中.职位仍然开放,欢迎发送简历及解 ...
- 为什么可以说Java语言是准动态语言?
什么是动态语言? 动态语言,是指程序在运行时可以改变其结构:新的函数可以被引进,已有的函数可以被删除等在结构上的变化.比如JavaScript便是一个典型的动态语言. 除此之外如Ruby.Python ...
- JS数组定义及详解
1.什么是数组 数组就是一组数据的集合 其表现形式就是内存中的一段连续的内存地址 数组名称其实就是连续内存地址的首地址 2.关于js中的数组特点 数组定义时无需指定数据类型 数组定义时可以无需指定数组 ...
- .Net中List<T> 泛型转成DataTable、DataSet
在开发过程过程中有时候需要将List<T>泛型转换成DataTable.DataSet,可以利用反射机制将DataTable的字段与自定义类型的公开属性互相赋值. 1.List<T& ...
- [转] Android优秀开源项目
Android经典的开源项目其实非常多,但是国内的博客总是拿着N年前的一篇复制来复制去,实在是不利于新手学习.今天爬爬把自己熟悉的一些开源项目整理起来,希望能对Android开发同学们有所帮助.另外, ...