Search code examples
asp.netvb.netpdfresponsepostback

Send response to a new window from a postback?


Example in my vb asp.net application

On postback

// ... do stuff
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/pdf"
Response.OutputStream.Write(fileData, 0, fileData.Length)
Response.End()

I have tried multiple ways and google doesn't offer me to much on my searchers regarding using script document.forms[0].target = "_blank"; and other techniques like creating a separate aspx page and storing the binary in a session then serving it up in the load function.

Thought maybe one of you can be my save n grace, thanks in advance

EDIT: Recently tried This guys solution without success.


Solution

  • It doesn't need to happen in postback. You can create the PDF and serve it from a generic handler (.ashx). On your ASPX page, you can open a new window with the URL pointing to the .ashx page, passing any necessary parameters via query string. Below is C#, but I think you'll get the idea.

    PDFCreator.ashx

    <%@ WebHandler Language="C#" Class="Handler" %>
    
    using System;
    using System.Web;
    
    public class Handler : IHttpHandler
    {
        public void ProcessRequest (HttpContext context)
        {
            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.ContentType = "application/pdf";
            var fileData = Database.GetFileData(); //this might be where you grab the query string parameters and pass them to your function that returns the PDF stream
            context.Response.OutputStream.Write(fileData, 0, fileData.Length);
            context.Response.End();
        }
    
        public bool IsReusable
        {
            get {return false;}
        }
    }
    

    ASPX page Javascript

    window.open("PDFCreator.ashx", "_blank");
    //or
    window.open('<%= ResolveClientUrl("~/PDFCreator.ashx") %>', '_blank');
    

    If you still want to have it occur after a postback with the generic handler technique, try this (again, C#):

    ClientScriptManager.RegisterStartupScript(this.GetType(), "openpdf", "window.open('PDFCreator.ashx', '_blank');", true); //You can also use ResolveClientUrl if necessary