Saturday, February 4, 2012

How to show PDF in new browser without showing Download File dialog

Sometimes, we need to show user guideline or user manual as PDF format in browser and we want to generate the PDF file and show it in browser according to their user info often.This example illustrates the simple way to show the PDF in new/tab browser without showing "Download File dialog" as below.

PDF in browser
Create a .aspx page and add the following control to <form> tag. Its navigateUrl will redirect the "AppGenerator.ashx" page we created later (navigateUrl has querystring also that it just show how to pass the parameter and we don't use).

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AppGenerator.ashx?id=1" Target="_blank">PDF Generate</asp:HyperLink>

Creaet a Generic Handler AppGenerato.ashx here as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class AppGenerator : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
         try
        {
            int id;
            string Qs = context.Request.QueryString["id"];

            if (int.TryParse(Qs, out id))
            {
                //go here to handle the querystring parameter
                //you can get the byte array data from your DB depend on parameter.

                //I use the static file here for sample and added pdf file in "Files" folder.
                string fileName = "Tutorial.pdf";
                string fullPath = context.Request.MapPath("~/Files/" + fileName);//here is relative file path in your project.
                //get byte array from file.
                System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
                int byteLen = (int)fs.Length;
                byte[] file = new byte[byteLen];
                fs.Read(file, 0, byteLen);

                //context.Response.ContentType = "image/jpeg"; // for images
                //context.Response.ContentType = "image/gif";
                //context.Response.ContentType = "image/png";
                //context.Response.ContentType = "text/plain";  for .txt
                //context.Response.ContentType = "text/HTML";   for .html, .htm

                context.Response.ContentType = "application/pdf";
                context.Response.BinaryWrite(file);
                context.Response.Flush();
            }
        }
        catch (Exception ex)
        { }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
That's it. When you click on the  "PDF Generate" hyperlink, it show the PDF on new browser. I haven't found yet for showing MS Word or Excel in browser. If you've got, pls drop a line. :)

No comments:

Post a Comment