转自源地址: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. 智能车学习(十六)——CCD学习

    一.使用硬件 1.兰宙CCD四代      优点:可以调节运放来改变放大倍数      缺点:使用软排线(容易坏),CCD容易起灰,需要多次调节   2.野火K60底层     二.CCD硬件电路 ( ...

  2. 【hibernate 执行方法未插入数据库】hibernate的save方法成功执行,但是未插入到数据库

    今天做项目,碰上这个问题: hibernate的save方法成功执行,但是未插入到数据库. Dao层代码: @Override public void save(T t) { this.getSess ...

  3. loadrunner实现字符串的替换

        char *replace_str(char *str, char *orig, char *rep) {    static char buffer[9096];   char *p;  i ...

  4. MVVM模式下实现拖拽

    在文章开始之前先看一看效果图 我们可以拖拽一个"游戏"给ListBox,并且ListBox也能接受拖拽过来的数据, 但是我们不能拖拽一个"游戏类型"给它. 所以 ...

  5. (转)sscanf() - 从一个字符串中读进与指定格式相符的数据

    (转)sscanf() - 从一个字符串中读进与指定格式相符的数据 sscanf() - 从一个字符串中读进与指定格式相符的数据. 函数原型: Int sscanf( string str, stri ...

  6. 车销 商场 批发零售无线POS开单 智能POS开单打印 开单APP应用-云POS扫描打印一体方案

    PDA数据采集器,是一款移动手持开单设备,它通过WIFI和GPRS连接并访问电脑,从进销存软件中读取数据,实现移动开单,打破电脑开单模式. 它自带扫描器,可直接扫描条码来查找产品,且功能强大.操作简单 ...

  7. css -- 布局元素

    默认情况下拥有布局的元素:HTML ,table,tr,td,img,hr,input,select,textarea,button,iframe,embed,object,applet,marque ...

  8. js不间断平滑地自动向上滚动

    <html> <head> <title>scroll up auto smooth</title> <style> *{ margin: ...

  9. Fzu月赛11 老S的旅行计划 dij

    Description 老S在某城市生活的非常不自在,想趁着ICPC举办期间在省内转转.已知老S所在的省有N个城市,M条无向边(对于某一对结点可能出现重边).由于省内的交通相当糟糕,通过某条边所需要花 ...

  10. struts2总结一:MVC设计模式

    设计模式 一.什么是编程里面的设计模式? 1.设计模式是一套被反复使用,多数人知晓的,代码设计经验的总结. 2.模式必须是典型问题(不是个别问题)的解决方案. 二.设计模式的作用 1.解决一类问题的成 ...