Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Write using ASP.NET into a new tab / window

I am using VB.NET to write a pdf file directly to the browser, which opens it right away replacing the content in a current window. I am trying to do is set a parameter which will cause binarywrite in a new tab / window.

' Set the appropriate ContentType.
Response.ContentType = "Application/pdf"

' Write file directly to browser.
Response.BinaryWrite(binaryData)
Response.End()

There is has to be something that I can set which will cause this to write binary PDF in a new window. Like Response.Target = "_blank" ?????


2 Answers

First, create an additional page named "PDF.aspx" or whatever you would like it called.

Second, in your page, store your "binarydata" variable in a session.

Session("binaryData") = binarydata

And tell it to go to your new page.

Response.Redirect("PDF.aspx")

Third, go to your PDF.aspx code behind page and put the following:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles       Me.Load
    Try
         Response.ContentType = "Application/pdf"
         Response.BinaryWrite(Session("binaryData"))
         Response.End()
    Catch ex As Exception
        Throw ex
    End Try
End Sub

That should produce the result you want. :)

like image 131
Jack Avatar answered Jun 05 '26 18:06

Jack


I know this is old but here's what I had done to achieve the OP was after. (Forgive me as this is C# but it shouldn't be too hard to convert it)

This is the original code that I had used that displayed the same behavior that you have described!

Response.ClearContent();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=" + docName);
Response.AddHeader("Content-Length", byteArray.Length.ToString());
Response.BinaryWrite(byteArray);
Response.End();

There are two key changes that I had to make to get this to work the way I wanted (Download the file as PDF, then open in a new tab when the user had clicked on that attachment.) and they are both on line 3 of the code above.

Change this

Response.AddHeader("Content-Disposition", "inline; filename=" + docName);

To this

Response.AddHeader("Content-Disposition", "attachment; filename=" + docName + ".pdf");

If you specify the Content-Disposition as "Inline" it will output the file content in your current window.

You need to change that disposition to "attachment" AND make sure your extension suffix is explicitly set to .pdf.

like image 21
Bonez024 Avatar answered Jun 05 '26 18:06

Bonez024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!