Dart Requires Chilkat v11.7.0+
Dart
Get Every Occurrence of a Label in a PDF
See more PDF Text Extraction Examples
Demonstrates the "labelOccurrence" option. When the same label appears more than once (for example "Total:" on each of several receipts), "first" (the default) uses the first occurrence, "all" returns every occurrence with its page, and a number selects one occurrence.Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// The PDF used in this example (three receipts, one per page) is available at three_receipts.pdf
final pdf = CkPdf();
try {
pdf.loadFile('qa_data/pdf/three_receipts.pdf');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final json = CkJsonObject();
final jsonOut = CkJsonObject();
// Each of the three pages is a receipt with a "Total:" line.
json.updateString('label', 'Total');
json.updateString('labelValue', 'right');
// By default only the first occurrence (in reading order) is used.
try {
pdf.extractText('text', json, jsonOut);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('First total: ${jsonOut.stringOf('text')}');
// labelOccurrence "all" returns every occurrence. The "text" member holds the values joined
// by line breaks, and labelMatches has one entry per occurrence with its page.
json.updateString('labelOccurrence', 'all');
try {
pdf.extractText('text', json, jsonOut);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
var i = 0;
final countI = jsonOut.sizeOfArray('labelMatches');
while (i < countI) {
jsonOut.i = i;
print('Page ${jsonOut.intOf('labelMatches[i].page')} total: ${jsonOut.stringOf('labelMatches[i].text')}');
i++;
}
// A number selects one occurrence: 2 is the second.
json.updateInt('labelOccurrence', 2);
try {
pdf.extractText('text', json, jsonOut);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('Second total: ${jsonOut.stringOf('text')}');
// The occurrences are counted over the selected pages, so combining "pages" with the label
// is another way to pick one receipt:
json.updateString('labelOccurrence', 'first');
json.updateString('pages', '3');
json.updateString('label', 'Receipt No.');
try {
pdf.extractText('text', json, jsonOut);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('Receipt number on page 3: ${jsonOut.stringOf('text')}');
// Sample output:
// First total: $19.86
// Page 1 total: $19.86
// Page 2 total: $17.34
// Page 3 total: $23.62
// Second total: $17.34
// Receipt number on page 3: 1003
}