Zig Requires Chilkat v11.7.0+
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// 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
const pdf = try chilkat.Pdf.init();
defer pdf.deinit();
pdf.loadFile("qa_data/pdf/invoice_template.pdf") catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
const json = try chilkat.JsonObject.init();
defer json.deinit();
const json_out = try chilkat.JsonObject.init();
defer json_out.deinit();
// 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("unusedPlaceholders", "keep") catch {};
// "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("labels[0].label", "Ref:") catch {};
json.updateString("labels[0].value", "B-7") catch {};
pdf.textReplace("check", json, json_out) catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
std.debug.print("default: {d} occurrence replaced\n", .{json_out.intOf("replacements[0].count")});
// The second occurrence only.
json.updateString("labels[0].occurrence", "2") catch {};
pdf.textReplace("check", json, json_out) catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
std.debug.print("occurrence 2: {d} occurrence replaced\n", .{json_out.intOf("replacements[0].count")});
// Every occurrence.
json.updateString("labels[0].occurrence", "all") catch {};
pdf.textReplace("apply", json, json_out) catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
std.debug.print("occurrence all: {d} occurrences replaced\n", .{json_out.intOf("replacements[0].count")});
pdf.writeFile("qa_output/invoice_refs.pdf") catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
// Sample output:
// default: 1 occurrence replaced
// occurrence 2: 1 occurrence replaced
// occurrence all: 2 occurrences replaced
}