songjun
2024-09-05 a3302fda10ff21ed3700be462ad560163ca13f14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
    {
        /// <summary>
        /// 重写,Json方法,使之返回JsonNetResult类型
        /// </summary>
        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 = "<p>" + htmlText + "</p>";
            }
            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<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> 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<IElement> { chunk };
        }
    }
    public class UnderlineHtmlTagProcessor : AbstractTagProcessor
    {
        public override IList<IElement> 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<IElement> { 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
    {
        /// <summary>
        /// 在控制器内获取指定视图生成后的HTML
        /// </summary>
        /// <param name="context">当前控制器的上下文</param>
        /// <param name="viewName">视图名称</param>
        /// <param name="model">视图所需要的参数</param>
        /// <returns>视图生成的HTML</returns>
        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();
            }
        }
    }
}