net 预览文件 转换文件
生活随笔
收集整理的這篇文章主要介紹了
net 预览文件 转换文件
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
預(yù)覽SWF文件
?swfobject.js? (google瀏覽器 會(huì)阻止 需設(shè)置)
@{ViewBag.Title = "PdfPreview";Layout = "~/Views/Shared/_Layout.cshtml";var fileType = ViewBag.fileType;var swfpath = ViewBag.filePath; }<script src="~/Content/js/jquery.uploadify/swfobject.js"></script> <script src="~/Content/js/jquery.uploadify/flexpaper_flash_debug.js"></script><script src="/Content/js/jquery.uploadify/jquery-1.4.1.min.js"></script> <div id="app"><div id="contentText" style="border: dashed 1px #dddddd; background-color: white;"><div id="flashContent"></div></div> </div><script type="text/javascript">var swfVersionStr = "10.0.0";var swf = "@swfpath";//var swf = "http://localhost:8080/tmp/94D1390E-930D-4D41-BD88-72FDC3273755/94D1390E-930D-4D41-BD88-72FDC3273755.pdf";//var swf = "C:/Users/zz/Desktop/File/1.pdf";if (swf != "") {var swfpath = swf.replace('docx', 'swf').replace('xlsx', 'swf').replace('xls', 'swf').replace('doc', 'swf').replace("pdf", "swf");var xiSwfUrlStr = "playerProductInstall.swf";var swfFile = swfpath;var flashvars = {SwfFile: escape(swfFile),//編碼設(shè)置 Scale: 0.6,ZoomTransition: "easeOut",//變焦過渡 ZoomTime: 0.5,ZoomInterval: 0.2,//縮放滑塊-移動(dòng)的縮放基礎(chǔ)[工具欄] FitPageOnLoad: true,//自適應(yīng)頁面 FitWidthOnLoad: true,//自適應(yīng)寬度 PrintEnabled: true,//是否啟用打印FullScreenAsMaxWindow: false,//全屏按鈕-新頁面全屏[工具欄] ProgressiveLoading: true,//分割加載 //MinZoomSize: 0.2,//最小縮放 //MaxZoomSize: 3,//最大縮放 PrintToolsVisible: true,//是否顯示打印工具ViewModeToolsVisible: true,//顯示模式工具欄是否顯示 ZoomToolsVisible: true,//縮放工具欄是否顯示 FullScreenVisible: true,//是否全屏NavToolsVisible: true,//跳頁工具欄 CursorToolsVisible: true,SearchMatchAll: true,//搜索匹配全部SearchToolsVisible: true,//是否顯示搜索工具localeChain: "zh_CN"//語言 };var params = {}params.quality = "high";params.bgcolor = "#ffffff";params.allowscriptaccess = "sameDomain";params.allowfullscreen = "true";var attributes = {};attributes.id = "FlexPaperViewer";attributes.name = "FlexPaperViewer";swfobject.embedSWF("/Content/js/jquery.uploadify/FlexPaperViewer.swf",//默認(rèn)顯示的swfUrl"flashContent",//展示區(qū)域Id"100%",//展示寬度(window.innerHeight - 25) + "px",//戰(zhàn)術(shù)高度 swfVersionStr, xiSwfUrlStr,flashvars, params, attributes);swfobject.createCSS("#flashContent",//展示區(qū)域Id"display:block;text-align:center;");//滾動(dòng)條監(jiān)聽window.onload = function () {if (window.addEventListener) {window.addEventListener('DOMMouseScroll', deltaDispatcher, false);}document.body.onmousewheel = deltaDispatcher;}function deltaDispatcher(event) {event = window.event || event;var delta = 0;if (event.wheelDelta) {delta = event.wheelDelta / 120;if (window.opera) {delta = -delta;}} else if (event.detail) {delta = -event.detail;}if (event.preventDefault) {event.preventDefault();}var obj = swfobject.getObjectById("FlexPaperViewer");if (typeof (obj.externalMouseEvent) == 'function') {obj.externalMouseEvent(delta);}}} </script> View Code預(yù)覽音頻 視頻 圖片
@{ViewBag.Title = "文件預(yù)覽";Layout = "~/Views/Shared/_Layout.cshtml";var fileType = ViewBag.fileType;var filePath = ViewBag.filePath; }<div id="app"><el-container id="filePreview">@*(因?yàn)榭赡懿恢С講ue動(dòng)態(tài)綁定,所以改成js動(dòng)態(tài)加載)*@@*<audio v-bind:style="{ 'display':preview.audioShow}" controls><source :src="preview.audioUrl" type="audio/mpeg"><source :src="preview.audioUrl" type="audio/ogg"><embed height="50" width="100" :src="preview.audioUrl"></audio>*@@*//音頻*@ @*<video v-bind:style="{ 'height': mainHeight - 17 + 'px','width':'100%','display':preview.videoShow}" controls autoplay><source :src="preview.videoUrl" type="video/ogg"><source :src="preview.videoUrl" type="video/mp4"><source :src="preview.videoUrl" type="video/webm"><object :data="preview.videoUrl" v-bind:style="{ 'height': mainHeight - 17 + 'px','width':'100%'}"><embed v-bind:style="{ 'height': mainHeight - 17 + 'px','width':'100%'}" :src="preview.videoUrl"></object></video>*@@*//視頻*@ @*<img :src="preview.imgUrl" :style="{ 'display':preview.imgShow}" />*@@*//圖片*@</el-container> </div><script>var app = new Vue({el: "#app",data: {mainHeight: window.innerHeight,preview: {fileUrl: "",audioUrl: "",videoUrl: "",imgUrl: "",fileShow: "none",audioShow: "none",videoShow: "",imgShow: "none"},},mounted: function () {const cur = this;window.onload = () => {cur.pageLoad();};window.onresize = () => {cur.mainHeight = window.innerHeight;}},methods: {pageLoad() {const cur = this;let fileType = "@fileType";//文件類型let filePath = "@filePath";//預(yù)覽URLcur.preview = {audioUrl: "",videoUrl: "",imgUrl: "",audioShow: "none",videoShow: "none",imgShow: "none"};var filePreview = document.getElementById("filePreview");var str = "";switch (fileType) {case "1"://視頻//cur.preview = {// audioUrl: "",// videoUrl: filePath,// imgUrl: "",// audioShow: "none",// videoShow: "",// imgShow: "none"//};str = "<video style='width:100%; height:" + (cur.mainHeight - 17) + "px;' controls autoplay>";str += "< source src = '" + filePath + "' type = 'video/ogg' >";str += "<source src='" + filePath + "' type='video/mp4'>";str += "<source src='" + filePath + "' type='video/webm'>";str += "<object data='" + filePath + "' style='width:100%; height:" + (cur.mainHeight - 17) + "px;'>";str += "<embed style='width:100%; height:" + (cur.mainHeight - 17) + "px;' src='" + filePath + "'>";str += "</object></video>";break;case "2-1"://圖片case "2"://圖片//cur.preview = {// audioUrl: "",// videoUrl: "",// imgUrl: filePath,// audioShow: "none",// videoShow: "none",// imgShow: ""//};str = "<img src=\"" + filePath + "\" />";break;case "3"://音頻//cur.preview = {// audioUrl: filePath,// videoUrl: "",// imgUrl: "",// audioShow: "",// videoShow: "none",// imgShow: "none"//};str = "<audio controls='controls'>";str += "<source src = '" + filePath + "' type = 'audio/mpeg' >";str += "<source src='" + filePath + "' type='audio/ogg'>";str += "<object height='50' width='100' data='" + filePath + "'>";str += "<embed height='50' width='100' src='" + filePath + "'>";str += "</object></audio>";break;default:break;}filePreview.innerHTML = str;},}}); </script> View Code?
后端:
1.返回定義好的文件類型
private string[] imgExts = new string[] { ".BMP", ".GIF", ".JPEG", ".JPG", ".PNG", ".TIFF", ".TIF" };//轉(zhuǎn)換文件類型 result.Data.RelativePaths = (HttpContext.Current.Request.Url.Authority + "\\" + Index(result.Data.RelativePaths)).Replace("\\", "/");string fileext = Util.GetFileExt(doc.DocName).ToLower();if (imgExts.Contains(fileext.ToUpper()))//圖片 {if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf"){result.Data.DocType = "2-2";//圖片-swf }else{result.Data.DocType = "2-1";//圖片 }}else if (".wav;.mp3;.ra;.rma;.wma;.asf;.mid;.midi;.rmi;.xmi;.ogg;.vqf;.tvq;.mod;.ape;.aiff;.au".Contains(fileext))//音頻 {result.Data.DocType = "3";}else if (".m4a;.wma;.rm;.midi;.ape;.flac;.avi;.rmvb;.asf;.divx;.mpg;.mpeg;.mpe;.wmv;.mp4;.mkv;.vob".Contains(fileext))//視頻 {result.Data.DocType = "1";}else if (".doc;.docx".Contains(fileext))//word {if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".html"){result.Data.DocType = "4-1";//word-html }else{result.Data.DocType = "4-2";//word-swf }}else if (".xls;.xlsx".Contains(fileext))//excel {if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".html"){result.Data.DocType = "5-1";//excel-html }else{result.Data.DocType = "5-2";//excel-swf }}else if (".txt".Contains(fileext))//文本 {if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf"){result.Data.DocType = "6-2";}else{result.Data.DocType = "6-1";}}else if (".html;.htm".Contains(fileext))//網(wǎng)頁 {if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf"){result.Data.DocType = "7-2";//網(wǎng)頁-swf }else{result.Data.DocType = "7-1";//網(wǎng)頁 }}else if (".pdf;.swf".Contains(fileext))//pdf {result.Data.DocType = "8";}}catch (Exception ex){Logger.Error(ex);result.ErrCode = 1;result.ResultMsg = "獲取文件失敗!";}return result; View Code2.轉(zhuǎn)換文件
/// <summary>/// 返回本地文件或共享文件/// </summary>/// <param name="path">相對(duì)路徑</param>/// <param name="serverPath">共享服務(wù)器</param>/// <returns></returns>public string MapPath(string path, string serverPath = ""){string ph = path;if (string.IsNullOrWhiteSpace(path)) return "";string url = ConfigHelper.GetValue("ShareFileUrl");if (!string.IsNullOrEmpty(serverPath)){url = serverPath;}//共享文件夾能夠連接if (ConnectShareFileSys()){ph = path.Replace("~", url).Replace("/", "\\");}else{ph = HttpContext.Current.Server.MapPath(path);}return ph;}/// <summary>/// 獲取客戶端IP地址/// </summary>/// <returns></returns>public string GetIP(){string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];if (string.IsNullOrEmpty(result)){result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];}if (string.IsNullOrEmpty(result)){result = HttpContext.Current.Request.UserHostAddress;}if (string.IsNullOrEmpty(result)){return "127.0.0.1";}return result;}#region Index頁面/// <summary>/// Index頁面/// </summary>/// <param name="url">例:/uploads/......XXX.xls</param>public string Index(string url){if (string.IsNullOrWhiteSpace(url)) return "";string physicalPath = AppDomain.CurrentDomain.BaseDirectory + url;string extension = Path.GetExtension(physicalPath);string htmlUrl = "";if (imgExts.Contains(extension.ToUpper()))//圖片 {htmlUrl = PreviewPicture(physicalPath, url);return htmlUrl;}if (".wav;.mp3;.ra;.rma;.wma;.asf;.mid;.midi;.rmi;.xmi;.ogg;.vqf;.tvq;.mod;.ape;.aiff;.au".Contains(extension.ToLower()))//音頻 {htmlUrl = PreviewAudio(physicalPath, url);return htmlUrl;}if (".m4a;.wma;.rm;.midi;.ape;.flac;.avi;.rmvb;.asf;.divx;.mpg;.mpeg;.mpe;.wmv;.mp4;.mkv;.vob".Contains(extension.ToLower()))//視頻 {htmlUrl = PreviewVideo(physicalPath, url);return htmlUrl;}switch (extension.ToLower()){case ".xls":case ".xlsx":htmlUrl = PreviewExcel(physicalPath, url);break;case ".doc":case ".docx":htmlUrl = PreviewWord(physicalPath, url);break;case ".txt":htmlUrl = PreviewTxt(physicalPath, url);break;case ".pdf":case ".swf":htmlUrl = PreviewPdf(physicalPath, url);break;case ".html":case ".htm":htmlUrl = PreviewHtml(physicalPath, url);break;}return htmlUrl;}#endregion#region 預(yù)覽Excel/// <summary>/// 預(yù)覽Excel/// </summary>/// <param name="physicalPath">絕對(duì)路徑</param>/// <param name="url">相對(duì)路徑</param>/// <returns></returns>public string PreviewExcel(string physicalPath, string url){string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".pdf";if (!File.Exists(pdfPath)){if (ExcelToPdf(physicalPath, pdfPath))//轉(zhuǎn)換成pdf {//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}else//轉(zhuǎn)換成html {return ExcelToHtml(physicalPath, url);}}else{//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}}/// <summary>/// 預(yù)覽Excel轉(zhuǎn)換成html(備用)/// </summary>/// <param name="physicalPath">絕對(duì)路徑</param>/// <param name="url">相對(duì)路徑</param>/// <returns></returns>public string ExcelToHtml(string physicalPath, string url){Excel.Application application = null;Excel.Workbook workbook = null;application = new Excel.Application();object missing = Type.Missing;object trueObject = true;application.Visible = false;application.DisplayAlerts = false;workbook = application.Workbooks.Open(physicalPath, missing, trueObject, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing);//Save Excel to Htmlobject format = Excel.XlFileFormat.xlHtml;string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;workbook.SaveAs(outputFile, format, missing, missing, missing,missing, Excel.XlSaveAsAccessMode.xlNoChange, missing,missing, missing, missing, missing);workbook.Close();application.Quit();return Path.GetDirectoryName(url) + "\\" + htmlName;}/// <summary>/// 把Excel文件轉(zhuǎn)換成PDF格式文件(office)/// </summary>/// <param name="sourcePath">源文件路徑</param>/// <param name="targetPath">目標(biāo)文件路徑</param>/// <returns>true=轉(zhuǎn)換成功</returns>public bool XLSConvertToPDF(string sourcePath, string targetPath){bool result = false;Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;object missing = Type.Missing;Excel.ApplicationClass application = null;//Excel.Application application = null;//如不支持換上面注釋代碼Excel.Workbook workBook = null;try{application = new Excel.ApplicationClass();//application = new Excel.Application();//如不支持換上面注釋代碼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, Excel.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;}/// <summary>/// 把Excel文件轉(zhuǎn)換成PDF格式文件(Aspose)/// </summary>/// <param name="sourcePath">源文件路徑</param>/// <param name="targetPath">目標(biāo)文件路徑</param>/// <returns>true=轉(zhuǎn)換成功</returns>public bool ExcelToPdf(string sourcePath, string targetPath){bool result = false;try{//ExcelWorkbook excel = new Workbook(sourcePath);excel.Save(targetPath, Aspose.Cells.SaveFormat.Pdf);result = true;}catch (Exception){result = false;}return result;}#endregion#region 預(yù)覽Word/// <summary>/// 預(yù)覽Word/// </summary>/// <param name="physicalPath">絕對(duì)路徑</param>/// <param name="url">相對(duì)路徑</param>/// <returns></returns>public string PreviewWord(string physicalPath, string url){string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".pdf";if (!File.Exists(pdfPath)){if (WordToPdf(physicalPath, pdfPath))//轉(zhuǎn)換成pdf {//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}else//轉(zhuǎn)換成html {return WordToHtml(physicalPath, url);}}else{//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}}/// <summary>/// 預(yù)覽Word轉(zhuǎn)換成html(備用)/// </summary>/// <param name="physicalPath">絕對(duì)路徑</param>/// <param name="url">相對(duì)路徑</param>/// <returns></returns>public string WordToHtml(string physicalPath, string url){Word._Application application = null;Word._Document doc = null;application = new Word.Application();object missing = Type.Missing;object trueObject = true;application.Visible = false;application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;doc = application.Documents.Open(physicalPath, missing, trueObject, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);//Save Excel to Htmlobject format = Word.WdSaveFormat.wdFormatHTML;string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;doc.SaveAs(outputFile, format, missing, missing, missing,missing, Excel.XlSaveAsAccessMode.xlNoChange, missing,missing, missing, missing, missing);doc.Close();application.Quit();return Path.GetDirectoryName(url) + "\\" + htmlName;}//Word轉(zhuǎn)換成pdf/// <summary>/// 把Word文件轉(zhuǎn)換成為PDF格式文件(office)/// </summary>/// <param name="sourcePath">源文件路徑</param>/// <param name="targetPath">目標(biāo)文件路徑</param>/// <returns>true=轉(zhuǎn)換成功</returns>private bool DOCConvertToPDF(string sourcePath, string targetPath){bool result = false;Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;object paramMissing = Type.Missing;Word.ApplicationClass wordApplication = new Word.ApplicationClass();//Word.Application wordApplication = new Word.Application();//如不支持換上面注釋代碼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 = 0;int paramEndPage = 0;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;}catch{result = false;}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;}/// <summary>/// 把Word文件轉(zhuǎn)換成為PDF格式文件(Aspose)/// </summary>/// <param name="sourcePath">源文件路徑</param>/// <param name="targetPath">目標(biāo)文件路徑</param>/// <returns>true=轉(zhuǎn)換成功</returns>private bool WordToPdf(string sourcePath, string targetPath){bool result = false;try{Aspose.Words.Document doc = new Aspose.Words.Document(sourcePath);doc.Save(targetPath, Aspose.Words.SaveFormat.Pdf);result = true;}catch (Exception){result = false;}return result;}#endregion#region 預(yù)覽Txt/// <summary>/// 預(yù)覽Txt/// </summary>public string PreviewTxt(string physicalPath, string url){string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".pdf";if (!File.Exists(pdfPath))//不存在pdf {if (TxtToPdf(physicalPath, pdfPath))//轉(zhuǎn)換成功 {//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}else{return url;}}else{//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}}/// <summary>/// 把txt文件轉(zhuǎn)換成pdf格式文件/// </summary>/// <param name="txtFile"></param>/// <param name="pdfFile"></param>/// <returns></returns>public bool TxtToPdf(string txtFile, string pdfFile){bool result = false;try{//第一個(gè)參數(shù)是txt文件物理路徑 string[] lines = System.IO.File.ReadAllLines(txtFile, Encoding.GetEncoding("gb2312"));//iTextSharp.text.PageSize.A4 自定義頁面大小 iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 20, 20, 20);PdfWriter pdfwriter =PdfWriter.GetInstance(doc, new FileStream(pdfFile, FileMode.Create));doc.Open();//創(chuàng)建我的基本字體 BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//創(chuàng)建字體 字體大小,字體粗細(xì) 字體顏色 iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);iTextSharp.text.Paragraph paragraph;foreach (string line in lines){paragraph = new iTextSharp.text.Paragraph(line, font);doc.Add(paragraph);}//關(guān)閉文件 doc.Close();result = true;}catch (Exception ex){result = false;}return result;}/// <summary>/// 把txt文件轉(zhuǎn)換成pdf格式文件(備用)/// </summary>/// <param name="txtFile"></param>/// <param name="pdfFile"></param>/// <returns></returns>public bool TxtConvertPdf(string txtFile, string pdfFile){bool result = false;try{var document = new iTextSharp.text.Document(PageSize.A4, 30f, 30f, 30f, 30f);PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));document.Open();var bfSun = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);var font = new iTextSharp.text.Font(bfSun, 12f);var objReader = new StreamReader(txtFile, Encoding.GetEncoding("gb2312"));var str = "";while (str != null){str = objReader.ReadLine();if (str != null){document.Add(new iTextSharp.text.Paragraph(str, font));}}objReader.Close();document.Close();result = true;}catch (Exception ex){result = false;}return result;}#endregion#region 預(yù)覽圖片/// <summary>/// 預(yù)覽圖片/// </summary>public string PreviewPicture(string physicalPath, string url){string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".pdf";if (!File.Exists(pdfPath))//不存在轉(zhuǎn)pdf {if (ConvertJPG2PDF(physicalPath, pdfPath))//轉(zhuǎn)換成功 {//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}else{//預(yù)覽圖片return url;}}else{//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}}/// <summary>/// 把圖片轉(zhuǎn)換pdf格式文件/// </summary>/// <param name="jpgfile"></param>/// <param name="pdf"></param>/// <returns></returns>public bool ConvertJPG2PDF(string jpgfile, string pdf){bool result = false;try{var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)){PdfWriter.GetInstance(document, stream);document.Open();using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){var image = Image.GetInstance(imageStream);if (image.Height > iTextSharp.text.PageSize.A4.Height - 25){image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);}else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25){image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);}image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;document.Add(image);}document.Close();}result = true;}catch (Exception ex){result = false;}return result;}#endregion#region 預(yù)覽Pdf/// <summary>/// 預(yù)覽Pdf/// </summary>public string PreviewPdf(string physicalPath, string url){if (Util.GetFileExt(physicalPath).ToLower() == ".swf"){return url;}string swfPath = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".swf";if (!File.Exists(swfPath)){Pdf2Swf(physicalPath, swfPath);}return url.Substring(0, url.LastIndexOf('.')) + ".swf";}//pwf2swf.exe 文件所在目錄 private string Pdf2Swfexe = Util.BaseDirectory.TrimEnd('\\') + @"\Tools\pdf2swf\pdf2swf.exe";/// <summary> /// 轉(zhuǎn)換所有的頁,圖片質(zhì)量80% /// </summary> /// <param name="pdfPath">PDF文件地址</param> /// <param name="swfPath">生成后的SWF文件地址</param> public bool Pdf2Swf(string pdfPath, string swfPath){return Pdf2Swf(pdfPath, swfPath, 1, GetPageCount(pdfPath), 80);}/// <summary> /// PDF格式轉(zhuǎn)為SWF /// </summary> /// <param name="pdfPath">PDF文件地址</param> /// <param name="swfPath">生成后的SWF文件地址</param> /// <param name="beginpage">轉(zhuǎn)換開始頁</param> /// <param name="endpage">轉(zhuǎn)換結(jié)束頁</param> /// <param name="photoQuality"></param> private bool Pdf2Swf(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality){if (!System.IO.File.Exists(Pdf2Swfexe) ||!System.IO.File.Exists(pdfPath) ||System.IO.File.Exists(swfPath)){return false;}//執(zhí)行的命令參數(shù) StringBuilder command = new StringBuilder();command.AppendFormat(" \"{0}\"", pdfPath);command.AppendFormat(" -o \"{0}\"", swfPath);command.Append(" -s flashversion=9");command.AppendFormat(" -p \"{0}-{1}\"", beginpage, endpage);command.AppendFormat(" -j {0}", photoQuality);Process p = new Process{StartInfo ={FileName = Pdf2Swfexe,Arguments = command.ToString(),WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/"),WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,UseShellExecute = false,RedirectStandardError = true,CreateNoWindow = false}};p.Start();p.BeginErrorReadLine();p.WaitForExit();p.Close();p.Dispose();return true;}/// <summary> /// 取PDF總頁數(shù) /// </summary> /// <param name="pdfPath">PDF文件地址</param> private int GetPageCount(string pdfPath){byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);if (buffer.Length <= 0){return -1;}string pdfText = Encoding.Default.GetString(buffer);Regex rx1 = new Regex(@"/Type\s*/Page[^s]");MatchCollection matches = rx1.Matches(pdfText);if (matches.Count == 0){//iTextSharp讀取pdf頁數(shù)PdfReader pdfReader = new PdfReader(pdfPath);if (pdfReader.NumberOfPages == 0){return 1;}return pdfReader.NumberOfPages;}return matches.Count;}#region 獲取PDF文件的頁數(shù)(廢棄)private int BytesLastIndexOf(Byte[] buffer, int length, string Search){if (buffer == null)return -1;if (buffer.Length <= 0)return -1;byte[] SearchBytes = Encoding.Default.GetBytes(Search.ToUpper());for (int i = length - SearchBytes.Length; i >= 0; i--){bool bFound = true;for (int j = 0; j < SearchBytes.Length; j++){if (ByteUpper(buffer[i + j]) != SearchBytes[j]){bFound = false;break;}}if (bFound)return i;}return -1;}private byte ByteUpper(byte byteValue){char charValue = Convert.ToChar(byteValue);if (charValue < 'a' || charValue > 'z')return byteValue;elsereturn Convert.ToByte(byteValue - 32);}/// <summary>/// 獲取pdf文件的頁數(shù)/// </summary>public int GetPDFPageCount(string path) //獲取pdf文件的頁數(shù) {//path = HttpContext.Current.Server.MapPath(path);byte[] buffer = File.ReadAllBytes(path);int length = buffer.Length;if (buffer == null)return -1;if (buffer.Length <= 0)return -1;try{//Sample// 29 0 obj// <</Count 9// Type /Pagesint i = 0;int nPos = BytesLastIndexOf(buffer, length, "/Type/Pages");if (nPos == -1)return -1;string pageCount = null;for (i = nPos; i < length - 10; i++){if (buffer[i] == '/' && buffer[i + 1] == 'C' && buffer[i + 2] == 'o' && buffer[i + 3] == 'u' && buffer[i + 4] == 'n' && buffer[i + 5] == 't'){int j = i + 3;while (buffer[j] != '/' && buffer[j] != '>')j++;pageCount = Encoding.Default.GetString(buffer, i, j - i);break;}}if (pageCount == null)return -1;int n = pageCount.IndexOf("Count");if (n > 0){pageCount = pageCount.Substring(n + 5).Trim();for (i = pageCount.Length - 1; i >= 0; i--){if (pageCount[i] >= '0' && pageCount[i] <= '9'){return int.Parse(pageCount.Substring(0, i + 1));}}}return -1;}catch (Exception ex){return -1;}}#endregion#endregion#region 預(yù)覽視頻/// <summary>/// 預(yù)覽視頻/// </summary>public string PreviewVideo(string physicalPath, string url){if (Util.GetFileExt(physicalPath).ToLower() == ".mp4"){return url;}string mp4Path = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".mp4";if (!File.Exists(mp4Path)){ConvertToMp4(physicalPath, mp4Path);}return url.Substring(0, url.LastIndexOf('.')) + ".mp4";}/// <summary>/// 格式轉(zhuǎn)換(Mp4)/// </summary>/// <param name="pathBefore">原格式文件路徑(絕對(duì)路勁)</param>/// <param name="pathLater">轉(zhuǎn)換后文件路徑(絕對(duì)路勁)</param>/// <returns></returns>public string ConvertToMp4(string pathBefore, string pathLater){string c = Util.BaseDirectory.TrimEnd('\\') + "\\Tools\\ffmpeg\\ffmpeg.exe -i " + pathBefore + " -y " + pathLater;string str = RunCmd(c);return str;}#endregion#region 預(yù)覽html/// <summary>/// 預(yù)覽html/// </summary>public string PreviewHtml(string physicalPath, string url){string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".pdf";if (!File.Exists(pdfPath))//不存在 {if (HtmlConvertToPdf(physicalPath, pdfPath))//轉(zhuǎn)換成功 {//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}else{return url;}}else{//預(yù)覽pdfreturn PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf('.')) + ".pdf");}}/// <summary>/// HTML文本內(nèi)容轉(zhuǎn)換為PDF/// </summary>/// <param name="strHtml">HTML文本內(nèi)容</param>/// <param name="savePath">PDF文件保存的路徑</param>/// <returns></returns>public bool HtmlTextConvertToPdf(string strHtml, string savePath){bool flag = false;try{string htmlPath = HtmlTextConvertFile(strHtml);flag = HtmlConvertToPdf(htmlPath, savePath);File.Delete(htmlPath);}catch{flag = false;}return flag;}/// <summary>/// HTML轉(zhuǎn)換為PDF/// </summary>/// <param name="htmlPath">可以是本地路徑,也可以是網(wǎng)絡(luò)地址</param>/// <param name="savePath">PDF文件保存的路徑</param>/// <returns></returns>public bool HtmlConvertToPdf(string htmlPath, string savePath){bool flag = false;CheckFilePath(savePath);///這個(gè)路徑為程序集的目錄,因?yàn)槲野褢?yīng)用程序 wkhtmltopdf.exe 放在了程序集同一個(gè)目錄下//string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";string exePath = Util.BaseDirectory.TrimEnd('\\') + @"\Tools\wkhtmltopdf\wkhtmltopdf.exe";if (!File.Exists(exePath)){throw new Exception("No application wkhtmltopdf.exe was found.");}try{ProcessStartInfo processStartInfo = new ProcessStartInfo();processStartInfo.FileName = exePath;processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);processStartInfo.UseShellExecute = false;processStartInfo.CreateNoWindow = true;processStartInfo.RedirectStandardInput = true;processStartInfo.RedirectStandardOutput = true;processStartInfo.RedirectStandardError = true;processStartInfo.Arguments = GetArguments(htmlPath, savePath);Process process = new Process();process.StartInfo = processStartInfo;process.Start();process.WaitForExit();///用于查看是否返回錯(cuò)誤信息//StreamReader srone = process.StandardError;//StreamReader srtwo = process.StandardOutput;//string ss1 = srone.ReadToEnd();//string ss2 = srtwo.ReadToEnd();//srone.Close();//srone.Dispose();//srtwo.Close();//srtwo.Dispose(); process.Close();process.Dispose();flag = true;}catch{flag = false;}return flag;}/// <summary>/// 獲取命令行參數(shù)/// </summary>/// <param name="htmlPath"></param>/// <param name="savePath"></param>/// <returns></returns>private string GetArguments(string htmlPath, string savePath){if (string.IsNullOrEmpty(htmlPath)){throw new Exception("HTML local path or network address can not be empty.");}if (string.IsNullOrEmpty(savePath)){throw new Exception("The path saved by the PDF document can not be empty.");}StringBuilder stringBuilder = new StringBuilder();stringBuilder.Append(" --page-height 297 "); //頁面高度297mm(A4紙高度)stringBuilder.Append(" --page-width 210 "); //頁面寬度210mm(A4紙寬度)//stringBuilder.Append(" --header-center 我是頁眉 "); //設(shè)置居中顯示頁眉//stringBuilder.Append(" --header-line "); //頁眉和內(nèi)容之間顯示一條直線//stringBuilder.Append(" --footer-center \"Page [page] of [topage]\" "); //設(shè)置居中顯示頁腳//stringBuilder.Append(" --footer-line "); //頁腳和內(nèi)容之間顯示一條直線stringBuilder.Append(" " + htmlPath + " "); //本地 HTML 的文件路徑或網(wǎng)頁 HTML 的URL地址stringBuilder.Append(" " + savePath + " "); //生成的 PDF 文檔的保存路徑return stringBuilder.ToString();}/// <summary>/// 驗(yàn)證保存路徑/// </summary>/// <param name="savePath"></param>private void CheckFilePath(string savePath){string ext = string.Empty;string path = string.Empty;string fileName = string.Empty;ext = Path.GetExtension(savePath);if (string.IsNullOrEmpty(ext) || ext.ToLower() != ".pdf"){throw new Exception("Extension error:This method is used to generate PDF files.");}fileName = Path.GetFileName(savePath);if (string.IsNullOrEmpty(fileName)){throw new Exception("File name is empty.");}try{path = savePath.Substring(0, savePath.IndexOf(fileName));if (!Directory.Exists(path)){Directory.CreateDirectory(path);}}catch{throw new Exception("The file path does not exist.");}}/// <summary>/// HTML文本內(nèi)容轉(zhuǎn)HTML文件/// </summary>/// <param name="strHtml">HTML文本內(nèi)容</param>/// <returns>HTML文件的路徑</returns>public string HtmlTextConvertFile(string strHtml){if (string.IsNullOrEmpty(strHtml)){throw new Exception("HTML text content cannot be empty.");}try{string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"html\";if (!Directory.Exists(path)){Directory.CreateDirectory(path);}string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 10000) + ".html";FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default);streamWriter.Write(strHtml);streamWriter.Flush();streamWriter.Close();streamWriter.Dispose();fileStream.Close();fileStream.Dispose();return fileName;}catch{throw new Exception("HTML text content error.");}}#endregion#region 預(yù)覽音頻/// <summary>/// 預(yù)覽音頻/// </summary>public string PreviewAudio(string physicalPath, string url){if (Util.GetFileExt(physicalPath).ToLower() == ".mp3"){return url;}string mp3Path = physicalPath.Substring(0, physicalPath.LastIndexOf('.')) + ".mp3";if (!File.Exists(mp3Path)){ConvertToMp3(physicalPath, mp3Path);}return url.Substring(0, url.LastIndexOf('.')) + ".mp3";}/// <summary>/// 格式轉(zhuǎn)換(Mp3)/// </summary>/// <param name="pathBefore">原格式文件路徑(絕對(duì)路勁)</param>/// <param name="pathLater">轉(zhuǎn)換后文件路徑(絕對(duì)路勁)</param>/// <returns></returns>public string ConvertToMp3(string pathBefore, string pathLater){string c = Util.BaseDirectory.TrimEnd('\\') + "\\Tools\\ffmpeg\\ffmpeg.exe -i " + pathBefore + " -f mp3 -acodec libmp3lame -y " + pathLater;string str = RunCmd(c);return str;}/// <summary>/// 執(zhí)行Cmd命令/// </summary>private string RunCmd(string c){try{System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("cmd.exe");info.RedirectStandardOutput = false;info.UseShellExecute = false;System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);p.StartInfo.UseShellExecute = false;p.StartInfo.RedirectStandardInput = true;p.StartInfo.RedirectStandardOutput = true;p.StartInfo.RedirectStandardError = true;p.Start();p.StandardInput.WriteLine(c);p.StandardInput.AutoFlush = true;System.Threading.Thread.Sleep(1000);p.StandardInput.WriteLine("exit");p.Close();p.WaitForExit(1000);string outStr = p.StandardOutput.ReadToEnd();//p.Close();return outStr;}catch (Exception ex){return "error" + ex.Message;}}#endregion View Code3.轉(zhuǎn)換文件工具
預(yù)覽 excel、word、txt、圖片、pdf、html、音視頻等文件(涉及到格式轉(zhuǎn)換,用到ffmpeg、pdf2swf、wkhtmltopdf工具,iTextSharp類,Aspose(破解版)類、Microsoft.Office.Interop.Excel、Word類、swf文件預(yù)覽插件FlexPaper)
?
C#文件網(wǎng)頁預(yù)覽:?https://blog.csdn.net/lixiaoer757/article/details/80277617
轉(zhuǎn)載于:https://www.cnblogs.com/love201314/p/9964977.html
總結(jié)
以上是生活随笔為你收集整理的net 预览文件 转换文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: #9733;为什么不要和“穷人”做朋友?
- 下一篇: 计算机内存的安装方法,内存条怎么装?内存