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

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

Html:

 <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'>window.open('" + 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.Response.WriteFile(filePath);
                this.Response.End();
            }
        }

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.

Return from Fiji Trip.

Went over to Fiji to visit my friends at Handy Finance Limited. Interesting to see how they are serving quality data and information out to the branches who are not connected directly to the head office. 🙂

Currently they are looking into growing their IT stack to support the ever increasing demand from the business and extending their product range significantly to cater for SME businesses as well. This is an exciting time for them and I wish them all the best in terms of success 🙂