PHP Requires Chilkat v11.7.0+
Chilkat2 PHP
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 PHP Downloads
<?php
use Chilkat2\JsonObject;
use Chilkat2\Pdf;
// 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
$pdf = new Pdf();
try {
$pdf->LoadFile('qa_data/pdf/three_receipts.pdf');
$json = new JsonObject();
$jsonOut = new JsonObject();
// 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.
$pdf->ExtractText('text', $json, $jsonOut);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
echo 'First total: ', $jsonOut->StringOf('text'), "\n";
// 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);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
$i = 0;
$count_i = $jsonOut->SizeOfArray('labelMatches');
while ($i < $count_i) {
$jsonOut->I = $i;
echo 'Page ', $jsonOut->IntOf('labelMatches[i].page'), ' total: ', $jsonOut->StringOf('labelMatches[i].text'), "\n";
$i = $i + 1;
}
// A number selects one occurrence: 2 is the second.
$json->UpdateInt('labelOccurrence', 2);
try {
$pdf->ExtractText('text', $json, $jsonOut);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
echo 'Second total: ', $jsonOut->StringOf('text'), "\n";
// 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);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
echo 'Receipt number on page 3: ', $jsonOut->StringOf('text'), "\n";
// 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