【问题标题】:Load PDF from Memory ASP.Net从内存 ASP.Net 加载 PDF
【发布时间】:2010-03-18 04:35:15
【问题描述】:

我正在使用 ITextSharp 即时生成 pdf,然后将其保存到磁盘并使用 Frame 显示。

Frame 有一个名为 src 的属性,我在其中传递生成的文件名。

这一切都很好我想要实现的是将生成的 pdf 文件传递​​给 Frame 而不将其保存到磁盘。

HtmlToPdfBuilder builder = new HtmlToPdfBuilder(PageSize.LETTER);
HtmlPdfPage first = builder.AddPage();

//import an entire sheet
builder.ImportStylesheet(Request.PhysicalApplicationPath + "CSS\\Stylesheet.css");
string coupon = CreateCoupon();
first.AppendHtml(coupon);

byte[] file = builder.RenderPdf();
File.WriteAllBytes(Request.PhysicalApplicationPath+"final.pdf", file);
printable.Attributes["src"] = "final.pdf";

【问题讨论】:

    标签: c# asp.net pdf itextsharp


    【解决方案1】:

    我已经完成了你想做的事情。您需要创建一个处理程序 (.ashx)。创建 PDF 后,使用以下代码将其加载到处理程序中:

    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    public class MapHandler : IHttpHandler, IReadOnlySessionState 
    { 
    
        public void ProcessRequest(HttpContext context) { 
            CreateImage(context); 
        } 
    
        private void CreateImage(HttpContext context) { 
    
            string documentFullname = // Get full name of the PDF you want to display... 
    
            if (File.Exists(documentFullname)) { 
    
                byte[] buffer; 
    
                using (FileStream fileStream = new FileStream(documentFullname, FileMode.Open, FileAccess.Read, FileShare.Read)) 
                using (BinaryReader reader = new BinaryReader(fileStream)) { 
                    buffer = reader.ReadBytes((int)reader.BaseStream.Length); 
                } 
    
                context.Response.ContentType = "application/pdf"; 
                context.Response.AddHeader("Content-Length", buffer.Length.ToString()); 
                context.Response.BinaryWrite(buffer); 
                context.Response.End(); 
    
            } else { 
                context.Response.Write("Unable to find the document you requested."); 
            } 
        } 
    
        public bool IsReusable { 
            get { 
                return false; 
            } 
        } 
    

    【讨论】:

    • 我想你误解了——他想写出生成的 pdf 而不将其写入磁盘。如果您可以将他的 pdf 生成代码合并到您的 CreateImage 函数中,以便在内存中创建 pdf 并一次性写入响应,那么这将是一个很好的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多