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

What PDF Text Replacement Does Not Change: Metadata, Links, Form Fields

See more PDF Text Replacement Examples

TextReplace changes the page content only. A placeholder that also appears in the document's metadata (the Title, Author, Subject, Keywords, Creator or Producer), in a link's target URL, or in a form field's value is left as it is and reported in "notReplaced" with "where" saying which. The invoice template's title is "Invoice for {{customer}}" and its "View this invoice online" link points at a URL that holds {{customer}}.

Chilkat Xbase++ Downloads

Xbase++
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 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")
oJson:UpdateString("placeholders.customer", "Acme Corp")
//  (The other placeholders are left as they are for this example.)
oJson:UpdateString("unusedPlaceholders", "keep")

oJsonOut := CreateObject("Chilkat.JsonObject")
nSuccess := oPdf:TextReplace("apply", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

? "In the page content, customer was replaced " + Str(oJsonOut:IntOf("replacements[0].count")) + " times."

//  Where else the placeholder occurs, untouched:
i := 0
nCount_i := oJsonOut:SizeOfArray("notReplaced")
DO WHILE i < nCount_i
    oJsonOut:I := i
    ? "not replaced: {{" + oJsonOut:StringOf("notReplaced[i].field") + "}} in " + oJsonOut:StringOf("notReplaced[i].where")
    i := i + 1
ENDDO

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

//  Sample output:

//  In the page content, customer was replaced 2 times.
//  not replaced: {{customer}} in metadata
//  not replaced: {{customer}} in linkTarget

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