C#在线预览文档(word,excel,pdf,txt,png)

1、预览方式:将word文件转换成html文件然后预览html文件
2、预览word文件:需要引入Interop.Microsoft.Office.Interop.Word.dll(Com组件)
3、预览Excel文件:需要引入Interop.Microsoft.Office.Interop.Excel.dll(Com组件,Microsoft Excel 12.0(or other version) Object Library)
4、PDF文件直接嵌入到浏览器中进行查看,无需转换(需安装pdf阅读器)
5、文本文件直接嵌入到浏览器进行查看,无需转换

6、图片文件直接嵌入到浏览器进行查看,无需转换

Excel预览方法
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web; /// <summary>
/// Summary description for ExcelPreview
/// </summary>
public class ExcelPreview
{
public static void Priview(System.Web.UI.Page p, string inFilePath, string outDirPath = "")
{
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Workbook xls = null;
excel = new Microsoft.Office.Interop.Excel.Application();
object missing = Type.Missing;
object trueObject = true;
excel.Visible = false;
excel.DisplayAlerts = false; string randomName = DateTime.Now.Ticks.ToString(); //output fileName xls = excel.Workbooks.Open(inFilePath, missing, trueObject, missing,
missing, missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing); //Save Excel to Html
object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
Workbook wsCurrent = xls;//(Workbook)wsEnumerator.Current;
String outputFile = outDirPath + randomName + ".html";
wsCurrent.SaveAs(outputFile, format, missing, missing, missing,
missing, XlSaveAsAccessMode.xlNoChange, missing,
missing, missing, missing, missing);
excel.Quit(); //Open generated Html
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputFile;
process.Start();
} }

Pdf类

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web; /// <summary>
/// Summary description for WordPreview
/// </summary>
public class PDFPreview
{
public static void Priview(System.Web.UI.Page p, string inFilePath)
{
p.Response.ContentType = "Application/pdf"; string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + );
p.Response.AddHeader("content-disposition", "filename=" + fileName);
p.Response.WriteFile(inFilePath);
p.Response.End();
}
}
Word预览方法

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web; /// <summary>
/// Summary description for WordPreview
/// </summary>
public class WordPreview
{
public static void Priview(System.Web.UI.Page p, string inFilePath, string outDirPath = "")
{
object missingType = Type.Missing;
object readOnly = true;
object isVisible = false;
object documentFormat = ;
string randomName = DateTime.Now.Ticks.ToString();
object htmlFilePath = outDirPath + randomName + ".htm";
string directoryPath = outDirPath + randomName + ".files"; object filePath = inFilePath;
//Open the word document in background
ApplicationClass applicationclass = new ApplicationClass();
applicationclass.Documents.Open(ref filePath,
ref readOnly,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref isVisible,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType);
applicationclass.Visible = false;
Document document = applicationclass.ActiveDocument; //Save the word document as HTML file
document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType); //Close the word document
document.Close(ref missingType, ref missingType, ref missingType); #region Read the Html File as Byte Array and Display it on browser
//byte[] bytes;
//using (FileStream fs = new FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read))
//{
// BinaryReader reader = new BinaryReader(fs);
// bytes = reader.ReadBytes((int)fs.Length);
// fs.Close();
//}
//p.Response.BinaryWrite(bytes);
//p.Response.Flush();
//p.Response.End();
#endregion Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = htmlFilePath.ToString();
process.Start(); #region Delete the Html File and Diretory 删除生成的文件
//File.Delete(htmlFilePath.ToString());
//foreach (string file in Directory.GetFiles(directoryPath))
//{
// File.Delete(file);
//}
//Directory.Delete(directoryPath);
#endregion
}
}
文本预览方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web; /// <summary>
/// Summary description for TextFilePreview
/// </summary>
public class TextFilePreview
{
public static void Preview(System.Web.UI.Page p, string inFilePath)
{
string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + ); p.Response.ContentType = "text/plain";
p.Response.ContentEncoding = System.Text.Encoding.UTF8; //保持和文件的编码格式一致
p.Response.AddHeader("content-disposition", "filename=" + fileName);
p.Response.WriteFile(inFilePath);
p.Response.End();
}
}
图片预览方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web; /// <summary>
/// Summary description for TextFilePreview
/// </summary>
public class TextFilePreview
{
public static void Preview(System.Web.UI.Page p, string inFilePath)
{
string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + ); p.Response.ContentType = "images/*";
p.Response.ContentEncoding = System.Text.Encoding.UTF8;
p.Response.AddHeader("content-disposition", "filename=" + fileName);
p.Response.WriteFile(inFilePath);
p.Response.End();
}
}

