Click here to Skip to main content
Click here to Skip to main content

Embed PDFs into a Web Page with a Custom Control

By , 27 Jan 2007
 

Introduction

This article describes an approach to embedding and displaying PDF documents in a web page through the use of a simple ASP.NET 2.0 custom server control. The approach indicated herein allows the developer the opportunity to control the web page content surrounding the embedded PDF; this is in contrast to linking directly to a PDF which uses the entire web page to display PDF but does not otherwise permit the developer to control the appearance of the page.

Figure 1. Embedding and Displaying PDFs

Figure 2. Linking Directly to a PDF

Getting Started

There are two solutions included with this download, one is web custom control library containing a single custom control used to render out the PDF, the other is a test web site used to display a PDF through the use of the control.

Figure 3 (below) shows the solution explorer for the project. The project appearing at the top of the solution is the test web site, it contains only a single web page (default) and it includes a PDF file included for testing purposes. The bottom project is the web custom control library with the single control included (ShowPdf). The references in the test web site are per the default configuration; the custom control library references include the default references but also include:

System.Design
Figure 3. Solution Explorer with Both Projects Visible

The Web Custom Control Project

Code: ShowPdf.cs

Within the web custom control project, there is a single custom control provided in this example. The example is entitled, ShowPdf.cs. The code for the project is very simple and should take very little time to implement. The control code starts out with the default imports:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PdfViewer
{
    [DefaultProperty("FilePath")]
    [ToolboxData("<{0}:ShowPdf
        runat="server"></{0}:ShowPdf>")]
    public class ShowPdf : WebControl
    {

Following the imports is the namespace and class declaration. The class contains a single property called FilePath, and the attributes for the class assign the default property attribute to point to the single added property. What this accomplishes is simple, when the control is dropped into a web page or selected by the developer at design time, the property editor will default to select this property. The toolbox data attribute is setup for a custom server control (runat=server).

After the class declaration, a declarations region was added and a single local member variable was defined and included within that region. The local member variable is used to retain the path to the PDF document loaded into the control.

#region
"Declarations"

    privatestring mFilePath;

#endregion

The next bit of code in the class is contained in a new region called Properties. Within this region is a single property entitled, FilePath. The property is used to provide public member access to the file path member variable. The attributes associated with this property indicate that the property is visible (Browsable) in the property editor, defines the property editor category under which to show the property in the editor, and provides the text used to describe the property which viewed in the property editor (Description). The editor defined specifies an association between this property and the URL Editor; when the developer using the control edits the property at design time, the URL editor will be displayed to allow the developer to navigate to and select a target file based using this editor. The System.Design reference is needed to support this portion of the design.

#region "Properties"

    [Category("Source File")]
    <Browsable(true)>
    [Description("Set path to source file.")]
    [Editor(typeof(System.Web.UI.Design.UrlEditor), 
        typeof(System.Drawing.Design.UITypeEditor))]

    public string FilePath
    {
        get
        {
            return mFilePath;
        }
          
        set
        {
            if (value == string.Empty)
            {
                mFilePath = string.Empty;
            }
            else
            {
                int tilde = -1;
                tilde = value.IndexOf('~');

                if (tilde != -1)
                {
                    mFilePath = value.Substring((tilde+ 2))
                                     .Trim();
                }
                else
                {
                    mFilePath = value;
                }
            }
        }
    }   //
end FilePath property

#endregion

Notice that in the set side of the property, the code is written to remove the tilde from in front of the file path if the tilde is present. If the tilde is left intact after setting the property to point to a file using the URL Editor, the tilde would otherwise be included in the HTML rendered to the page and the file would not found. It is necessary to strip this character from the file path in order to use the URL Editor to set this property at design time.

The last bit of code needed to finish the control is contained in a region called Rendering. This region contains a single method used to override the RenderContents method. Within RenderContents, a string builder is created and then populated with the HTML needed to render the control on a page. In this instance, the simplest way to display the PDF is through the use of an IFrame. Looking at the string builder, note that the IFrame contains the source property which points to the file path property added earlier in this project. Further, the width and height of the IFrame is set to equal the height and width of the control itself. After the string builder is populated, the content is dumped into a div. The entire control is constructed within a try catch block, if the try fails, the catch block will render out "Display PDF Control" into a box on the page in lieu of showing the control. When the control is first added to the page, it does not point to a file and so the try will fail, this prevents an error from occurring during that initial placement of the control.

#region "Rendering"

protected override void RenderContents(HtmlTextWriter
                                       writer)
{
    try
    {
        StringBuilder sb = newStringBuilder();

        sb.Append("<iframe src="
                  +FilePath.ToString() + " ");

        sb.Append("width=" +
                  Width.ToString() + " height=" + 
                  Height.ToString() + " ");

        sb.Append("<View PDF: <a
            href=" + FilePath.ToString() + "</a></p>
            ");

        sb.Append("</iframe>");
               
        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write(sb.ToString());

        writer.RenderEndTag();
    }
    catch
    {
               
        // with no properties set, this will render
        // "Display PDF Control" in 
        // a box on the page

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write("Display PDF Control");

        writer.RenderEndTag();     
    }  // end try-catch

}   //

end RenderContents

#endregion

The Test Web Project

Code: Default Page

The default page included in the web project is provided to serve as a test bed for the control. The page contains only a panel used as a banner, a hyperlink pointing directly to a PDF file, and the custom control with its file path property also pointing to the PDF. The PDF added to the web site content is also included in the web project. When this site is viewed, the control will display the PDF document in the defined area, selection of the hyperlink will open the same PDF into a separate window; I just included the hyperlink for comparison purposes.

Summary

This article demonstrates an approach that may be used to develop a custom control through which PDFs may be embedded into a web page. The purpose of the control is to allow the PDF to be included within a web page as opposed to the alternative of opening the PDF into a separate page where the PDF consumes the entire available display area and where the user cannot control the appearance of that page. Naturally, the code included in the custom control could be added directly into any page and the same effect could be achieved, however, by adding the code once into a custom control, the developer need only drop the control into the form and set the file path and dimensions to display PDFs without repeating the manual addition of the code each time it is needed.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

salysle
Software Developer (Senior)
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberbatime1 Feb '13 - 21:52 
Cool
QuestionPassword protected pdf filemembermaha_g15 May '12 - 22:42 
My files are password protected.how to pass password also not only filepath to the control?I dont want the window for entering password to appear
GeneralMy vote of 5membermanoj kumar choubey24 Apr '12 - 23:40 
Nice
GeneralShow pdf files from WSmemberMaverick20093 May '11 - 1:14 
Hi Saluse, interesting article and project.
Is it possible to use it in order to embed pdf files obtained from a web service call?
 
Thanks in advance
QuestionHow do you close the .pdf file?memberddaurio23 Nov '10 - 6:31 
I created a class and it all works great! My problem is I view the file, upload it, then I want to delete it. I get the file is in use. I cannot figure out how to close the viewer. Any help please! It one of those things that you mess with forever.
 
Thanks,
 
D Daurio
GeneralMy vote of 5memberDon_Hard11 Jul '10 - 2:56 
Very Good!!!
GeneralMy vote of 1membersrini547411 Aug '09 - 11:18 
does not work
QuestionHow to implement this custom control to my web pagememberphamtasmic6 Aug '09 - 12:03 
Hi Salysle,
I am new to user control. Your control is exactly what I need. However, I do not know how to bring your control to my web page. What are the steps?
Thanks so much,
James
Generalpdf opens in a seperate windowmemberivandevan3 Aug '09 - 4:50 
tried running this, opens the pdf always opens in a separate pdf application window. Not getting embeded into the web page iframe. any suggestions???
 
thanks.
QuestionHow to remove pdf Toolbar in browsermemberemperor17 May '08 - 20:31 
Hello there,
 
In the same application I need to remove/hide the acrobat toolbar within the browser and this has to be achieved programmatically. Can anyone help how to do this.
AnswerRe: How to remove pdf Toolbar in browser [modified]memberETollenaar11 Sep '08 - 0:29 
Just found this control. Also wanted to do the same thing.
 
Found a solution: after the filename enter "#toolbar=0"
Example: http://mysite/mydocument.pdf#toolbar=0
 
and to complete, see http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf
 
modified on Thursday, September 11, 2008 8:01 AM

Generalsimilar article in this sitemembersivabalank19 Dec '07 - 19:32 
http://www.beansoftware.com/ASP.NET-Tutorials/PDF-View-Custom-Control.aspx[^]
 
i have seen the similar article in the above link..????? OMG | :OMG: Suspicious | :suss:
QuestionHow to disable Select optionmemberkoonasaikumar2 Nov '07 - 5:47 
Hello

This control is very nice and usefull, but i require no to copy paste my pdf file so please help me how to disable selectable options of pdf viewer in my web page...
 
Hi, Iam Sai Kumar and iam recently completed my Mastering in Computer Science (MCA) in one the prestigious university in India...

QuestionPDF Does Not DisplaymemberPhantom20827 Oct '07 - 11:16 
I translated the C# code to VB and all seemed OK. However, when I run it I get the following in the iframe:
 
iframe src= file.pdf Height=350px Width=800px
 
where file.pdf is the full path and filename of the pdf and the height and width values are what I set in the behind code. The code was
 
ShowPdf1.FilePath= NewsletterPath
ShowPdf1.Height = 350
ShowPdf1.Width = 800
 
NewsletterPath was created by concatenating the pdf file name obtained from a GridView HyperLinkField to a directory in the website. However, the same thing happened when the FilePath was hard coded.
 
Has this happened to anyone else and, if so, what was the remedy?
 
Dick
AnswerRe: PDF Does Not DisplaymemberPhantom20827 Oct '07 - 12:42 
Well, I went ahead and used the C# dll and it works fine in a plain window but I was unable to get it to work with a master page. If anyone has had experience with this control and master pages, I would like to hear about it.
 
Looks like I need to work on translating C# to VB.
GeneralRe: PDF Does Not DisplaymemberPhantom20829 Oct '07 - 9:00 
The control works great in a contentplaceholder. Wink | ;)
GeneralExcellent Custom ControlmemberVenAliens18 Oct '07 - 10:00 
Thank you for this great article. It is good stuff. Wink | ;)
 
Everything can be solved with a smart chat!!!

QuestionPDF Viewermemberlevienigma13 Sep '07 - 10:39 
What version of Adobe did you use to develop ur dll?
 
vision without action is a daydream, action without vision is a nightmare.

GeneralProgrammatically Printmemberandrewkiss11 Sep '07 - 18:42 
Hi,
 
Great control. Is there a way to print the pdf programmatically?
 
Thanks
GeneralRe: Programmatically Printmemberandrewkiss11 Sep '07 - 23:53 
I've tried the following neither have worked.
 
** client side
function PrintPDF()
{
frames["pdfViewer"].focus();
frames["pdfViewer"].print();
}
 
<img src="images/print.gif" önclick="PrintPDF();" id="IMG1" />
 
** server side
ShowPdf.Focus();
System.Windows.Forms.SendKeys.SendWait("^(p)");
 
Server side will print the webpage, I think the focus is lost when print dialogue open.
Does anyone know how to suppress the print dialogue box?
 
Any help would be appreciated.
 
Thanks in advance

Generalchange iframe tag to object , and without ie messagebox to saving .pdf file after page loaded. [modified]memberDeemc31 Aug '07 - 14:11 
<code>
 

protected override void RenderContents(HtmlTextWriter writer)
            {
                  try
                  {
 

                        StringBuilder sb = new StringBuilder();
                    
                        //sb.Append("<iframe src=" + FilePath.ToString() + " ");
                        //sb.Append("width=" + Width.ToString() + " height=" + Height.ToString() + " ");
                        //sb.Append("<View PDF: <a href=" + FilePath.ToString() + "</a></p> ");
                        //sb.Append("</iframe>");
 
                        sb.Append("<OBJECT CLASSID=\"" + "clsid:CA8A9780-280D-11CF-A24D-444553540000\"" + " ");
                        sb.Append("width=" + Width.ToString() + " height=" + Height.ToString() + "> ");
                        sb.Append("<PARAM NAME=\"" + "SRC\"" + "value=\"" + FilePath.ToString() + "\" >");
                        sb.Append("<EMBED SRC=" + FilePath.ToString() + "");
                        sb.Append("width=" + Width.ToString() + " height=" + Height.ToString() + "> ");
                        sb.Append("<NOEMBED> Your browser does not support embedded PDF files. ");
                        sb.Append("</NOEMBED></EMBED></OBJECT>");
 
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.Write(sb.ToString());
                        writer.RenderEndTag();
                  }
                  catch
                  {
                        // with no properties set, this will render "Display PDF Control" in a
                        // a box on the page
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.Write("Display PDF Control");
                        writer.RenderEndTag();
                  }   // end try-catch
            }   // end RenderContents
 

</code>
Questionchanging path from gridviewmemberrenef798 Aug '07 - 3:13 
Hi,
I have a gridview were you can select a row, when the row is selected the control should refresh his path, every row is a different document, sou when you select a different row in the gridview another odf should be visible.
 
Is this possible and how?
 
Thanks!!
AnswerRe: changing path from gridviewmembermiyukihj28 Jun '11 - 22:53 
just assign "Filepath" in your handler function:
 
e.g
 
ShowPdf1.FilePath = "1.pdf";
QuestionQuery on Embed PDFs into a Web Page with a Custom ControlmemberGovardhana Reddy20 Jul '07 - 6:28 
Hi,
 
I saw this article in Code Project, it was very helpful for me to understand some of the concepts.
 
I had a query on this article, and thought u can clarify it, by default when we right click the mouse button on the custom control it pops up the menu, i needed to know can we some how block that menu from popping up.
 
It would be very helpful if u could take out some time and clarify it. and also let me know how to proceed.
 
My mail-id : apondu@gmail.com
 
Waiting for ur response.
 
Thanks for this article
 
Regards,
Govardhan
NewsI have transtled it to Chinese and pubulised it! [modified]member51aspx.com2 Jul '07 - 17:25 
This is a good forum!
 
I have transtled it to Chinese and pubulised it!You can dowload it from under URL!Big Grin | :-D
 
http://www.51aspx.com/CV/JumpyForum/[^]
 

-- modified at 0:01 Tuesday 3rd July, 2007
 
Do U know 51aspx.com?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 27 Jan 2007
Article Copyright 2007 by salysle
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid