Swift Requires Chilkat v11.7.0+
Swift
Replace PDF Text on Selected Pages Only
See more PDF Text Replacement Examples
Demonstrates the "pages" option, which limits the search for placeholders and labels to the given pages: "all" (the default), "first", "last", "odd", "even", or a list such as "1,3,5-9". The two-page order confirmation carries the same "Status:" label on both pages; the status is changed on page 2 only, then on both pages.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 order_confirmation.pdf
let pdf = CkoPdf()!
success = pdf.loadFile(filePath: "qa_data/pdf/order_confirmation.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
let json = CkoJsonObject()!
let jsonOut = CkoJsonObject()!
// Both pages have "Status: Pending". With pages "2", only page 2 is searched.
json.updateString(jsonPath: "pages", value: "2")
json.updateString(jsonPath: "labels[0].label", value: "Status:")
json.updateString(jsonPath: "labels[0].value", value: "Shipped")
success = pdf.textReplace(op: "check", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("pages 2: found on page(s) \(jsonOut.string(of: "replacements[0].pages")!)")
// With every page searched, the default occurrence ("first") still replaces one -- the first in reading order.
json.updateString(jsonPath: "pages", value: "all")
success = pdf.textReplace(op: "check", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("pages all, first occurrence: found on page(s) \(jsonOut.string(of: "replacements[0].pages")!)")
// Every occurrence on every page.
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("pages all, every occurrence: \(jsonOut.int(of: "replacements[0].count").intValue) replaced on page(s) \(jsonOut.string(of: "replacements[0].pages")!)")
success = pdf.writeFile(path: "qa_output/order_shipped.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
// Sample output:
// pages 2: found on page(s) 2
// pages all, first occurrence: found on page(s) 1
// pages all, every occurrence: 2 replaced on page(s) 1,2
}