Text extraction
Extract page text, Markdown and positioned text blocks with NexPDF for C++, and retrieve passages for a language model.
License module
Text extraction, Markdown export and the offline assistant are part of the viewer module and work
without a key.
Plain text of a page
extract_page_text(page_index) returns the text of a page in reading order, with the layout
reconstructed into lines and paragraphs:
auto doc = nexpdf::Document::open("contract.pdf");
std::string text;
for (int32_t i = 0; i < doc.page_count(); ++i) {
if (i > 0) text += "\n\n";
text += doc.extract_page_text(i);
}The whole document as Markdown
extract_markdown() keeps headings, lists and tables, which makes it a good input for search
indexes and language models:
std::string markdown = doc.extract_markdown();Text blocks with positions
page_blocks_json(page_index) returns the text blocks of a page with their font size and rectangle
in PDF points:
#include <nlohmann/json.hpp> // an example; use your JSON library
for (const auto& block : nlohmann::json::parse(doc.page_blocks_json(0))) {
std::printf("%5.1fpt %s\n", block["size"].get<double>(), block["text"].get<std::string>().c_str());
}Each block has text, size, llx, lly, urx and ury.
Words with exact boxes
page_words_json(page_index, options_json) returns every word of a page with its exact box:
{"page","words":[{"text","bbox","quad","font","size","angle","line"}]}. bbox is
[llx, lly, urx, ury] and quad the four corners, so rotated text is boxed exactly.
{"glyphs":true} adds the box of every glyph.
auto words = nlohmann::json::parse(doc.page_words_json(0));
for (const auto& w : words["words"])
std::cout << w["line"] << " " << w["text"].get<std::string>() << " " << w["bbox"] << "\n";Text is returned in logical order, right-to-left and shaped scripts included.
Passages for a language model
ask_document(question, k, max_chars) ranks the passages of the document against a question,
offline, and returns the k best with a page-tagged context you can send to a language model.
max_chars 0 uses the default limit (200,000 characters).
auto result = nlohmann::json::parse(doc.ask_document("When does the contract end?", 5, 0));
for (const auto& p : result["passages"]) {
std::cout << p["page"] << " " << p["score"] << " " << p["text"] << "\n";
}
std::string prompt = "Answer from this document:\n" + result["context"].get<std::string>() +
"\n\nQuestion: When does the contract end?";Scanned documents
Pages that are images have no text to extract. Run OCR first to add a searchable text layer.
Related
- Search
- Conversion for HTML, JSON, XML and CSV output