.net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览
转自源地址: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. 编写相应的转换方法,AsposeUtil 中的方法可根据具体自己需要提取部分,可做相应修改调整后使用
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 = ;
if (System.IO.File.Exists(pdf_filename))
{
try
{
byte[] buffer = System.IO.File.ReadAllBytes(pdf_filename);
if (buffer != null && buffer.Length > )
{
pageCount = -;
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;
}
}
}
前台页面: js 相关文件可在此处下载
<%@ 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如果有问题,可再联系....
由于试用版限制只能转换5页文件,所以有可能的话就使用 aspose 破解版
.net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览的更多相关文章
- .net 实现Office文件预览 Word PPT Excel 2015-01-23 08:47 63人阅读 评论(0) 收藏
先打个广告: .Net交流群:252713569 本人QQ :524808775 欢迎技术探讨, 近期公司要求上传的PPT和Word都需要可以在线预览.. 小弟我是从来没有接触过这一块的东西 感觉很棘 ...
- Asp.net MVC 利用(aspose+pdfobject.js) 实现在线预览word、excel、ppt、pdf文件
在线预览word.excel.ppt利用aspose动态生成html 主要代码 private bool OfficeDocumentToHtml(string sourceDoc, string s ...
- 文档控件NTKO OFFICE 详细使用说明之预览word编辑保存回服务器
1.在线预览Word文件 (1) 运行环境 ① 浏览器:支持IE7-IE11(平台版本还支持Chrome和Firefox) ② IE工具栏-Internet 选项:将www.ntko.com加入到浏览 ...
- .NET读取Office文件内容(word、excel、ppt)
引用命名空间 using Microsoft.Office.Core; using Word = Microsoft.Office.Interop.Word; using Excel = Micros ...
- 【OfficeWebViewer】在线预览Word,Excel~
今天有个需求, 直接支持web端预览word,excel等文件, 查了一下很多写的比较麻烦, 这里找到一种简单的方式: http://view.officeapps.live.com/op/view. ...
- PowerDesigner逆向操作(从mysql5.0生成数据库的物理模型),把Comment写到name中,pdm文件导出为word
PowerDesigner逆向操作(从mysql5.0生成数据库的物理模型) 环境:powderdesigner12.5:mysql5.0步骤:1. 为指定的数据库配置mysql的ODBC数据源先下载 ...
- 在线预览Word,Excel
今天在项目中遇到了在线预览word的需求,经过查阅资料与测试发现可以解决问题,特做记录: 方式: http://view.officeapps.live.com/op/view.aspx?src= s ...
- IOS 预览word文档的集中方式
在iPhone中可以很方便的预览文档文件,如:pdf.word等等,这篇文章将以PDF为例.介绍三种预览PDF的方式,又分别从本地pdf文档和网络上的pdf文档进行对比. 预览本地PDF文档: 1.使 ...
- 在线文档转换API word,excel,ppt等在线文件转pdf、png
在线文档转换API提供word,excel,ppt等在线文件转pdf.png等,文档:https://www.juhe.cn/docs/api/id/259 接口地址:http://v.juhe.cn ...
随机推荐
- C语言基本点初探
1,对于int a=10++;此语句错误,为什么呢,对于i++来说,i是一个变量,是把i加1然后赋值给i,然而10不是一个变量所以无法执行加加的语法; 2,运算符的优先级: 赋值运算符<逻辑运算 ...
- Linux学习笔记(3)Linux常用命令之文件处理命令
Linux的命令格式一般为:命令 [-选项] [参数],如ls -la /etc,需要注意几点:1)个别命令使用不遵循此格式:2)当有多个选项时,可以写在一起:3)存在简化选项(-)与完整选项,如-a ...
- CentOS配置本地yum源(使用镜像iso文件)
本人在使用yum安装软件的时候,感觉最不爽的是网络不佳时,安装的速度特别慢.所以,个人就上网search了一下如何使用Linux的安装文件作为其yum源.经过几次尝试,已经可以成功的配置了.下面是详细 ...
- cf 二分图
题目链接:http://vjudge.net/contest/133033#problem/C 题目大意:给你n个点,m条边,将其分成两个集合,集合A是图的一个点覆盖,集合B也是图的一个点覆盖,要求集 ...
- POJ 2002 统计正方形 HASH
题目链接:http://poj.org/problem?id=2002 题意:给定n个点,问有多少种方法可以组成正方形. 思路:我们可以根据两个点求出对应正方形[有2个一个在两点左边,一个在两点右边] ...
- http://jingyan.baidu.com/article/2009576193ee38cb0721b416.html
http://jingyan.baidu.com/article/2009576193ee38cb0721b416.html
- Codeforces Round #349
终于又回到熟悉的Round了 数学 A - Pouring Rain 设个未知数,解方程,还好没有hack点 #include <bits/stdc++.h> typedef long l ...
- spring mvc 通过配置xml访问控制器的三种方式
(一)通过 name 来一一映射(默认) (二)通过简单url 来指定映射,key 表示访问url value 是bean的ID (三)通过控制类的类名控制器,访问时类名首字母需要小写 <!-- ...
- HDU5724 Chess(SG定理)
题目 Source http://acm.hdu.edu.cn/showproblem.php?pid=5724 Description Alice and Bob are playing a spe ...
- ccc 播放动画
cc.Class({ extends: cc.Component, properties: { anim:cc.Animation, }, // use this for initialization ...