Delphi DLL Requires Chilkat v11.7.0+
Delphi DLL
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 Delphi DLL Downloads
var
success: Boolean;
pdf: HCkPdf;
json: HCkJsonObject;
jsonOut: HCkJsonObject;
i: Integer;
count_i: Integer;
begin
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
pdf := CkPdf_Create();
success := CkPdf_LoadFile(pdf,'qa_data/pdf/search_context.pdf');
if (success = False) then
begin
Memo1.Lines.Add(CkPdf__lastErrorText(pdf));
Exit;
end;
json := CkJsonObject_Create();
jsonOut := CkJsonObject_Create();
// The string to find.
CkJsonObject_UpdateString(json,'query','chilkat');
// The number of characters returned before and after each match. The default is 40.
CkJsonObject_UpdateInt(json,'context',30);
success := CkPdf_ExtractText(pdf,'search',json,jsonOut);
if (success = False) then
begin
Memo1.Lines.Add(CkPdf__lastErrorText(pdf));
Exit;
end;
// "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.
Memo1.Lines.Add('Matches: ' + IntToStr(CkJsonObject_IntOf(jsonOut,'count')));
i := 0;
count_i := CkJsonObject_SizeOfArray(jsonOut,'matches');
while i < count_i do
begin
CkJsonObject_putI(jsonOut,i);
Memo1.Lines.Add('page ' + IntToStr(CkJsonObject_IntOf(jsonOut,'matches[i].page')) + ': ...' + CkJsonObject__stringOf(jsonOut,'matches[i].before') + '[' + CkJsonObject__stringOf(jsonOut,'matches[i].text')
+ ']' + CkJsonObject__stringOf(jsonOut,'matches[i].after') + '...');
i := i + 1;
end;
// The search ignores case by default. Set caseSensitive to find only the exact spelling.
CkJsonObject_UpdateBool(json,'caseSensitive',True);
CkJsonObject_UpdateString(json,'query','Chilkat');
success := CkPdf_ExtractText(pdf,'search',json,jsonOut);
if (success = False) then
begin
Memo1.Lines.Add(CkPdf__lastErrorText(pdf));
Exit;
end;
Memo1.Lines.Add('Case-sensitive matches for Chilkat: ' + IntToStr(CkJsonObject_IntOf(jsonOut,'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
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkJsonObject_Dispose(jsonOut);