Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.7.0+

Replace the Second (or Every) Occurrence of a Label in a PDF

See more PDF Text Replacement Examples

Demonstrates the "occurrence" member of a label entry. By default the first occurrence of a label, in reading order across the selected pages, is replaced; "occurrence" can be a number for the nth, or "all" for every occurrence. The invoice template has "Ref:" twice.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oPdf
LOCAL oJson
LOCAL oJsonOut

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 is available at invoice_template.pdf

oPdf := CreateObject("Chilkat.Pdf")
nSuccess := oPdf:LoadFile("qa_data/pdf/invoice_template.pdf")
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    RETURN
ENDIF

oJson := CreateObject("Chilkat.JsonObject")
oJsonOut := CreateObject("Chilkat.JsonObject")

//  This template's {{placeholders}} are not being filled here: "keep" leaves them as they are
//  (the default, "error", would refuse to apply while a placeholder on the page has no value).
oJson:UpdateString("unusedPlaceholders", "keep")

//  "Ref:" appears twice on the page (A-1 near the top, A-2 below the totals).
//  The default replaces the first occurrence only.
oJson:UpdateString("labels[0].label", "Ref:")
oJson:UpdateString("labels[0].value", "B-7")
nSuccess := oPdf:TextReplace("check", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

? "default: " + Str(oJsonOut:IntOf("replacements[0].count")) + " occurrence replaced"

//  The second occurrence only.
oJson:UpdateString("labels[0].occurrence", "2")
nSuccess := oPdf:TextReplace("check", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

? "occurrence 2: " + Str(oJsonOut:IntOf("replacements[0].count")) + " occurrence replaced"

//  Every occurrence.
oJson:UpdateString("labels[0].occurrence", "all")
nSuccess := oPdf:TextReplace("apply", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

? "occurrence all: " + Str(oJsonOut:IntOf("replacements[0].count")) + " occurrences replaced"

nSuccess := oPdf:WriteFile("qa_output/invoice_refs.pdf")
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

//  Sample output:

//  default: 1 occurrence replaced
//  occurrence 2: 1 occurrence replaced
//  occurrence all: 2 occurrences replaced

oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()