Search
Find text in a PDF with NexPDF for C++ and get the page and rectangle of every match.
License module
Search is part of the viewer module and works without a key.
search_json(query) searches every page, case-insensitively, and returns a JSON array of hits:
#include <nexpdf.hpp>
#include <nlohmann/json.hpp> // an example; use your JSON library
namespace nexpdf = nexdevit::nexpdf;
auto doc = nexpdf::Document::open("contract.pdf");
auto hits = nlohmann::json::parse(doc.search_json("termination"));
for (const auto& hit : hits) {
std::cout << "page " << hit["page"].get<int>() + 1 << ": " << hit["context"].get<std::string>() << "\n";
}Each hit has:
| Field | Meaning |
|---|---|
page | 0-based page index |
context | The text around the match |
llx, lly, urx, ury | The rectangle of the match in PDF points |
Highlight every match
With the annotations module you can turn the hits into highlight annotations:
for (const auto& hit : hits) {
doc.add_annotation(hit["page"].get<size_t>(), "Highlight", "#FFD400", 1.0, "",
hit["llx"], hit["lly"], hit["urx"], hit["ury"]);
}
doc.save("highlighted.pdf");Redact every match
To remove the matches permanently instead, use redact_matches. See
Redaction.
Scanned documents
Search finds only real text. Run OCR on scanned pages first.