SelectPdf for .NET - Search for Text in PDF - VB.NET / ASP.NET Sample

This sample shows how to use SelectPdf PDF Library for .NET to search for text in a PDF document.
A new PDF will be created highlighting the text that has been found.

The sample uses the following (existing) test PDF:
Test PDF document

Text to Search:


Search Settings:


Sample Code Vb.Net



Public Class search_pdf_text
    Inherits System.Web.UI.Page

    Protected Sub BtnSubmit_Click(sender As Object, e As EventArgs)
        ' the test file
        Dim filePdf As String = Server.MapPath("~/files/selectpdf.pdf")

        ' settings
        Dim caseSensitive As Boolean = ChkCaseSensitive.Checked
        Dim wholeWordsOnly As Boolean = ChkWholeWordsOnly.Checked

        ' instantiate a pdf to text converter object
        Dim pdfToText As New PdfToText()

        ' load PDF file
        pdfToText.Load(filePdf)

        ' search for text and retrieve all found text positions
        Dim positions As TextPosition() = pdfToText.Search( _
            TxtSearchText.Text, caseSensitive, wholeWordsOnly)

        ' open the existing PDF document in editing mode
        Dim doc As New PdfDocument(filePdf)

        ' highlight the found text in the existing PDF document
        For i As Integer = 0 To positions.Length - 1
            Dim position As TextPosition = DirectCast(positions(i), TextPosition)

            Dim page As PdfPage = doc.Pages(position.PageNumber - 1)

            Dim rect As New PdfRectangleElement( _
                position.X, position.Y, position.Width, position.Height)
            rect.BackColor = New PdfColor(240, 240, 0)
            rect.Transparency = 30
            page.Add(rect)
        Next

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

        ' close pdf document
        doc.Close()

    End Sub
End Class