引言
之前在一个项目中初识了这个控件,当时自己对这个东西非常高的好奇就尝试着做了一个Demo,最近在项目中
遇到了这个需求,所以我向组长推荐了我的这中做法,在之前的系统中是将文档转换成html然后在前台中预览,这样
有一个弊端就是在预览的时候会破坏文档原来的格式,感觉不符合全心全意为人民服务的思想,所以就采用了我的这
种做法。下面给大家分享这个控件的用法;
首先给大家展示一张效果图:
和之前的预览相比最重要的就是不会破坏文档的样式,和上传时候的文档的上市一模一样;
一、上传并将文档转换成.swf格式的文件
这一步需要我们在上传的过程中来实现这种转换,代码如下:
上传的前台界面代码:
<div class="easyui-panel" style="width:1380px;height:180px; font-size:16px;"> <span class="tip" style="font-size:16px;color :red; font-weight :bold ">提示:请您先选择一个文件(文档大小不能超过4M,格式为:doc//docx//xls//xlsx//zip//rar)</span> <br /> <br /> @using (Html.BeginForm("UpDocument", "DocumentManagement", FormMethod.Post, new { enctype = "multipart/form-data" })) { <form id="Batch" method="post"> <input type="file" name="files" id="FileUpload" style="height :40px;width:200px;"> <input type="submit" name="btnUpload" value="上传" id="btnUpload" style="height:20px;width:55px" /> </form> } </div>
#region 上传文档,将文档的相应信息插入 到数据库——郑浩——2016年2月28日11:49:17 public ActionResult UpDocument() { //变量定义pdf转为swf的工具路径 string pdf2swfToolPath = System.Web.HttpContext.Current.Server.MapPath("~/FlexPaper/pdf2swf.exe"); //定义保存路径的变量 string OfficeFilePath = Server.MapPath("~/File/UpFile/"); string PdfFilePath = Server.MapPath("~/File/TeaFile/PDF/"); string SWFFilePath = Server.MapPath("~/File/TeaFile/SWF/"); string SwfFileName = String.Empty; HttpPostedFileBase file = Request.Files["files"]; string strFileName = ""; string strSavePath; string ClientPath = AppDomain.CurrentDomain.BaseDirectory + "File\\UpFile\\"; if (file == null || file.ContentLength <= 0) { Response.Write("<script>alert('文件不能为空')</script>"); return View("~/Views/DocumentManagement/UploadWord.cshtml"); } string strFilename = Path.GetFileName(file.FileName); int intFilesize = file.ContentLength;//获取上传文件的大小单位为字节byte string fileEx = System.IO.Path.GetExtension(strFilename);//获取上传文件的扩展名 string strNoFileName = System.IO.Path.GetFileNameWithoutExtension(strFilename);//获取无扩展名的文件名 int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M string FileType = ".xls,.xlsx,.doc,docx,.zip,.rar";//定义上传文件的类型字符串 strFileName = strNoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx; if (!FileType.Contains(fileEx)) { Response.Write("<script>alert('文件类型不对,请参考提示上传文件')</script>"); return View("~/Views/DocumentManagement/UploadWord.cshtml"); } if (intFilesize >= Maxsize) { Response.Write("<script>alert('上传文件超过4M,不能上传')</script>"); return View("~/Views/DocumentManagement/UploadWord.cshtml"); } strSavePath = Path.Combine(ClientPath, strFileName); file.SaveAs(strSavePath); //开始格式转换 string PdfFileName = OfficeToPdf(OfficeFilePath, strFileName, PdfFilePath); SwfFileName = PdfToSwf(pdf2swfToolPath, PdfFilePath, PdfFileName, SWFFilePath); //将对应的数据保存到数据库中 DocumentViewModel documentView = new DocumentViewModel() { DocumentID = Guid.NewGuid(), UploadYear = DateTime.Now, DocumentName = strFileName, DocumentPath = "File\\UpFile\\" + strFileName, IsEnable = 1, Operator = "admin" }; //调用后台的方法 bool flag = iDocument.UpDocument(documentView); if (flag) { Response.Write("<script>alert('文件上传成功!!')</script>"); return View("~/Views/DocumentManagement/UploadWord.cshtml"); } else { Response.Write("<script>alert('文件上传失败!!')</script>"); return View("~/Views/DocumentManagement/UploadWord.cshtml"); } } #endregion
#region office转换过程 -郑浩-2016年2月29日10:44:05 #region OfficeToPdf-将office文件转化为pdf文件,文件名称不变-郑浩-2016年2月29日10:44:29 /// <summary> /// 将office文件转化为pdf文件,文件名称不变 /// </summary> /// <param name="pdf2swfPath">pdf2swfPath工具所在路径</param> /// <param name="OfficePath">office存储路径</param> /// <param name="OfficeName">office文件名称</param> /// <param name="destPath">pdf存储路径</param> /// <returns>返回生成pdf的文件名,无效则返回空</returns> private string OfficeToPdf(string OfficePath, string OfficeName, string destPath) { string fullPathName = OfficePath + OfficeName;//包含 路径 的全称 string fileNameWithoutEx = System.IO.Path.GetFileNameWithoutExtension(OfficeName);//不包含路径,不包含扩展名 string extendName = System.IO.Path.GetExtension(OfficeName).ToLower();//文件扩展名 string saveName = destPath + fileNameWithoutEx + ".pdf"; string returnValue = fileNameWithoutEx + ".pdf"; switch (extendName) { case ".doc": PreviewConvert.WordToPDF(fullPathName, saveName); break; case ".docx": PreviewConvert.WordToPDF(fullPathName, saveName); break; case ".xls": PreviewConvert.ExcelToPDF(fullPathName, saveName); break; case ".xlsx": PreviewConvert.ExcelToPDF(fullPathName, saveName); break; default: returnValue = ""; break; } return returnValue; } #endregion #region PdfToSwf-将pdf文件转化为swf文件,文件名称不变-郑浩-2016年2月29日10:51:50 /// <summary> /// 将pdf文件转化为swf文件,文件名称不变 /// </summary> /// <param name="pdf2swfPath">pdf2swfPath工具所在路径</param> /// <param name="PdfPath">pdf存储路径</param> /// <param name="PdfName">pdf文件名称</param> /// <param name="destPath">swf存储路径</param> /// <returns></returns> private string PdfToSwf(string pdf2swfPath, string PdfPath, string PdfName, string destPath) { string fullPathName = PdfPath + PdfName;//包含 路径 的全称 string fileNameWithoutEx = System.IO.Path.GetFileNameWithoutExtension(PdfName);//不包含路径,不包含扩展名 string extendName = System.IO.Path.GetExtension(PdfName).ToLower();//文件扩展名 string saveName = destPath + fileNameWithoutEx + ".swf"; string returnValue = fileNameWithoutEx + ".swf"; if (extendName != ".pdf") { returnValue = ""; } else { PreviewConvert.PDFToSWF(pdf2swfPath, fullPathName, saveName); } return returnValue; } #endregion #endregion
转换的公共类:
public class PreviewConvert { /// <summary> /// 把Word文件转换成为PDF格式文件 /// </summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true=转换成功</returns> public static bool WordToPDF(string sourcePath, string targetPath) { bool result = false; Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF; Microsoft.Office.Interop.Word.ApplicationClass application = null; Microsoft.Office.Interop.Word.Document document = null; try { application = new Microsoft.Office.Interop.Word.ApplicationClass(); application.Visible = false; document = application.Documents.Open(sourcePath); document.SaveAs(); document.ExportAsFixedFormat(targetPath, exportFormat); result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { if (document != null) { document.Close(); document = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return result; } /// <summary> /// 把Microsoft.Office.Interop.Excel文件转换成PDF格式文件 /// </summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true=转换成功</returns> public static bool ExcelToPDF(string sourcePath, string targetPath) { bool result = false; Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF; object missing = Type.Missing; Microsoft.Office.Interop.Excel.ApplicationClass application = null; Microsoft.Office.Interop.Excel.Workbook workBook = null; try { application = new Microsoft.Office.Interop.Excel.ApplicationClass(); application.Visible = false; workBook = application.Workbooks.Open(sourcePath); workBook.SaveAs(); workBook.ExportAsFixedFormat(targetType, targetPath); result = true; } catch (Exception e) { Console.WriteLine(e.Message); 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> /// 把PDF文件转化为SWF文件 /// </summary> /// <param name="toolPah">pdf2swf工具路径</param> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true=转化成功</returns> public static bool PDFToSWF(string toolPah, string sourcePath, string targetPath) { Process pc = new Process(); bool returnValue = true; string cmd = toolPah; string args = " -t " + sourcePath + " -s flashversion=9 -o " + targetPath; try { ProcessStartInfo psi = new ProcessStartInfo(cmd, args); psi.WindowStyle = ProcessWindowStyle.Hidden; pc.StartInfo = psi; pc.Start(); pc.WaitForExit(); } catch (Exception ex) { returnValue = false; throw new Exception(ex.Message); } finally { pc.Close(); pc.Dispose(); } return returnValue; } /// <summary> /// png、jpg和jpeg文件的转化 /// </summary> /// <param name="toolPah"></param> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> /// <returns></returns> public static bool PicturesToSwf(string toolPah, string sourcePath, string targetPath) { Process pc = new Process(); bool returnValue = true; string cmd = toolPah; string args = " " + sourcePath + " -o " + targetPath + " -T 9"; //如果是多个图片转化为swf 格式为 ..jpeg2swf.exe C:\1.jpg C:\2.jpg -o C:\swf1.swf try { ProcessStartInfo psi = new ProcessStartInfo(cmd, args); psi.WindowStyle = ProcessWindowStyle.Hidden; pc.StartInfo = psi; pc.Start(); pc.WaitForExit(); } catch (Exception ex) { returnValue = false; throw new Exception(ex.Message); } finally { pc.Close(); pc.Dispose(); } return returnValue; } /// <summary> /// Gif文件转化为swf /// </summary> /// <param name="toolPah"></param> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> /// <returns></returns> public static bool GifPicturesToSwf(string toolPah, string sourcePath, string targetPath) { Process pc = new Process(); bool returnValue = true; string cmd = toolPah; string args = " " + sourcePath + " -o " + targetPath; try { ProcessStartInfo psi = new ProcessStartInfo(cmd, args); psi.WindowStyle = ProcessWindowStyle.Hidden; pc.StartInfo = psi; pc.Start(); pc.WaitForExit(); } catch (Exception ex) { returnValue = false; throw new Exception(ex.Message); } finally { pc.Close(); pc.Dispose(); } return returnValue; } }
二、预览
前台代码:这里需要我们引入一个封装的js:flexpaper_flash.js;
@*文档预览*@ <div id="dlgPreview" closed="true" class="easyui-dialog" style="width: 750px; height: 750px;padding-left: 0px;" buttons="#dlg-buttons" title="添加"> <form id="PreviewHomeWork" method="post"> @*method="post" action="/TeaQueryHomework/AddHomeWork"*@ <div @*style="margin-top:20px;margin-left:auto ;margin-right :auto"*@> <a id="viewerPlaceHolder" style="width: 718px; height: 750px; display: block;"></a> </div> </form> </div>
js代码
//文档预览 function preview() { var selectRow = $("#dg").datagrid("getSelections") var name = selectRow[0].DocumentName; var result = name.split("."); documentName = result[0] + ".swf"; $("#dlgPreview").dialog('open'); //var path = "工作流研究的历程20160229012547.documentName" var target = "../../File/TeaFile/SWF/" + documentName; //var test = "../../Content/TeaFile/SWF/成绩管理.swf"; //var target = "../../Content/TeaFile/SWF/word上传验证.swf"; var fp = new FlexPaperViewer( '../../FlexPaper/FlexPaperViewer', /* 对应FlexPaperViewer.swf文件*/ 'viewerPlaceHolder', {config : { SwfFile: escape(target), Scale : 0.6, ZoomTransition : 'easeOut', ZoomTime : 0.5, ZoomInterval : 0.2, FitPageOnLoad : true, FitWidthOnLoad : true, FullScreenAsMaxWindow : false, ProgressiveLoading : false, MinZoomSize : 0.2, MaxZoomSize : 5, SearchMatchAll : false, InitViewMode : 'Portrait', ViewModeToolsVisible : true, ZoomToolsVisible : true, NavToolsVisible : true, CursorToolsVisible : true, SearchToolsVisible : true, localeChain: 'zh_CN' } }); $("#dlgPreview").dialog('open').dialog('setTitle', '预览'); }
上面就是对于这个Flexpaper控件的使用,我们在平时的时候应该多了解一些第三方控件,并不是说第三方控件
是好滴,而是说我们在实现需求的时候会多一些思路,这样就不会因为某个问题而焦头烂额,因为我们会采用多种方
法来实现,一条思路不同不至于导致系统不能继续。希望上面的分享能给大家带来帮助!!