Click or drag to resize
Pdf Library for .NET

Search for Text in PDF

The Pdf To Text Converter provided by SelectPdf, described in Extract Text from PDF section, provides one other very interesting feature: the possibility to search for text in a PDF document and retrieve the locations for all searched text occurrences.

This can be done using the Search method of the PdfToText class. The method will return an array of TextPosition objects.

Sample Code

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 test file
string filePdf = "document.pdf";

// settings
bool caseSensitive = false;
bool wholeWordsOnly = false;

// instantiate a pdf to text converter object
PdfToText pdfToText = new PdfToText();

// load PDF file
pdfToText.Load(filePdf);

// search for text and retrieve all found text positions
TextPosition[] positions = pdfToText.Search(searchText, 
    caseSensitive, wholeWordsOnly);

// open the existing PDF document in editing mode
PdfDocument doc = new PdfDocument(filePdf);

// highlight the found text in the existing PDF document
for (int i = 0; i < positions.Length; i++)
{
    TextPosition position = (TextPosition)positions[i];

    PdfPage page = doc.Pages[position.PageNumber - 1];

    PdfRectangleElement rect = new PdfRectangleElement(
        position.X, position.Y, position.Width, position.Height);
    rect.BackColor = new PdfColor(240, 240, 0);
    rect.Transparency = 30;
    page.Add(rect);
}

// save pdf document
doc.Save("Sample.pdf");

// close pdf document
doc.Close();
Every word with its position and font

GetWords returns every word of the document (the pages from StartPageNumber to EndPageNumber), and GetWords those of one page, as PdfTextWord objects: the text, the page, the rectangle the word covers - in points from the top-left corner of the page, as for the search above - the name and size of its font, the direction it runs in and whether a space follows it. This is what layout analysis and data extraction need: the words of a table column, the headings of a document by their font size, a value found next to its label.

The words come in reading order, as GetText reads the text: columns one after the other, a right-to-left word (Arabic, Hebrew) in the order it is read and a right-to-left line from its right end, vertical writing down its columns.

PdfToText pdfToText = new PdfToText();
pdfToText.Load("document.pdf");

// the headings of the first page: the words in a large font
foreach (PdfTextWord word in pdfToText.GetWords(1))
{
    if (word.FontSize >= 16)
        Console.WriteLine("{0} ({1} {2}pt) at {3}, {4}",
            word.Text, word.FontName, word.FontSize, word.X, word.Y);
}

pdfToText.Close();
See Also