Search

Atalasoft Knowledge Base

HOWTO: Highlight a Search Query on a PDF Page

Administrator
DotImage

Background

Using the PDF Reader with Text Extract add-on to DotImage, you can easily search for words on a PDF Page, find their bounding boxes and use that to draw a highlight on the rasterized page. Here is the code to do that:

private void HighlightQueryOnPdfImagePage( string query, PdfTextPage pdfTextPage, AtalaImage pdfImagePage )
{
    if (pdfTextPage.CharCount > 0) 
    {
        Canvas c = new Canvas(pdfImagePage);

        using (PdfSearchResults pdfResults = pdfTextPage.Search(0, query, false, false)) {

            // each query can appear multiple times on a page
            pdfResults.FindNext();

            for (; pdfResults.HasResults; pdfResults.FindNext()) {
                // each result can have more than one box bounding it
                // (if it goes across lines of text)
                QuadrilateralF[] boxes = pdfTextPage.GetBoxes( pdfResults.StartIndex, pdfResults.CharCount );

                foreach (QuadrilateralF box in boxes) {
                    // draw highlights
                    Rectangle rect =
                        Rectangle.Round(
                            pdfTextPage.ConvertPdfUnitsToPixels(
                                box, pdfImagePage.Resolution
                            ).Bounds
                    );
                    c.DrawRectangle(rect, new SolidFill(Color.FromArgb(128, Color.Yellow)));
                }
            }
        }
    }
}

Given a filename of a PDF and a page number, you can call this function using the following code:

private AtalaImage HighlightQueryOnPdfPage( string query, string pdfFullPath, int pageNum )
{
    using (PdfTextDocument doc = new PdfTextDocument(pdfFullPath))
    {
        PdfTextPage pdfTextPage = doc.GetPage(pageNum);
        AtalaImage pdfImagePage =
              new AtalaImage(pdfFullPath, pageNum, null);
        HighlightQueryOnPdfImagePage( query, pdfTextPage, pdfImagePage );
        return pdfImagePage;
    }
}

Original Article

Q10304 - HOWTO: How to highlight a search query on a PDF page

Last Update

2026-11-04 - TD - (Code fencing and headings)

Details
Last Modified: 2 Weeks Ago
Last Modified By: Tananda
Type: HOWTO
Article not rated yet.
Article has been viewed 635 times.
Options
Also In This Category