Swift Requires Chilkat v11.7.0+
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// 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
let pdf = CkoPdf()!
success = pdf.loadFile(filePath: "qa_data/pdf/invoice_template.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
let json = CkoJsonObject()!
let jsonOut = CkoJsonObject()!
// 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).
json.updateString(jsonPath: "unusedPlaceholders", value: "keep")
// "Ref:" appears twice on the page (A-1 near the top, A-2 below the totals).
// The default replaces the first occurrence only.
json.updateString(jsonPath: "labels[0].label", value: "Ref:")
json.updateString(jsonPath: "labels[0].value", value: "B-7")
success = pdf.textReplace(op: "check", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("default: \(jsonOut.int(of: "replacements[0].count").intValue) occurrence replaced")
// The second occurrence only.
json.updateString(jsonPath: "labels[0].occurrence", value: "2")
success = pdf.textReplace(op: "check", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("occurrence 2: \(jsonOut.int(of: "replacements[0].count").intValue) occurrence replaced")
// Every occurrence.
json.updateString(jsonPath: "labels[0].occurrence", value: "all")
success = pdf.textReplace(op: "apply", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("occurrence all: \(jsonOut.int(of: "replacements[0].count").intValue) occurrences replaced")
success = pdf.writeFile(path: "qa_output/invoice_refs.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
// Sample output:
// default: 1 occurrence replaced
// occurrence 2: 1 occurrence replaced
// occurrence all: 2 occurrences replaced
}