转自源地址: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文件在线预览的更多相关文章

  1. .net 实现Office文件预览 Word PPT Excel 2015-01-23 08:47 63人阅读 评论(0) 收藏

    先打个广告: .Net交流群:252713569 本人QQ :524808775 欢迎技术探讨, 近期公司要求上传的PPT和Word都需要可以在线预览.. 小弟我是从来没有接触过这一块的东西 感觉很棘 ...

  2. Asp.net MVC 利用(aspose+pdfobject.js) 实现在线预览word、excel、ppt、pdf文件

    在线预览word.excel.ppt利用aspose动态生成html 主要代码 private bool OfficeDocumentToHtml(string sourceDoc, string s ...

  3. 文档控件NTKO OFFICE 详细使用说明之预览word编辑保存回服务器

    1.在线预览Word文件 (1) 运行环境 ① 浏览器:支持IE7-IE11(平台版本还支持Chrome和Firefox) ② IE工具栏-Internet 选项:将www.ntko.com加入到浏览 ...

  4. .NET读取Office文件内容(word、excel、ppt)

    引用命名空间 using Microsoft.Office.Core; using Word = Microsoft.Office.Interop.Word; using Excel = Micros ...

  5. 【OfficeWebViewer】在线预览Word,Excel~

    今天有个需求, 直接支持web端预览word,excel等文件, 查了一下很多写的比较麻烦, 这里找到一种简单的方式: http://view.officeapps.live.com/op/view. ...

  6. PowerDesigner逆向操作(从mysql5.0生成数据库的物理模型),把Comment写到name中,pdm文件导出为word

    PowerDesigner逆向操作(从mysql5.0生成数据库的物理模型) 环境:powderdesigner12.5:mysql5.0步骤:1. 为指定的数据库配置mysql的ODBC数据源先下载 ...

  7. 在线预览Word,Excel

    今天在项目中遇到了在线预览word的需求,经过查阅资料与测试发现可以解决问题,特做记录: 方式: http://view.officeapps.live.com/op/view.aspx?src= s ...

  8. IOS 预览word文档的集中方式

    在iPhone中可以很方便的预览文档文件,如:pdf.word等等,这篇文章将以PDF为例.介绍三种预览PDF的方式,又分别从本地pdf文档和网络上的pdf文档进行对比. 预览本地PDF文档: 1.使 ...

  9. 在线文档转换API word,excel,ppt等在线文件转pdf、png

    在线文档转换API提供word,excel,ppt等在线文件转pdf.png等,文档:https://www.juhe.cn/docs/api/id/259 接口地址:http://v.juhe.cn ...

随机推荐

  1. SQL详解(上)

    SQL 什么是SQL:结构化查询语言(Structured Query Language).SQL标准(例如SQL99,即1999年制定的标准): 由国际标准化组织(ISO)制定的,对DBMS的统一操 ...

  2. vim 清空

    插入模式 首先执行gg 跳至文件首行 然后执行dG就清空了整个文件 还有一种方法就要退出VIM,然后使用echo > file ,这样也能快速清空文件内容

  3. SpringMyBatis解析4-MapperScannerConfigurer

    如果有成百上千个dao接口呢,那我们岂不是要配置添加成百上千个bean,当然不是这样,spring还为MyBatis添加了拓展的功能,可以通过扫描包目录的方式,添加dao,让我看看具体使用和实现. & ...

  4. SU Demo之01MakingData--02MultiShot

  5. 豆制品厂开车超市送货智能手持PDA POS打票机-手持票据打印机

    豆制品厂开车拉着豆腐到某一个超市送货,到达后秤出斤数后就用票据打印机开单 能直接开单,单子一式两份,一张给客户一张留底,到月底时客户要根据客户的量返点的,单子统计.能现场开单,单子上显示哪个超市,豆制 ...

  6. Gym 100814C Connecting Graph 并查集+LCA

    Description standard input/output Statements Alex is known to be very clever, but Walter does not be ...

  7. 【主席树】【bzoj2161】[hdu4348]

    #include<cstdio> #include<algorithm> #include<cstring> #define N 400000 using name ...

  8. iOS实现简书的账号识别方式(正则表达式)

    通过简书iOS客户端登录,我们会看到请输入手机号或者邮箱登录,但是我们随机输入1234567的时候,便会弹出手机格式不正确,同样也会识别我们的邮箱格式,那么我们在项目中怎么实现这种判断呢? 0E471 ...

  9. jenkins+ant+jmeter搭建持续集成的接口测试平台

    一.jemter接口脚本的编写步骤如下: 1. 编写接口请求 通过录制或者查看接口文档,编写接口请求,进行调试,确保接口调试通过,对于http的请求来说,就是正确的填写域名,查询字符串,查询参数等信息 ...

  10. XML Basic

    XML声明: <?xml version="1.0" encoding="UTF-8"?> XML中属性的value值要被引号(单引号or双引号)引 ...