文件在线预览方案
- 格式:docx
- 大小:16.18 KB
- 文档页数:1


C#在线预览⽂档(word,excel,pdf,txt,png) 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 fileNamexls = excel.Workbooks.Open(inFilePath, missing, trueObject, missing,missing, missing, missing, missing, missing, missing, missing, missing,missing, missing, missing);//Save Excel to Htmlobject 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 HtmlProcess process = new Process();eShellExecute = 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(stIndexOf('\\') + 1);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 = 8;string randomName = DateTime.Now.Ticks.ToString();object htmlFilePath = outDirPath + randomName + ".htm";string directoryPath = outDirPath + randomName + ".files";object filePath = inFilePath;//Open the word document in backgroundApplicationClass 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 filedocument.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 documentdocument.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();#endregionProcess process = new Process();eShellExecute = 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(stIndexOf('\\') + 1);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(stIndexOf('\\') + 1);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界⾯可⽤。
php在线预览word⼀般类似oa或者crm等管理系统可能都会遇到需要再线查看word⽂档的功能,类似百度⽂库。
记得去年⼩组中的⼀个成员负责的项⽬就需要这个的功能,后⾯说是实现⽐较困难,就将就着⽤chm格式替代了。
今天看到⽹上⼀遍⽂章《LINUX下⾯PHP⽂件转换》,介绍怎么样在linux下使⽤Openoffice 3 , Pdf2Swf tool , Jodconverter , FlexPaper,实现⽂档在线查看。
⾃⼰再ubuntu下进⾏的尝试安装,步骤如下:因为ubuntu版本为10.0.4,openoffice已经默认安装。
如果没有安装openoffice的话⾃⾏⾕歌安装。
第⼀步:安装jodconverter,安装之后可以实现doc⽂档转成pdf。
1. java -jar /opt/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar /home/php/1.doc /home/php/1.pdf这⾥提⽰缺少java软件包,并会提⽰⼏个安装包供。
选择我安装openjdk-6-jre-headless,命令如下:1. sudo apt_get openjdk-6-jre-headless安装之后再运⾏上⾯doc转pdf的命名,会提⽰openoffice进程未启动,因为JODConverter是通过OpenOffice來做转换的,所以使⽤前需要先安裝OpenOffice, 並且將OpenOffice的Service启动, 才可以使⽤. 启动命令1. /usr/lib/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &到此运⾏上⾯的doc转pdf的命令已经可以成功。
第⼆步:安装swftools,安装之后可以实现pdf⽂件转成swf1. wget /swftools-0.9.1.tar.gz2. tar xzf swftools-0.9.1.tar.gz3. cd swftools-0.9.14. ./configure5. make6. make install测试是否可以使⽤1. pdf2swf -o /home/php/1.swf -T -z -t -f /home/php/1.pdf -s flashversion=9第三步:⽤FlexPaper实现在线预览,⾥⾯有详细的demo。
知识库中文档在线预览功能的实现1 文档预览方案知识库中文档以附件的形式上传后,以 flash 的形式在网页上展示。
文档需要先转化为 pdf ,再从 pdf 转化为 flash 。
本文采用 JODConverter 和 OpenOffice 将 Txt、Word Excel、PPT格式的文件转换为 PDF文件,再通过 SWFTools中的PDF2SW工具将PDF 文件转换为SWF文件,最终在页面显示,实现在线预览功能。
OpenOffice 是一套跨平台的办公室软件套件,能在 Windows、Linux 等操作系统上执行。
它与各个主要的办公室软件套件兼容,支持XML微软的 Word Excel、PPT文件等格式。
为了把文档转换PDF格式,需将 变成一个转换引擎,可以通过网络接口或命令行工具对文件的格式进行转换。
JODConverter 能够将 Word Excel、PPT转换 PDF SWFTools是种与Adobe Flash ( SWF文件工作的实用工具包,主要包括用于读取、编译以及生成 SWF文件的程序。
其中,P DF2SW工具可以将PDF文件转换成SWF文件。
Flex Player是一款高性能的、轻量型且极具表现力的客户端运行时播放器,能够在各种主流操作系统、浏览器上使用,使得在没有安装PDF阅读器软件的情况下浏览PDF文件成为可能。
本文采用 Java语言对其进行编程实现,具有与 Java 语言相同的跨平台性,可在不同的操作系统上运行。
2 实现步骤2.1 用 JODConverter 调用 服务转换文档为PDF格式首先,启动 OpenOffice 服务。
设定DefaultOfficeManagerConfiguration 相关参数,并得到OfficeManager 。
调用 OfficeManager 实现类的 start 方法启动服务。
主要代码如下:DefaultOfficeManagerConfigurationconfiguration =newDefaultOfficeManagerConfiguration);configuration.setOfficeHome (OPENOFFICE_HO)M;E // OP ENOFFICE_HO 为EO penO 安装目录configuration.setPortNumbers (port ); // 实例运行的端口号,默认为 8100officeManager =configuration.buildOfficeManager);officeManager.start (); // 启动服务其次,将 doc、 ppt 、 excele 、txt 转化为 pdf 文档。
使⽤pdf.js在线预览PDF(本地⽂件,服务器⽂件)前⾔不使⽤插件直接进⾏pdf预览时,对于⼩⽂件没有任何问题,但在预览⼀个305M,近400页的pdf⽂件时,打开pdf直接拉到最后⼏页,会造成浏览器崩溃,于是尝试使⽤pdf.js的插件⽅式进⾏pdf预览,解决⼤⽂件浏览器崩溃的问题。
1、下载地址主要⽤到⾥边的 viewer.js 和 viewer.html ⽂件2、打开⽂件夹,把这两个⽂件放进程序,⼀个是 build,⼀个是 web ⽂件夹,建议整个⽂件夹都放进去!到这差不多安装过程就 ok了,viewer.html ⽂件⾥边有默认的 PDF ⽂件测试⽅法window.open(' ../pdf/web/viewer.html')3、找到刚刚放⼊程序的⽂件,打开 web ⽂件⽬录,打开 viewer.js ⽂件找到他默认展⽰的 PDF ⽂件的路径改为 value:’’ ( 也可以不修改 )4、想要调⽤这个 JS 来预览 PDF ,⽅法跟上⽅测试⽅法差不多,只不过多加了⼀个条件 调⽤⽅法:windows.open("/pdf/web/viewer.html?file=file.pdf"); 这个⽅法只能读取你 web ⽬录下的⽂件,如果想要读取你本地⽂件或者服务器⽂件就通过流的⽅式输出5、获取本地/服务器⽂件前端写法:通过点击事件触发预览previewURL: 项⽬地址路径filePath: 要打开的项⽬encodeURIComponent:⽤于 url 特殊字符的转译(⽐如: ; / ? : @ & = + $ , # 这些⽤于分隔 URI 组件的标点符号)// 点击调⽤预览⽅法function xx(filePath){var previewURL= "127.0.0.1:8080/";window.open('../pdf/web/viewer.html?file='+encodeURIComponent(previewURL+"/test?url="+filePath));}后端写法:拿到⽂件地址,通过流的⽅式输出到移动端页⾯显⽰// 通过⽂件流的⽅式预览 PDF ⽂件@RequestMapping(value = "test")public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response, HttpSession session) {// 获取路径String filePath = request.getParameter("url");File file = new File(filePath);byte[] data = null;try {// 编辑请求头部信息// 解决请求头跨域问题(IE兼容性也可使⽤该⽅法)response.setHeader("Access-Control-Allow-Origin", "*");response.setContentType("application/pdf");FileInputStream input = new FileInputStream(file);data = new byte[input.available()];input.read(data);response.getOutputStream().write(data);input.close();} catch (Exception e) {}}下⾯是我的项⽬中的调⽤⽅式:/*** 预览PDF*/@RequiresPermissions("dagl:pdf")@Log(title = "PDF预览", businessType = BusinessType.DELETE)@GetMapping("/pdfPreview/{dh}")public String pdfPreview(@PathVariable("dh") String dh, ModelMap mmap){mmap.put("pdf_url", fileReadUrl+dazlxxb.getPdfUrl());return prefix + "/pdfPreview";}<!DOCTYPE html><html style="height: 100%" lang="zh" xmlns:th="" ><head><link th:href="@{/css/update.css}" rel="stylesheet"/><th:block th:include="include :: header('PDF预览')"/><th:block th:include="include :: datetimepicker-css"/></head><body class="white-bg"><iframe style="width: 100%;height: 100%;" frameborder="0" id="pdfView"></iframe></body><script th:src="@{/js/jquery.min.js}"></script><script th:inline="javascript">var pdf_url = [[${pdf_url}]];var prefix = "/dagl";$('#pdfView').attr('src', '/pdf/web/viewer.html?file=' + encodeURIComponent(prefix +"/pdfStreamHandeler?pdf_url=" + pdf_url)); </script></html>// 通过⽂件流的⽅式预览 PDF ⽂件@RequestMapping(value = "pdfStreamHandeler")public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response, HttpSession session) {// 获取路径String filePath = request.getParameter("pdf_url");try {if(StringUtils.isNotBlank(filePath)) {byte[] data = fileDfsUtil.downLoadFile(filePath);// 编辑请求头部信息// 解决请求头跨域问题(IE兼容性也可使⽤该⽅法)response.setHeader("Access-Control-Allow-Origin", "*");response.setContentType("application/pdf");response.getOutputStream().write(data);}} catch (Exception e) {e.printStackTrace();}}@Componentpublic class FileDfsUtil {private static final Logger LOGGER = LoggerFactory.getLogger(FileDfsUtil.class);@Resourceprivate FastFileStorageClient storageClient ;/*** 上传⽂件*/public String upload(MultipartFile multipartFile,String fileName) throws Exception{StorePath storePath = storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(),FilenameUtils.getExtension(fileName), null);return storePath.getFullPath() ;}/*** 删除⽂件*/public String deleteFile(String fileUrl) {if (StringUtils.isEmpty(fileUrl)) {return "fileUrl == >>⽂件路径为空...";}try {StorePath storePath = StorePath.parseFromUrl(fileUrl);storageClient.deleteFile(storePath.getGroup(), storePath.getPath());} catch (Exception e) {return e.getMessage();}return "OK";}public byte[] downLoadFile(String filePath){StorePath storePath = StorePath.parseFromUrl(filePath);return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());}}6、测试界⾯7、常见问题1).跨域错误:file origin does not match viewer’s解决⽅式:找到 viewer.js 中下⽅的这段代码注释掉2).找不到⽂件错误:这个问题原因是因为没有获取到你本地或者服务器⽂件,也就是 pdf > web ⽬录⾥没有这个 pdf ,因为它默认是获取这个⽬录下的 pdf ⽂件解决⽅式:获取本地⽂件或者服务器⽂件路径,通过流的⽅式输出到页⾯上3).⽂件损坏⽆法显⽰问题:出现这个问题⼀般都是你的 url 没有进⾏转码就直接请求到浏览器了,然后 url 存在的特殊字符会会让浏览器误认为你这个不是⼀个完整的链接解决⽅式:查看前端访问的路径是否使⽤ encodeURIComponent 转码8、如何隐藏插件⾃带的下载和打印功能?打开 viewer.html ⽂件,搜索<button id="download"在这个 button 按钮加上⼀个属性style="visibility:hidden"就 ok 了,如下图。