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

目录
相关文章
|
Linux
Centos7安装nvidia-container-toolkit
Centos7安装nvidia-container-toolkit
6033 0
|
4月前
|
SQL 存储 机器学习/深度学习
基于 Dify + Hologres + QWen3 进行企业级大数据的处理和分析
在数字化时代,企业如何高效处理和分析海量数据成为提升竞争力的关键。本文介绍了基于 Dify 平台与 Hologres 数据仓库构建的企业级大数据处理与分析解决方案。Dify 作为开源大语言模型平台,助力快速开发生成式 AI 应用;Hologres 提供高性能实时数仓能力。两者结合,不仅提升了数据处理效率,还实现了智能化分析与灵活扩展,为企业提供精准决策支持,助力数字化转型。
682 2
基于 Dify + Hologres + QWen3 进行企业级大数据的处理和分析
|
Docker 容器
轻松搞定Docker!教你一键删除所有镜像!
轻松搞定Docker!教你一键删除所有镜像!
|
10月前
|
云安全 人工智能 供应链
阿里云安全白皮书发布:面向未来的安全能力与实践
阿里云发布2024年安全白皮书,聚焦数智化趋势下的安全新态势、安全治理框架的八大支柱及云上安全最佳实践。白皮书强调动态更新和实战验证,涵盖云平台自身安全、数据合规、身份管控等关键领域,并介绍淘宝上云的安全转型经验。通过红蓝对抗、自动化防御等手段,确保持续提升安全能力,帮助客户应对复杂多变的网络安全挑战。
1257 6
|
数据采集 人工智能
Dify 工作流分享-小红书文案生成器
本文介绍了生成小红书文案的具体流程和节点设置,包括输入主题、风格、字数,以及处理URL链接和直接主题的两种方式。最后,三金分享了实际测试效果和相关资源。
2104 1
Dify 工作流分享-小红书文案生成器
|
存储 机器学习/深度学习 计算机视觉
字节开源大模型量化新思路,2-bit量化模型精度齐平fp16
【5月更文挑战第25天】字节跳动研究团队提出新型量化方法decoupleQ,实现2-bit量化模型与fp16/bf16同等精度。该方法通过参数分解,将量化转化为数学优化问题,简化处理并提高硬件兼容性。decoupleQ在大型语音模型上验证了其2-bit量化效果,降低了存储和计算成本,适用于资源受限环境。论文开源,为量化技术发展带来新视角。
528 4
|
4天前
|
弹性计算 运维 搜索推荐
三翼鸟携手阿里云ECS g9i:智慧家庭场景的效能革命与未来生活新范式
三翼鸟是海尔智家旗下全球首个智慧家庭场景品牌,致力于提供覆盖衣、食、住、娱的一站式全场景解决方案。截至2025年,服务近1亿家庭,连接设备超5000万台。面对高并发、低延迟与稳定性挑战,全面升级为阿里云ECS g9i实例,实现连接能力提升40%、故障率下降90%、响应速度提升至120ms以内,成本降低20%,推动智慧家庭体验全面跃迁。
|
4天前
|
数据采集 人工智能 自然语言处理
3分钟采集134篇AI文章!深度解析如何通过云无影AgentBay实现25倍并发 + LlamaIndex智能推荐
结合阿里云无影 AgentBay 云端并发采集与 LlamaIndex 智能分析,3分钟高效抓取134篇 AI Agent 文章,实现 AI 推荐、智能问答与知识沉淀,打造从数据获取到价值提炼的完整闭环。
375 91
|
5天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~