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

Audit a PDF First, Optimize Only If It Is Worth It

See more PDF Optimization Examples

Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.

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;
    };

    const file_size = json_out.intOf("fileSize");
    const estimated = json_out.intOf("estimatedSavings.total");
    std.debug.print("fileSize:  {d}\n", .{file_size});
    std.debug.print("estimated: {d}\n", .{estimated});

    // Only bother when at least a tenth of the file would go.
    if (estimated > (@divTrunc(file_size, 10))) {
        std.debug.print("Worth optimizing.\n", .{});
        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("bytesSaved: {d}\n", .{json_out.intOf("bytesSaved")});
    } else {
        std.debug.print("Already small enough; left as it is.\n", .{});
    }
}