ASP.Net Tip – Open a PDF File in a new window

To Open a PDF file in a new window in ASP.Net:


 <asp:LinkButton ID="lnkView" runat="server" Text="View File" OnClick="View" CommandArgument="MyFileName"></asp:LinkButton>

(The CommandArgument holds the name of the file – easier ways to pass a filename across, but this is just one of them..)

On the page where the above button is:

 protected void View(object sender, EventArgs e)
            string url = string.Format("ViewPDF.aspx?fileName={0}.pdf", (sender as LinkButton).CommandArgument);  //change name of aspx as required.
            string script = "<script type='text/javascript'>'" + url + "')</script>";
            this.ClientScript.RegisterStartupScript(this.GetType(), "script", script);

Set up a blank aspx page (in the example above, I called it ViewPDF.aspx) and in the page_load:

protected void Page_Load(object sender, EventArgs e)
            if (!this.IsPostBack)
                string filePath = Server.MapPath("~/Reports/") + Request.QueryString["fileName"];  //change path as required
                this.Response.ContentType = "application/pdf";
                this.Response.AppendHeader("Content-Disposition;", "attachment;filename=" + Request.QueryString["fileName"]);

This is just sample that takes a PDF filename via querystring and writes the file to display. You can play with the client script to change window properties as required.

One thought on “ASP.Net Tip – Open a PDF File in a new window

Leave a Reply to admin Cancel reply

Your email address will not be published. Required fields are marked *