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

A PDF Label That Is Not on the Page: notFound or Ignore

See more PDF Text Replacement Examples

Demonstrates the "unmatchedValues" option. A label or placeholder given a value but not found on the selected pages is a problem with the reason notFound, which stops "apply", because a missing label usually means the wrong document or a typo in the label. With unmatchedValues "ignore" such a value is skipped and the rest is applied -- the right choice when one set of values serves several document layouts.

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_labels.pdf

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

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

//  "Tracking Number:" is not on this invoice.
oJson:UpdateString("labels[0].label", "Invoice Number:")
oJson:UpdateString("labels[0].value", "INV-2026-0500")
oJson:UpdateString("labels[1].label", "Tracking Number:")
oJson:UpdateString("labels[1].value", "1Z999AA10123456784")

nSuccess := oPdf:TextReplace("check", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

? "default: ok = " + Str(oJsonOut:BoolOf("ok")) + ', problem: "' + oJsonOut:StringOf("problems[0].label") + '" ' + oJsonOut:StringOf("problems[0].reason")

//  With "ignore", the label that is not there is skipped.
oJson:UpdateString("unmatchedValues", "ignore")
nSuccess := oPdf:TextReplace("apply", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

? "ignore: applied = " + Str(oJsonOut:BoolOf("applied")) + ", replacements: " + Str(oJsonOut:SizeOfArray("replacements"))

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

//  Sample output:

//  default: ok = false, problem: "Tracking Number:" notFound
//  ignore: applied = true, replacements: 1

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