2010-03-18 65 views
3

我正在使用ITextSharp生成pdf,然后将其保存到磁盘并使用Frame进行显示。从内存加载PDF ASP.Net

该框架有一个名为src的属性,我传递生成的文件名。

这一切工作正常,我想实现的是将生成的PDF文件传递到帧而不保存到磁盘。

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"; 

回答

2

我已经完成了你想要做的事情。你会想创建一个处理程序(.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; 
     } 
    } 
+0

+1,这里也一样。很好的工作 – 2010-03-18 04:58:31

+0

我想你会误解 - 他想写出生成的pdf,而不必将其写入磁盘。如果您可以将他的pdf生成代码合并到您的CreateImage函数中,以便在内存中创建pdf并一次写入响应,那么这将是一个很好的答案。 – patmortech 2010-03-18 05:45:19