Unicode C++ Requires Chilkat v11.7.0+
Unicode C++
Search for Text in a PDF
See more PDF Text Extraction Examples
Demonstrates the "search" operation, which finds every occurrence of a string in a PDF and returns each match with its page number and the text around it. Matching ignores case unless caseSensitive is true.Chilkat Unicode C++ Downloads
#include <CkPdfW.h>
#include <CkJsonObjectW.h>
void ChilkatSample(void)
{
bool success = false;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// The three-page PDF used in this example is available at search_context.pdf
CkPdfW pdf;
success = pdf.LoadFile(L"qa_data/pdf/search_context.pdf");
if (success == false) {
wprintf(L"%s\n",pdf.lastErrorText());
return;
}
CkJsonObjectW json;
CkJsonObjectW jsonOut;
// The string to find.
json.UpdateString(L"query",L"chilkat");
// The number of characters returned before and after each match. The default is 40.
json.UpdateInt(L"context",30);
success = pdf.ExtractText(L"search",json,jsonOut);
if (success == false) {
wprintf(L"%s\n",pdf.lastErrorText());
return;
}
// "count" is the number of matches. Each match has the page, the matched text as it appears
// in the PDF, and the text before and after it.
wprintf(L"Matches: %d\n",jsonOut.IntOf(L"count"));
int i = 0;
int count_i = jsonOut.SizeOfArray(L"matches");
while (i < count_i) {
jsonOut.put_I(i);
wprintf(L"page %d: ...%s[%s]%s...\n",jsonOut.IntOf(L"matches[i].page"),jsonOut.stringOf(L"matches[i].before"),jsonOut.stringOf(L"matches[i].text"),jsonOut.stringOf(L"matches[i].after"));
i = i + 1;
}
// The search ignores case by default. Set caseSensitive to find only the exact spelling.
json.UpdateBool(L"caseSensitive",true);
json.UpdateString(L"query",L"Chilkat");
success = pdf.ExtractText(L"search",json,jsonOut);
if (success == false) {
wprintf(L"%s\n",pdf.lastErrorText());
return;
}
wprintf(L"Case-sensitive matches for Chilkat: %d\n",jsonOut.IntOf(L"count"));
// Sample output:
// Matches: 5
// page 1: ...[Chilkat] River Field Notes The Chilkat...
// page 1: ...Chilkat River Field Notes The [Chilkat] River runs for about fifty mi...
// page 2: ...DAY ONE: UPPER [CHILKAT] FLATS Clear and cold, minus e...
// page 2: ...he river is sometimes spelled [chilkat] in older records, and the val...
// page 3: ...y because the fish run on the [Chilkat] was thinning. Two tagged bird...
// Case-sensitive matches for Chilkat: 3
}