Find and Highlight Text Spanning Multiple Lines in PDF in C#/VB.NET

Some long text, such as a phrase or a sentence, is likely to span two or more lines. When we try to highlight it, it’s required to be able to detect the whole phrase or sentence even if it spans two lines. This article is going to introduce how to find and highlight long text spanning multiple lines by using Spire.PDF with C# and VB.NET.

Code Snippets

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


namespace FindAndHighlightText
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the sample PDF file
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\Hello.pdf");

            //find all matching strings from the first page, even if some of them span multiple lines
            PdfTextFind[] findResults = doc.Pages[0].FindText("Besides, Spire.PDF for JAVA can be applied easily to convert PDF to XPS, XPS to PDF, PDF to SVG, and PDF to PDF/A in high quality.", TextFindParameter.CrossLine).Finds;

            //highlight the first search result
            findResults[0].ApplyHighLight(Color.Yellow);

            //save to file
            doc.SaveToFile("output.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.General.Find
Imports System.Drawing


Namespace FindAndHighlightText
	Class Program
		Private Shared Sub Main(args As String())
			'load the sample PDF file
			Dim doc As New PdfDocument("C:\Users\Administrator\Desktop\Hello.pdf")

			'find all matching strings from the first page, even if some of them span multiple lines
			Dim findResults As PdfTextFind() = doc.Pages(0).FindText("Besides, Spire.PDF for JAVA can be applied easily to convert PDF to XPS, XPS to PDF, PDF to SVG, and PDF to PDF/A in high quality.", TextFindParameter.CrossLine).Finds

			'highlight the first search result
			findResults(0).ApplyHighLight(Color.Yellow)

			'save to file
			doc.SaveToFile("output.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace

Output

Find and Highlight Text Spanning Multiple Lines in PDF in C#, VB.NET