using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.UI; using System.IO; using System.Data; using System.Text; using System.Reflection; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.pdf.draw; using iTextSharp.tool.xml.html; using iTextSharp.tool.xml.pipeline.html; using iTextSharp.tool.xml.pipeline.css; using iTextSharp.tool.xml.pipeline.end; using iTextSharp.tool.xml.parser; using iTextSharp.tool.xml; using iTextSharp.tool.xml.css; using iTextSharp.tool; namespace sbcLabSystem.Controllers { public class BaseController : Controller { /// /// 重写,Json方法,使之返回JsonNetResult类型 /// protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { return new JsonNetResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } protected void RenderToPDF(string html, string fontPath) { StringBuilder sb = new StringBuilder(); sb.Append(html); //sb.Append(new HtmlViewRenderer().RenderViewToString(this, action, viewData)); byte[] buffer = this.ConvertHtmlTextToPDF(sb.ToString(), fontPath); base.Response.Clear(); base.Response.ContentType = "application/pdf"; base.Response.Buffer = true; base.Response.BinaryWrite(buffer); base.Response.Flush(); } private byte[] ConvertHtmlTextToPDF(string htmlText, string fontPath) { if (string.IsNullOrEmpty(htmlText)) { htmlText = "

" + htmlText + "

"; } MemoryStream inp = new MemoryStream(Encoding.UTF8.GetBytes(htmlText)); Document document = new Document(); MemoryStream os = new MemoryStream(); PdfWriter instance = PdfWriter.GetInstance(document, os); document.Open(); ITagProcessorFactory htmlTagProcessorFactory = Tags.GetHtmlTagProcessorFactory(); htmlTagProcessorFactory.RemoveProcessor("hr"); htmlTagProcessorFactory.AddProcessor(new UnderlineHtmlTagProcessor(), new string[] { "underline" }); htmlTagProcessorFactory.AddProcessor(new HRHtmlTagProcessor(), new string[] { "hr" }); HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(new UnicodeFontFactory(fontPath))); hpc.SetTagFactory(htmlTagProcessorFactory); CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetCSS(Assembly.GetExecutingAssembly().GetManifestResourceStream("iTextSharp.tool.xml.css.default.css"))); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipeline next = new HtmlPipeline(hpc, new PdfWriterPipeline(document, instance)); CssResolverPipeline pipeline = new CssResolverPipeline(cssResolver, next); XMLWorker listener = new XMLWorker(pipeline, true); new XMLParser(listener).Parse(inp, Encoding.UTF8); listener.Close(); PdfDestination dest = new PdfDestination(0, 0f, document.PageSize.Height, 1f); PdfAction action = PdfAction.GotoLocalPage(1, dest, instance); instance.SetOpenAction(action); document.Close(); inp.Close(); os.Close(); return os.ToArray(); } } public class HRHtmlTagProcessor : AbstractTagProcessor { public override IList End(IWorkerContext ctx, Tag tag, IList currentContent) { float num = 1f; if (tag.Attributes.Count > 0) { num = ObjectParseExt.TryParseToSingle(tag.Attributes["size"], 1f); } LineSeparator separator = new LineSeparator { LineColor = new BaseColor(0, 0, 0), LineWidth = num, Percentage = 100f }; Chunk chunk = new Chunk(separator); return new List { chunk }; } } public class UnderlineHtmlTagProcessor : AbstractTagProcessor { public override IList Content(IWorkerContext ctx, Tag tag, string content) { int totalWidth = 1; if (tag.Attributes.Count > 0) { totalWidth = ObjectParseExt.TryParseToInt32(tag.Attributes["blank"], 1); } Chunk chunk = new Chunk(content.PadRight(totalWidth, ' ')); chunk.SetUnderline(0.1f, -2f); return new List { chunk }; } } public class UnicodeFontFactory : FontFactoryImp { private string fontPath; public UnicodeFontFactory(string fontPath) { this.fontPath = fontPath; } public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached) { return new Font(BaseFont.CreateFont(this.fontPath, "Identity-H", true), size, style, color); } } public static class ViewExtensions { /// /// 在控制器内获取指定视图生成后的HTML /// /// 当前控制器的上下文 /// 视图名称 /// 视图所需要的参数 /// 视图生成的HTML public static string GetViewHtml(this ControllerContext context, string viewName, Object param) { if (string.IsNullOrEmpty(viewName)) viewName = context.RouteData.GetRequiredString("action"); context.Controller.ViewData.Model = param; using (var sw = new StringWriter()) { ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName); var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw); try { viewResult.View.Render(viewContext, sw); } catch (Exception ex) { throw; } return sw.GetStringBuilder().ToString(); } } } }