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

Optimize a PDF Without Rewriting It (Incremental Update)

See more PDF Optimization Examples

Demonstrates the one combination of options that does not rewrite the file. With dropOldRevisions false and objectStreams "disable", the optimized objects are appended to the original bytes as an incremental update: every byte of the input is still there, byte for byte, followed by the changes and a new cross-reference section. That is what keeps an existing digital signature valid, and what lets a reader that has the original cached fetch only the tail. The file gets a little larger before it gets smaller, so this is for compatibility, not for size.

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();
    json.updateBool("dropOldRevisions", false) catch {};
    json.updateString("objectStreams", "disable") catch {};

    const json_out = try chilkat.JsonObject.init();
    defer json_out.deinit();
    pdf.optimize("optimize", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

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

    const fac = try chilkat.FileAccess.init();
    defer fac.deinit();
    std.debug.print("original: {d}\n", .{json_out.intOf("fileSize")});
    std.debug.print("written:  {d}\n", .{fac.fileSize("qa_output/watersense_incremental.pdf")});

    // Everything the optimizer changed is in the appended part; the original bytes are the start of the
    // new file.  Any other combination of options -- dropOldRevisions, or generated object streams --
    // rewrites the document instead.
    std.debug.print("bytesSaved: {d}\n", .{json_out.intOf("bytesSaved")});
}