类似百度文库源码
这段时间想弄一个类似于百度文库的程序,网上查了比较多的资料都没有合适,没办法只能自己动手,现把自己整理的与大家分享,希望能对大家能有帮助[实例下载,在文章最后]
1.下载必备工具
1>下载swftools[http://www.swftools.org/swftools-2013-04-09-1007.exe]安装
2>下载flexpager[https://flexpaper.googlecode.com/files/FlexPaper_2.1.5.zip]
2.创建MVC应用程序,在Scripts下新建"flexpager"文件夹,并将解压flexpager_2.1.5.zip文件夹中的"flexpaper.css","flexpaper.js","flexpaper_handlers.js","flexpaper_handlers_debug.js","FlexPaperViewer.swf"复制到刚创建的flexpager下,如下图:
然后打开flexpager.js,搜索window[instance] = flashembed,将下面的Src修改为_jsDirectory+"FlexPaperViewer.swf",expressInstall修改为:/Scripts/flexpager/expressinstall.swf,
修改web.config添加appSettings
<add key="SwfFilePath" value="D:\UploadFiles\Swf\" /> <add key="PdfFilePath" value="D:\UploadFiles\Pdf\" /> <add key="ExtractText" value=""C:\Program Files\SWFTools\swfstrings.exe" "{path.swf}{swffile}"" /> <add key="SplitPages" value=""C:\Program Files\SWFTools\pdf2swf.exe" "{path.pdf}{pdffile}" -o "{path.swf}{pdffile}%.swf" -f -T 9 -t -s storeallcharacters -s linknameurl" /> <add key="SingleDoc" value=""C:\Program Files\SWFTools\pdf2swf.exe" "{path.pdf}{pdffile}" -o "{path.swf}{pdffile}.swf" -f -T 9 -t -s storeallcharacters -s linknameurl" /> <add key="AllowCache" value="1"/>
SwfFilePath转换后的Swf文件存放位置,pdfFilePath上传PDF文件位置,ExtractText查找命令,splitpages生成swf命令,allowCache是否缓存
3.创建类库SwfConvert,将创建三个类,分别为:PdfCommon.cs,PdfToSwf.cs,SwfExtract.cs,如下图所示:
PdfCommon.cs[计算PDF页大小和设置缓存]:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Text.RegularExpressions;using System.Web;namespace SwfConvert{ public static class PdfCommon { public static Boolean validPdfParams(String pdfFilePath, String doc, String page) { return doc != null && !(doc.Length > 255 || page != null && page.Length > 255); } public static Boolean validSwfParams(String swfFilePath, String doc, String page) { return doc != null && !(doc.Length > 255 || page != null && page.Length > 255); } public static int getTotalPages(string fileName) { using (StreamReader sr = new StreamReader(File.OpenRead(fileName))) { Regex regex = new Regex(@"/Type\s*/Page[^s]"); MatchCollection matches = regex.Matches(sr.ReadToEnd()); return matches.Count; } } public static void setCacheHeaders(HttpContext context) { context.Response.AddHeader("Cache-Control", "private, max-age=10800, pre-check=10800"); context.Response.AddHeader("Pragma", "private"); context.Response.Cache.SetExpires(DateTime.Now.AddDays(2)); } }}
PdfToSwf.cs[PDF转Swf类]:
using System;using System.Web;using System.Configuration;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace SwfConvert{ public class PdfToSwf { public String ConvertToSwf(string doc, String page) { try { String output = ""; String pdfFilePath = ConfigurationManager.AppSettings["PdfFilePath"].ToString() + doc; String swfFilePath = ConfigurationManager.AppSettings["SwfFilePath"].ToString() + doc + page + ".swf"; String command = ""; if (page != null && page.Length > 0) command = ConfigurationManager.AppSettings["SplitPages"].ToString(); else command = ConfigurationManager.AppSettings["SingleDoc"].ToString(); command = command.Replace("{path.pdf}", ConfigurationManager.AppSettings["PdfFilePath"].ToString()); command = command.Replace("{path.swf}", ConfigurationManager.AppSettings["SwfFilePath"].ToString()); command = command.Replace("{pdffile}", doc); try { if (!this.isNotConverted(pdfFilePath, swfFilePath)) { return "[Converted]"; } } catch (Exception ex) { return "[" + ex.Message + "]"; } int return_var = 0; String pagecommand = ""; if (page != null && page.Length > 0) { pagecommand = command.Replace("%", page); pagecommand += " -p " + page; } System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = command.Substring(0, command.IndexOf(".exe") + 5); command = command.Substring(command.IndexOf(".exe") + 5); if (page != null && page.Length > 0) proc.StartInfo.Arguments = pagecommand.Substring(pagecommand.IndexOf(".exe") + 5); else proc.StartInfo.Arguments = command; proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; if (proc.Start()) { output = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); proc.Close(); return_var = 0; if (page != null && page.Length > 0) { System.Diagnostics.Process proc2 = new System.Diagnostics.Process(); proc2.StartInfo.FileName = proc.StartInfo.FileName; proc2.StartInfo.Arguments = command; proc2.StartInfo.UseShellExecute = true; proc2.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc2.StartInfo.CreateNoWindow = true; proc2.Start(); } } else return_var = -1; if (return_var == 0) return "[Converted]"; else return "Error converting document, make sure the conversion tool is installed and that correct user permissions are applied to the SWF Path directory"; } catch (Exception ex) { throw ex; } return ""; } public Boolean isNotConverted(String pdfFilePath, String swfFilePath) { if (!File.Exists(pdfFilePath)) throw new Exception("Document does not exist"); if (swfFilePath == null) throw new Exception("Document output file name not set"); else { if (!File.Exists(swfFilePath)) return true; else if (new System.IO.FileInfo(pdfFilePath).LastWriteTime > new System.IO.FileInfo(swfFilePath).LastWriteTime) return true; } return false; } }}
SwfExtract.cs[PDF内容查找类]:
using System;using System.Configuration;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace SwfConvert{ public class SwfExtract { public String FindText(String doc, String page, String searchterm, int numPages = -1) { try { String output = ""; String swfFilePath = ConfigurationManager.AppSettings["SwfFilePath"].ToString() + doc + page + ".swf"; String command = ConfigurationManager.AppSettings["ExtractText"].ToString() ; int pagecount = -1; if (numPages == -1) { pagecount = Directory.GetFiles(ConfigurationManager.AppSettings["SwfFilePath"].ToString(), doc + "*").Count(); } else { pagecount = numPages; } if (!PdfCommon.validSwfParams(swfFilePath, doc, page)) return "[Invalid Parameters]"; command = command.Replace("{path.swf}", ConfigurationManager.AppSettings["SwfFilePath"].ToString()); command = command.Replace("{swffile}", doc + page + ".swf"); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = command.Substring(0, command.IndexOf(".exe") + 5); proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.Arguments = command.Substring(command.IndexOf(".exe") + 5); if (proc.Start()) { output = proc.StandardOutput.ReadToEnd(); int strpos = output.ToLower().IndexOf(searchterm.ToLower()); if (strpos > 0) { return "[{\"page\":" + page + ", \"position\":" + strpos + "}]"; } else { int npage = Convert.ToInt32(page); if (npage < pagecount) { return this.FindText(doc, (npage + 1).ToString(), searchterm, pagecount); } else { return "[{\"page\":-1, \"position\":-1}]"; } } } else return "[Error Extracting]"; } catch (Exception ex) { return "[Error Extracting]"; } } }}
4.MVC应用程序引用SwfConvert类库,创建ReadPdfController,创建视图FileListWin.cshtml,如下图所示:
ReadPdfController.cs代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Configuration;using SwfConvert;using System.Data;using System.IO;namespace MvcReadPdfApp.Controllers{ public class ReadPdfController : Controller { // // GET: /ReadPdf/ public ActionResult Index(string doc) { ViewBag.PdfFilePath = ConfigurationManager.AppSettings["PdfFilePath"].ToString() + doc; ViewBag.SwfFilePath = ConfigurationManager.AppSettings["SwfFilePath"].ToString(); ViewBag.Numbers = PdfCommon.getTotalPages(ViewBag.PdfFilePath); ViewBag.Doc = doc; return View(); } /// <summary> /// 文件列表 /// </summary> /// <returns></returns> public ActionResult FileListWin() { ViewBag.FileList = FindFileList(); return View(); } /// <summary> /// 上传文件 /// </summary> /// <param name="file"></param> /// <returns></returns> [HttpPost] public ActionResult UploadFile(HttpPostedFileBase file) { var pdfFilePath = ConfigurationManager.AppSettings["PdfFilePath"].ToString() + Path.GetFileName(file.FileName); file.SaveAs(pdfFilePath); ViewBag.FileList = FindFileList(); return View("~/Views/ReadPdf/FileListWin.cshtml"); } private IList<string> FindFileList() { var list = new List<string>(); var pdfFilePath = ConfigurationManager.AppSettings["PdfFilePath"].ToString(); DirectoryInfo dir = new DirectoryInfo(pdfFilePath); foreach (FileInfo f in dir.GetFiles()) { var dict = new Dictionary<string, string>(); if (Path.GetExtension(f.Name).ToLower() == ".pdf") { list.Add(f.Name); } } return list; } }}
FileListWin.cshtml代码:
@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>FileListWin</title> <style type="text/css"> ul { margin:0px;padding:0px;} </style></head><body style="padding:50px;"> <div> @using (Html.BeginForm("UploadFile", "ReadPdf", FormMethod.Post, new { enctype = "multipart/form-data" })) { <span>选择上传文件:</span><input name="file" type="file" id="file" /> <span><input type="submit" name="Upload" value="Upload" /></span> } </div> <div> <ul> @foreach (var f in (ViewBag.FileList as List<string>)) { <li><a href="@Url.Action("Index","ReadPdf")?doc=@f" target="_blank">@f</a></li> } </ul> </div></body></html>
Index.cshtml代码:
@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link type="text/css" rel="Stylesheet" href="@Url.Content("~/Scripts/flexpager/flexpaper.css")" /> <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.min.js")"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/flexpager/flexpaper.js")"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/flexpager/flexpaper_handlers.js")"></script> <script type="text/javascript"> var numPages = "@ViewBag.Numbers"; var doc = '@ViewBag.Doc'; var swfFileUrl = escape('{@Url.Action("View.ashx","PdfServices")?doc=' + doc + '&page=[*,0],' + numPages + '}'); var searchServiceUrl = escape('@Url.Action("Containstext.ashx","PdfServices")?doc=' + doc + '&page=&searchterm=[searchterm]'); function getDocumentUrl(document) { var url = "{@Url.Action("View.ashx","PdfServices")?doc={doc}&format={format}&page=[*,0],{numPages}}"; url = url.replace("{doc}", document); url = url.replace("{numPages}", numPages); return url; } $(function () { $("#documentViewer").css("height", $(window).height()); $('#documentViewer').FlexPaperViewer( { config: { DOC: escape(getDocumentUrl("@ViewBag.Doc")), Scale: 0.6, ZoomTransition: 'easeOut', ZoomTime: 0.5, ZoomInterval: 0.2, FitPageOnLoad: true, FitWidthOnLoad: false, FullScreenAsMaxWindow: false, ProgressiveLoading: false, MinZoomSize: 0.2, MaxZoomSize: 5, SearchMatchAll: false, SearchServiceUrl: searchServiceUrl, InitViewMode: 'Portrait', ViewModeToolsVisible: true, ZoomToolsVisible: true, NavToolsVisible: true, CursorToolsVisible: true, SearchToolsVisible: true, cssDirectory: '@Url.Content("~/Scripts/flexpager/")', jsDirectory: '@Url.Content("~/Scripts/flexpager/")', JSONDataType: 'jsonp', localeChain: 'zh_CN' } } ); }); </script> <style type="text/css"> body {margin:0px; padding:0px;} #documentViewer {width:800px; margin:0 auto;} </style></head><body> <div id="documentViewer" class="flexpaper_viewer"></div></body></html>
5.更改路由:MVC4修改App_Start/RouteConfig.cs,MVC3修改Global.asax,修改如下
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "ReadPdf", action = "FileListWin", id = UrlParameter.Optional }, namespaces: new[] { "MvcReadPdfApp.Controllers" } );
实例代码,请点击这里
下面大家可以运行一下,看一下效果了: