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

Remove PDF Objects Nothing Refers To

See more PDF Optimization Examples

Demonstrates removeUnreferenced. When a page, an image or a whole section is replaced in an editor, the objects it used often stay in the file with nothing pointing at them any more. They are not old revisions -- they are in the current revision, simply unreachable -- so only a reachability walk from the document catalog finds them. In a publication assembled over several editing passes this is frequently the largest single saving.

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 watersense_accomplishments.pdf

    const pdf = try chilkat.Pdf.init();
    defer pdf.deinit();
    pdf.loadFile("qa_data/pdf/watersense_accomplishments.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();
    pdf.optimize("audit", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("fileSize: {d}\n", .{json_out.intOf("fileSize")});
    std.debug.print("removeUnreferenced would save: {d}\n", .{json_out.intOf("estimatedSavings.removeUnreferenced")});

    // Optimize with the defaults and see how many objects were actually dropped.
    pdf.optimize("optimize", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    pdf.writeFile("qa_output/watersense_optimized.pdf") catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("objects removed: {d}\n", .{json_out.intOf("actions.removeUnreferenced.count")});
    std.debug.print("bytes saved:     {d}\n", .{json_out.intOf("actions.removeUnreferenced.bytesSaved")});

    // Nothing a page needs is ever removed: the walk starts at the document catalog and follows every
    // reference, including the ones in annotations, the structure tree, named destinations and the
    // optional-content configuration.
    std.debug.print("pages after: {d}\n", .{pdf.getNumPages()});
}