Rust Requires Chilkat v11.7.0+
Rust
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 Rust Downloads
// 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 = chilkat::Pdf::new();
if pdf.load_file("qa_data/pdf/invoice_template.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();
// 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).
let _ = json.update_string("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.
let _ = json.update_string("labels[0].label", "Ref:");
let _ = json.update_string("labels[0].value", "B-7");
if pdf.text_replace("check", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("default: {} occurrence replaced", json_out.int_of("replacements[0].count"));
// The second occurrence only.
let _ = json.update_string("labels[0].occurrence", "2");
if pdf.text_replace("check", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("occurrence 2: {} occurrence replaced", json_out.int_of("replacements[0].count"));
// Every occurrence.
let _ = json.update_string("labels[0].occurrence", "all");
if pdf.text_replace("apply", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("occurrence all: {} occurrences replaced", json_out.int_of("replacements[0].count"));
if pdf.write_file("qa_output/invoice_refs.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
// Sample output:
// default: 1 occurrence replaced
// occurrence 2: 1 occurrence replaced
// occurrence all: 2 occurrences replaced