Xbase++ Requires Chilkat v11.7.0+
Xbase++
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 Xbase++ Downloads
LOCAL nSuccess
LOCAL oPdf
LOCAL oJson
LOCAL oJsonOut
LOCAL i
LOCAL nCount_i
nSuccess := 0
// 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
oPdf := CreateObject("Chilkat.Pdf")
nSuccess := oPdf:LoadFile("qa_data/pdf/three_receipts.pdf")
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
RETURN
ENDIF
oJson := CreateObject("Chilkat.JsonObject")
oJsonOut := CreateObject("Chilkat.JsonObject")
// Each of the three pages is a receipt with a "Total:" line.
oJson:UpdateString("label", "Total")
oJson:UpdateString("labelValue", "right")
// By default only the first occurrence (in reading order) is used.
nSuccess := oPdf:ExtractText("text", oJson, oJsonOut)
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
? "First total: " + oJsonOut: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.
oJson:UpdateString("labelOccurrence", "all")
nSuccess := oPdf:ExtractText("text", oJson, oJsonOut)
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
i := 0
nCount_i := oJsonOut:SizeOfArray("labelMatches")
DO WHILE i < nCount_i
oJsonOut:I := i
? "Page " + Str(oJsonOut:IntOf("labelMatches[i].page")) + " total: " + oJsonOut:StringOf("labelMatches[i].text")
i := i + 1
ENDDO
// A number selects one occurrence: 2 is the second.
oJson:UpdateInt("labelOccurrence", 2)
nSuccess := oPdf:ExtractText("text", oJson, oJsonOut)
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
? "Second total: " + oJsonOut:StringOf("text")
// The occurrences are counted over the selected pages, so combining "pages" with the label
// is another way to pick one receipt:
oJson:UpdateString("labelOccurrence", "first")
oJson:UpdateString("pages", "3")
oJson:UpdateString("label", "Receipt No.")
nSuccess := oPdf:ExtractText("text", oJson, oJsonOut)
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
? "Receipt number on page 3: " + oJsonOut: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
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()