以上的pdf,txt,图片这个三种方式在MVC下不可用,在aspx界面可用。研究后进行了更改

以上是转成html进行预览,预览效果不是太好。以下是转成pdf预览代码

 新建windows应用程序项目

 添加以下com组件的引用

 Microsoft Word 12.0 Object Library

 Microsoft PowerPoint 12.0 Object Library

 Microsoft Excel 12.0 Object Library

 ------------------------------------------------------

 using Word = Microsoft.Office.Interop.Word; using Excel = Microsoft.Office.Interop.Excel; using PowerPoint = Microsoft.Office.Interop.PowerPoint;

 using Microsoft.Office.Core;

 我们可以使用一个枚举类型来决定生成文件的类型

 Word.WdExportFormat wd = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;

 Excel.XlFixedFormatType excelType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF; PowerPoint.PpSaveAsFileType ppType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;

   //将word文档转换成PDF格式
private bool Convert(string sourcePath, string targetPath, Word.WdExportFormat exportFormat)
{
bool result;
object paramMissing = Type.Missing;
Word.ApplicationClass wordApplication = new Word.ApplicationClass();
Word.Document wordDocument = null;
try
{
object paramSourceDocPath = sourcePath;
string paramExportFilePath = targetPath; Word.WdExportFormat paramExportFormat = exportFormat;
bool paramOpenAfterExport = false;
Word.WdExportOptimizeFor paramExportOptimizeFor =
Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
int paramStartPage = ;
int paramEndPage = ;
Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
bool paramIncludeDocProps = true;
bool paramKeepIRM = true;
Word.WdExportCreateBookmarks paramCreateBookmarks =
Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
bool paramDocStructureTags = true;
bool paramBitmapMissingFonts = true;
bool paramUseISO19005_1 = false; wordDocument = wordApplication.Documents.Open(
ref paramSourceDocPath, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing); if (wordDocument != null)
wordDocument.ExportAsFixedFormat(paramExportFilePath,
paramExportFormat, paramOpenAfterExport,
paramExportOptimizeFor, paramExportRange, paramStartPage,
paramEndPage, paramExportItem, paramIncludeDocProps,
paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
paramBitmapMissingFonts, paramUseISO19005_1,
ref paramMissing);
result = true;
}
finally
{
if (wordDocument != null)
{
wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
wordDocument = null;
}
if (wordApplication != null)
{
wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
wordApplication = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
} //将excel文档转换成PDF格式
private bool Convert(string sourcePath, string targetPath, XlFixedFormatType targetType)
{
bool result;
object missing = Type.Missing;
Excel.ApplicationClass application = null;
Workbook workBook = null;
try
{
application = new Excel.ApplicationClass();
object target = targetPath;
object type = targetType;
workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing); workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
result = true;
}
catch
{
result = false;
}
finally
{
if (workBook != null)
{
workBook.Close(true, missing, missing);
workBook = null;
}
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
} //将ppt文档转换成PDF格式
private bool Convert(string sourcePath, string targetPath, PpSaveAsFileType targetFileType)
{
bool result;
object missing = Type.Missing;
PowerPoint.ApplicationClass application = null;
Presentation persentation = null;
try
{
application = new PowerPoint.ApplicationClass();
persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue); result = true;
}
catch
{
result = false;
}
finally
{
if (persentation != null)
{
persentation.Close();
persentation = null;
}
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
}

cshtml代码:

$.get("/Home/Index",{url:a,rnd:new Date()},function(data)

{
if(data.status=)
{
Window.Open(data.url);//在新窗口中打开预览文档
}
});

Controller的方法

 Public JsonResult PreView()
{
string url=Request["url"];//url 格式"/doc/123456.pdf"
string html=Url.Content(url);
return Json(new {status=,url=html},JsonRequestBehavior.AllowGet); }

转载请注明出处。此方法预览PDf需要机器上安装pdf阅读器。有好方法可以交流学习。

C#在线预览文档(word,excel,pdf,txt,png)的更多相关文章

  1. C# 基于NPOI+Office COM组件 实现20行代码在线预览文档(word,excel,pdf,txt,png)

    由于项目需要,需要一个在线预览office的功能,小编一开始使用的是微软提供的方法,简单快捷,但是不符合小编开发需求, 就另外用了:将文件转换成html文件然后预览html文件的方法.对微软提供的方法 ...

  2. 在线预览文档(支持word、excel、ppt、pdf)+在线预览文档html版(转)

    1.首先上网搜索一下有什么解决方案 (1).将文档转换为html,只支持支持office文档 (2).将文档转换为flash,实现类似百度文库的效果,除支持office文档外还支持pdf (1) a. ...

  3. [SWF]在线预览文档下载

    写本文的缘由:领导有些项目文档需要审阅,网站上的文档只能在线预览,没有提供下载.开始用截屏的方式,可想而知这将会是多大的重复性劳动.所以研究了一下,发现可以曲线救国,所以在这里分享一下. 问题描述:这 ...

  4. Java 如何实现在线预览文档及修改(Office文件)

    测试地址: https://sms.idxkj.cn 用户名:aa 密码:123456

  5. Java 如何实现在线预览文档及修改(文本文件)

    暂时未解决的问题:多用户并发修改一个文件 测试地址: http://sms.reyo.cn 用户名:aa 密码:123456

  6. 在其他app里预览文档

    本文转载至 http://www.cocoachina.com/newbie/basic/2013/0515/6212.html iOS中的沙盒可以让平台更加的安全,这也是沙盒给用户带来的最主要好处. ...

  7. 文件在线预览doc,docx转换pdf(一)

    文件在线预览doc,docx转换pdf(一) 1. 前言 文档转换是一个是一块硬骨头,但是也是必不可少的,我们正好做的知识库产品中,也面临着同样的问题,文档转换,精准的全文搜索,知识的转换率,是知识库 ...

  8. java实现在线预览--poi实现word、excel、ppt转html

    java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...

  9. 实战动态PDF在线预览及带签名的PDF文件转换

    开篇语: 最近工作需要做一个借款合同,公司以前的合同都是通过app端下载,然后通过本地打开pdf文件,而喜欢创新的我,心想着为什么不能在线H5预览,正是这个想法,说干就干,实践过程总是艰难的,折腾了3 ...

随机推荐

  1. neutron 虚拟机网络问题调试

    1. Security Group全部打开,这是最基本的,但是很多人容易忘记 2. 通过界面查看虚拟机的log,也可以在compute节点上查看console.log文件,看看里面是否有DHCP获取I ...

  2. js代理模式

    代理模式的关键是,当客户不方便直接访问一个对象或者不满足需要的时候,提供一个替身对象来控制对这个对象的访问,客户实际上访问的是替身对象.替身对象对请求做出一些处理之后,再把请求转交给本体对象. 代理模 ...

  3. dp2--合并石子(一)

    dp2--合并石子(一) 一.心得 二.题目 石子合并(一) 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述     有N堆石子排成一排,每堆石子有一定的数量.现要将 ...

  4. 解决mssql for linux 中文乱码问题

    什么叫一波未平一波又起,这就是,好不容易安装完成了,在用的时候居然出现了乱码,很是头疼,但还是解决了这个蛋疼的问题,在windows中使用mssql这么久,从来没出现过中文乱码的情况,具体原因是出现在 ...

  5. nodeJs爬虫小程序练习

    //爬虫小程序 var express = require('express'); //superagent是一个http的库,可以发起get和post请求 var superagent = requ ...

  6. python字典方法

    本文参考自<python基础教程 (第二版)> 操作 语法 举例 结果 建立字典 dict() 1.以关键字参数建立字典 2.以其他映射作为参数建立字典 1.d = dict(name=' ...

  7. 在OSX上安装python3使用pip安装Flask

    官方的pypi.python.org可能访问不了,可以先将pip配置为豆瓣的pypi镜像 $ mkdir ~/.pip $ vim ~/.pip/pip.conf [global] timeout = ...

  8. 分布式_理论_08_Consistent Hash(一致性哈希算法)

    一.前言 五.参考资料 1.分布式理论(八)—— Consistent Hash(一致性哈希算法)

  9. SpringCloud教程 | 第五篇: 路由网关(zuul)

    在微服务架构中,需要几个基础的服务治理组件,包括服务注册与发现.服务消费.负载均衡.断路器.智能路由.配置管理等,由这几个基础组件相互协作,共同组建了一个简单的微服务系统.一个简答的微服务系统如下图: ...

  10. 数据处理之pandas库

    1. Series对象 由于series对象很简单,跟数组类似,但多了一些额外的功能,偷个懒,用思维导图表示 2. DaraFrame对象 DataFrame将Series的使用场景由一维扩展到多维, ...