How to Get Coordinates of Desired Text in PDF in C#, VB.NET

Spire.PDF provides an easy and straightforward method called FindText to find a particular text in a page of a PDF document. After the specified text is found, we’re able to acquire the coordinate information by the Position property. Follow sections presents how to get coordinates of desired text in PDF using Spire.PDF.

Code Snippets:

Step 1: Initialize an instance of PdfDocument class and load a sample PDF file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"sample.pdf");

Step 2: Declare a variable of an array whose array type is PdfTextFind class, which represents a result of searching text in a PDF page.

PdfTextFind[] results = null;

Step 3: Find all results of searched text “Spire.PDF” in the PDF document and store the results in PdfTextFind[]. Traversal the results to get the specified text and acquire its coordinate information by the Position property.

foreach (PdfPageBase page in doc.Pages)
{
    results = page.FindText("Spire.PDF").Finds;
    foreach (PdfTextFind text in results)
    {
        PointF p = text.Position;
        Console.WriteLine(p);
    }
}

Result:

How to Get Coordinates of Desired Text in PDF in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.General.Find;
using System;
using System.Drawing;


namespace GetCoordinates
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"sample.pdf");

            PdfTextFind[] results = null;
            foreach (PdfPageBase page in doc.Pages)
            {
                results = page.FindText("C#").Finds;
                foreach (PdfTextFind text in results)
                {
                    PointF p = text.Position;
                    Console.WriteLine(p);
                }
            }
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.General.Find
Imports System.Drawing


Namespace GetCoordinates
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("sample.pdf")

			Dim results As PdfTextFind() = Nothing
			For Each page As PdfPageBase In doc.Pages
				results = page.FindText("C#").Finds
				For Each text As PdfTextFind In results
					Dim p As PointF = text.Position
					Console.WriteLine(p)
				Next
			Next
		End Sub
	End Class
End Namespace