Skip to Content
NexPDF

Search

Find text in a PDF with NexPDF for iOS (Swift) and get the page and rectangle of every match.

English

License module

Search is part of the viewer module and works without a key.

searchJson(query:) searches every page, case-insensitively, and returns a JSON array of hits:

import NexPdf

let doc = try NexPdfDocument.open(url: url)
let hits = NexPdf.json(try doc.searchJson(query: "termination")) as? [[String: Any]] ?? []
for hit in hits {
    let page = hit["page"] as? Int ?? 0
    print("page \(page + 1): \(hit["context"] ?? "")")
}

Each hit has:

FieldMeaning
page0-based page index
contextThe text around the match
llx, lly, urx, uryThe rectangle of the match in PDF points

To draw a hit on a rendered page, see the coordinate mapping in Rendering.

Highlight every match

With the annotations module you can turn the hits into highlight annotations:

func num(_ v: Any?) -> Double { (v as? NSNumber)?.doubleValue ?? 0 }

for hit in hits {
    try doc.addAnnotation(pageIndex: hit["page"] as? Int ?? 0, kind: "Highlight", colorHex: "#FFD400",
                          opacity: 1, contents: "",
                          llx: num(hit["llx"]), lly: num(hit["lly"]), urx: num(hit["urx"]), ury: num(hit["ury"]))
}
try doc.write(to: outputURL)

Redact every match

To remove the matches permanently instead, use redactMatches(query:mode:fillWhite:). See Redaction.

Scanned documents

Search finds only real text. Run OCR on scanned pages first.

On this page