SelectPdf for .NET - Search for Text in PDF - VB.NET / ASP.NET MVC 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:
Case Sensitive
Whole Words Only


Sample Code VB.NET



Imports SelectPdf

Namespace Controllers
    Public Class SearchPdfTextController
        Inherits Controller

        ' GET: SearchPdfText
        Function Index() As ActionResult
            Return View()
        End Function

        <HttpPost>
        Public Function SubmitAction(collection As FormCollection) As ActionResult
            ' the test file
            Dim filePdf As String = Server.MapPath("~/files/selectpdf.pdf")

            ' settings
            Dim caseSensitive As Boolean = collection("ChkCaseSensitive") = "on"
            Dim wholeWordsOnly As Boolean = collection("ChkWholeWordsOnly") = "on"

            ' 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(
                collection("TxtSearchText"), 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
            Dim pdf As Byte() = doc.Save()

            ' close pdf document
            doc.Close()

            ' return resulted pdf document
            Dim fileResult As FileResult = New FileContentResult(pdf, "application/pdf")
            fileResult.FileDownloadName = "Document.pdf"
            Return fileResult
        End Function
    End Class
End Namespace