Displaying Binary PDF file on a webpage using Generic Handler

Donald Symmons 3,066 Reputation points
2024-01-25T19:39:25.33+00:00

In my old Visual Studio, I was able to retrieve and display a pdf file saved in the database but in this latest visual studio the file does not display, any help in displaying it please? HTML

<div class="contentt">     
	<asp:Literal ID="ltEmbed" runat="server" />
</div>

C#

 protected void Page_Load(object sender, EventArgs e)
        {
            FileDisplay();
        }

 private void FileDisplay()
        {
            if (Request.QueryString["Id"] != null)
            {
                int id = Convert.ToInt32(Request.QueryString["Id"]);
                // Binding PDF file in Literal control
               string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"500px\" height=\"650px\"></object>";
               ltEmbed.Text = string.Format(embed, ResolveUrl("~/Handler1.ashx?Id="), id);
            }
        }

Generic Handler (Handler.ashx) In this Generic Handler, I noticed that it is Handler1.ashx.cs, but in the old version of Visual Studio, it is Handler1.ashx, I don't know if this could result to difference in code.

using System;
using System.Web;
using System.Data.SqlClient;

public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            int id = int.Parse(context.Request.QueryString["Id"]);
            byte[] bytes;
            string contentType;
            using (SqlConnection con = new SqlConnection())
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT Data, contentType FROM FileTable WHERE Id=@Id";
                    cmd.Parameters.AddWithValue("@Id", id);
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        contentType = sdr["contentType"].ToString();
                    }
                    con.Close();
                }
            }

             context.Response.Buffer = true;
            context.Response.Charset = "";
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.ContentType = "application/pdf";
            context.Response.BinaryWrite(bytes);
            context.Response.Flush();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
Developer technologies .NET Other
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

Accepted answer
  1. SurferOnWww 4,631 Reputation points
    2024-01-26T02:27:47.8433333+00:00

    Please use an iframe instead of the Literal control and set the url of HTTP handler to the src attribute of iframe.

    See sample below:

    HTTP Handler Handler4.ashx

    using System;
    using System.Web;
    
    namespace WebForms1
    {
        public class Handler4 : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.Cache.SetExpires(DateTime.Now.ToUniversalTime());
                context.Response.Cache.SetMaxAge(new TimeSpan(0, 0, 0, 0));
                context.Response.ContentType = "application/pdf";
    
                // byte array is obtained from the file in Files holder (not from DB)
                string filename = "JBL4312G.pdf";
                string path = context.Server.MapPath("~/Files") + "\\" + filename;
                byte[] data = System.IO.File.ReadAllBytes(path);
    
                context.Response.BinaryWrite(data);
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true" 
        CodeBehind="WebForm33.aspx.cs" Inherits="WebForms1.WebForm33" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <h1>pdf in iframe</h1>
            <iframe src="Handler4.ashx" width="500" height="500"></iframe>
        </form>    
    </body>
    </html>
    

    result

    enter image description here


1 additional answer

Sort by: Most helpful
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2024-01-26T01:58:28.04+00:00

    Hi @Donald Symmons,

    I found a workaround where you can change back to Handler1.ashx.

    1. add a Generic handler - Handler1.ashx in visual studio
    2. delete the cs file which auto-created.
    3. open ashx again,
      • remove CodeBehind="Handler1.ashx.cs"
      • add c# code below
      User's image Best regards,
      Lan Huang

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.