Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET and Web » Embed PDFs into a Web Page with a VB Built Custom Control

Embed PDFs into a Web Page with a VB Built Custom Control

This article describes a simple approach to embedding and displaying PDF documents in a web page through the use of a simple ASP.NET 2.0 VB built custom server control.

Author Rank :
Page Views : 15596
Downloads : 706
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
EmbedPdf_VB.zip
 
 
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

This article describes a simple approach to embedding and displaying PDF documents in a web page through the use of a simple ASP.NET 2.0 VB built 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 the PDF but does not otherwise permit the developer to control the appearance of the page.



Figure 1:  Embedding and Displaying PDF Documents in a Web Page.



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, and 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 bottom 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 an added reference to System.Design which is necessary to support design time usage of the control.



Figure 3:  Solution Explorer with Both Projects Visible.
 

The Web Custom Control Project

Code:  ShowPdf.vb.

Within the web custom control project, there is a single custom control provided in this example. The example is entitled, "ShowPdf.vb". 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 and class declaration:

Imports System

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Text

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls 

 

<DefaultProperty("FilePath"), ToolboxData("<{0}:PdfViewVB runat=server></{0}:PdfViewVB>")> _

Public Class PdfViewVB

    Inherits WebControl

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"

 

    Dim mFilePath As String

 

#End Region 

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(GetType(System.Web.UI.Design.UrlEditor), 

    GetType(System.Drawing.Design.UITypeEditor))> _

    Public Property FilePath() As String

        Get

            Return mFilePath

        End Get

        Set(ByVal value As String)

            Dim tilde As Integer = -1

            tilde = value.IndexOf("~")

 

            If (tilde <> -1) Then

                mFilePath = value.Substring((tilde + 2)).Trim()

            Else

                mFilePath = value

            End If

        End Set

    End Property 

 

#End Region 

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 be 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 Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)

 

        Try

            Dim sb As 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>")

 

            writer.RenderBeginTag(HtmlTextWriterTag.Div)

            writer.Write(sb.ToString())

            writer.RenderEndTag()

 

        Catch ex As Exception

 

            ' 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

 

    End Sub

 

#End Region 

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 label used as a banner, a link button pointing directly to a PDF file, a few images for eyewash, 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 merely 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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Hide toolbars & navigation panel buttons by Mike On July 7, 2009
Hi great bit of code! I was wondering is there a way to by default hide the toolbars (F8 or right click 'Hide Toolbars' and also the navigation panel buttons on the left - right click 'Hide Navigation Panel Buttons'
Reply | Email | Modify 
Dynamically change the path property to newly created PDF by Janine On March 7, 2011
Love this code, I am using it with the .render function to produce a report and save dynamically as a pdf file. I would then like to preview this pdf file using the pdf control however if I set the path property to the filepath of the pdf it just remains blank rather than filling the control with the new pdf? Does anyone have an example of how to do this. Regards J
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.