Opening a new Window Codebehind ASP.net
24,031
Solution 1
In order to do this you'll need to upload the PDF to a path in the application where it can be presented to the user, then register some javascript to open the PDF in a new window:
protected void Page_Load(object sender, EventArgs e)
{
byte[] buffer = null;
buffer = File.ReadAllBytes("C:\\myfile.pdf");
//save file to somewhere on server, for example in a folder called PDFs inside your application's root folder
string newFilepath = Server.MapPath("~/PDFs/uploadedPDF.pdf");
System.IO.FileStream savedPDF = File.Create(newFilepath);
file.Write(buffer, 0, buffer.Length);
file.Close();
//register some javascript to open the new window
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenPDFScript", "window.open(\"/PDFs/uploadedPDF.pdf\");", true);
}
Solution 2
There is no way to open a new window from a codebehind file. The link to the page on which this Page_Load event is being fired must have the target="_blank"
attribute to open it in a new window. For example:
<a href="DownloadPdf.aspx" target="_blank">Download PDF<a>
On a side note, if this is the only function of your ASPX file, you may want to consider using an HttpHandler instead.
Related videos on Youtube
Comments
-
fubo over 3 years
I have the following code:
protected void Page_Load(object sender, EventArgs e) { byte[] buffer = null; buffer = File.ReadAllBytes("C:\\myfile.pdf"); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length); HttpContext.Current.Response.End(); }
I want to open a second window for the pfd file beside the current page, where the pageload comes from.
-
fubo over 11 yearsok, i've been searching such a long time for a solution that i was expecting this answer :/ can i open my pdf in another existing frame? target="customtarget"
-
Andrew Lavers over 11 years@fubo Yep, you can set the target to the name of another frame or window.
-
fubo over 11 yearssmart solution but the files would be saved two times. so i think the solution with an handler would be the better one
-
Sean Airey over 11 yearsYeah they would, I'm kinda hoping that the PDFs aren't saved on the server in a place where they'd need to be moved or copied and that it was just a stand-in example. Perhaps he's getting the file from an asp:FileUpload control? Either way it gives some useful information, and registering scripts like this can be really useful sometimes =]
-
fubo over 11 yearsi solved it a little diferent way but the hint with the registered script was the key