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

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 Zig Downloads

Zig
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 order_confirmation.pdf

    const pdf = try chilkat.Pdf.init();
    defer pdf.deinit();
    pdf.loadFile("qa_data/pdf/order_confirmation.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();

    // Both pages have "Status:   Pending".  With pages "2", only page 2 is searched.
    json.updateString("pages", "2") catch {};
    json.updateString("labels[0].label", "Status:") catch {};
    json.updateString("labels[0].value", "Shipped") catch {};
    pdf.textReplace("check", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("pages 2: found on page(s) {s}\n", .{try json_out.stringOf(alloc, "replacements[0].pages")});

    // With every page searched, the default occurrence ("first") still replaces one -- the first in reading order.
    json.updateString("pages", "all") catch {};
    pdf.textReplace("check", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("pages all, first occurrence: found on page(s) {s}\n", .{try json_out.stringOf(alloc, "replacements[0].pages")});

    // Every occurrence on every page.
    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("pages all, every occurrence: {d} replaced on page(s) {s}\n", .{ json_out.intOf("replacements[0].count"), try json_out.stringOf(alloc, "replacements[0].pages") });

    pdf.writeFile("qa_output/order_shipped.pdf") catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        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
}