Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to assign PDF byte[] to Object Element?

I can open PDF in IFrame by changing the response content type but as we can open pdf in object tag as well then we may have a way to open pdf in object tag by assigning its byte[] to it. If anyone knows, please share.

user-image
Question added by Zubair Ali , Software Developer III , S&P Global
Date Posted: 2014/02/11

The data attribute of object tag accepts URL of the resource to be used by the object. So in order to open/view pdf in object tag you can create a new Webform (separate aspx page) in your project. Assign "application/pdf" to Response.ContentType and use Response.BinaryWrite for making use of the file buffer in byte array to show pdf in that Webform. Finally assigning the URL of this new Webform to the data attribute of object tag in the main Webform.

 

For better understandings let’s check this with a sample.

1)  Create a new ASP.NET empty web application project.

2) Add a new Webform name it as Webform1.aspx.

3) Add another Webform name it as Webform2.aspx.

4) Add an existing pdf file from your system to the project by Shift+Alt+A.

(Let’s suppose file name is MyPDFfile.pdf)

5) Add the following code snippet in the body of Webform1.aspx

<object id="pdfObj" type="application/pdf" data="WebForm2.aspx"></object>

6) Add the following code snippet in the Page_Load handler (in Webform2.aspx.cs ) of Webform2

string FilePath = Server.MapPath("~/MyPDFfile.pdf ");

                WebClient User = new WebClient();

                Byte[] FileBuffer = User.DownloadData(FilePath);

                if (FileBuffer != null)

                {

                    Response.ContentType = "application/pdf";

                    Response.AddHeader("content-length", FileBuffer.Length.ToString());

                    Response.BinaryWrite(FileBuffer);

                }

7) For above code to work fine we need to add some namespace reference. So add the following namespace references in the same Webform2.aspx.cs

using System.IO;

using System.Net;

 

The sample project is ready, we can run the Webform1 in browser to view the pdf file in the object tag of Webform1

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.