FlexPaper控件实现文档的上传和预览

简介: FlexPaper控件实现文档的上传和预览

引言


之前在一个项目中初识了这个控件,当时自己对这个东西非常高的好奇就尝试着做了一个Demo,最近在项目中遇到了这个需求,所以我向组长推荐了我的这中做法,在之前的系统中是将文档转换成html然后在前台中预览,这样有一个弊端就是在预览的时候会破坏文档原来的格式,感觉不符合全心全意为人民服务的思想,所以就采用了我的这种做法。下面给大家分享这个控件的用法;首先给大家展示一张效果图:


20160229161353688.png


和之前的预览相比最重要的就是不会破坏文档的样式,和上传时候的文档的上市一模一样;


一、上传并将文档转换成


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控件的使用,我们在平时的时候应该多了解一些第三方控件,并不是说第三方控件是好滴,而是说我们在实现需求的时候会多一些思路,这样就不会因为某个问题而焦头烂额,因为我们会采用多种方法来实现,一条思路不同不至于导致系统不能继续。希望上面的分享能给大家带来帮助!!

目录
相关文章
|
机器学习/深度学习 算法 决策智能
智能解决装箱问题:使用优化算法实现高效包装
装箱问题(Bin Packing Problem)是组合优化领域中的一个经典问题,主要涉及如何将一系列对象高效地装入有限数量的容器(或“箱”)中,同时满足特定的约束条件。这个问题的目标是最小化所需使用的箱子数量或者最大化箱子的装载效率,以减少空间或资源的浪费。
|
10月前
|
数据库 Python
15 分钟用 FastMCP 搭建你的第一个 MCP Server(附完整代码)
Model Context Protocol(MCP)是一个轻量开放标准,让LLM能统一、可靠地调用外部工具。无需手写解析逻辑或维护胶水代码。核心仅三概念:Server(暴露工具)、Tool(带装饰器的函数)、Client(调用方)。FastMCP框架15分钟即可上手,支持stdio快速测试、HTTP生产部署,真正实现“写一次,随处调用”。
1558 5
15 分钟用 FastMCP 搭建你的第一个 MCP Server(附完整代码)
|
C++ Windows
0xc0000142的解决方法?
以下是解决Windows系统0xc0000142错误的多种方法,按优先级排序:
|
NoSQL Java 关系型数据库
超全 Java 学习路线,帮你系统掌握编程的超详细 Java 学习路线
本文为超全Java学习路线,涵盖基础语法、面向对象编程、数据结构与算法、多线程、JVM原理、主流框架(如Spring Boot)、数据库(MySQL、Redis)及项目实战等内容,助力从零基础到企业级开发高手的进阶之路。
940 1
|
监控 API 开发者
淘宝获取商品详情券后价API接口
本文介绍如何通过淘宝开放平台API获取商品券后价,涵盖API调用流程、Python代码示例及注意事项。基于官方接口taobao.item.get,解析商品价格与优惠券信息,实现自动化比价与优惠监控,适合电商开发者参考。(238字)
|
缓存 JSON 前端开发
nestjs的拦截器 —— 面向切面编程(AOP)
nestjs的拦截器 —— 面向切面编程(AOP)
|
存储 人工智能 供应链
深入解析Agent实现“听懂→规划→执行”全流程的奥秘
AI智能体正从"回答问题"升级为"解决问题"——它能听懂"订明早京沪最早航班"并自动完成全流程预订。本文将剖析其三大核心能力:精准意图理解、动态工具调用和任务自主执行,通过电商索赔、家居控制等案例,展示如何让AI从"会说"到"会做"。掌握智能体技术,就是抢占下一代生产力制高点。
|
人工智能 运维 监控
阿里云携手神州灵云打造云内网络性能监测标杆 斩获中国信通院高质量数字化转型十大案例——金保信“云内网络可观测”方案树立云原生运维新范式
2025年,金保信社保卡有限公司联合阿里云与神州灵云申报的《云内网络性能可观测解决方案》入选高质量数字化转型典型案例。该方案基于阿里云飞天企业版,融合云原生引流技术和流量“染色”专利,解决云内运维难题,实现主动预警和精准观测,将故障排查时间从数小时缩短至15分钟,助力企业降本增效,形成可跨行业复制的数字化转型方法论。
1144 6
|
JSON Kubernetes API
手把手带你,在K8S集群中删除处于 "terminating" 状态命名空间。
手把手带你,在K8S集群中删除处于 "terminating" 状态命名空间。
|
数据可视化 搜索推荐 数据挖掘
数据挖掘实战 —— 抖音用户浏览行为数据分析与挖掘(一)
数据挖掘实战 —— 抖音用户浏览行为数据分析与挖掘(一)
2907 1