SelectPdf for .NET - Get Web Elements Location in PDF - VB.NET / ASP.NET Sample

This sample shows how the html to pdf converter can locate certain web elements in the generated PDF using SelectPdf Pdf Library for .NET.

The web elements are defined using CSS selectors. For example, the selector for all the H1 elements is "H1", the selector for all the elements with the CSS class name 'myclass' is "*.myclass" and the selector for the elements with the id 'myid' is "*#myid". Read more about CSS selectors here.

The specified web elements will be marked/highlighted in PDF with a blue rectangle.


Web elements:

Sample Code Vb.Net

Imports System.Drawing

Public Class web_elements_location
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Load
        If Not IsPostBack Then
            TxtUrl.Text = ""
        End If
    End Sub

    Protected Sub BtnCreatePdf_Click(sender As Object, e As EventArgs)
        ' instantiate a html to pdf converter object
        Dim converter As New HtmlToPdf()

        ' set the css selectors for the web elements
        ' whose positions will be retrieved
        converter.Options.WebElementsMappingOptions.CssSelectors = _
            TxtElements.Text.Split(New Char() {","c})

        ' create a new pdf document converting an url
        Dim doc As PdfDocument = converter.ConvertUrl(TxtUrl.Text)

        ' get all web elements and mark/highlight them with a green rectangle
        For Each element As WebElement In _
            ' each web element has several rendering rectangles 
            ' (if it is displayed in more than 1 page)
            For Each webElementRectangle As WebElementPdfRectangle In _
                ' get the PDF page
                Dim page As PdfPage = doc.Pages(webElementRectangle.PageIndex)
                Dim rectangle As RectangleF = webElementRectangle.Rectangle

                ' highlight the HTML element
                Dim blueRectangle As New PdfRectangleElement( _
                    rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height)
                blueRectangle.ForeColor = Color.Blue


        ' save pdf document
        doc.Save(Response, False, "Sample.pdf")

        ' close pdf document
    End Sub
End Class