Zig Requires Chilkat v11.7.0+
Zig
Shrink a PDF Losslessly
See more PDF Optimization Examples
Demonstrates the "optimize" operation with the default options, which is the lossless preset: nothing is resampled, recoloured or thrown away, so every page looks exactly as it did and all the text is still there. The changes are kept in memory until WriteFile (or WriteBd) is called. Note that the real saving is "fileSize" minus the size of the file that was written, not "bytesSaved": the rewrite also packs objects into object streams and writes a compact cross-reference stream, which belongs to no option.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 grand_canyon_hiking_guide.pdf
const pdf = try chilkat.Pdf.init();
defer pdf.deinit();
pdf.loadFile("qa_data/pdf/grand_canyon_hiking_guide.pdf") catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
// An empty JSON means the default options: every lossless optimization, object streams generated,
// old revisions dropped, deflate level 9.
const json = try chilkat.JsonObject.init();
defer json.deinit();
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;
};
// Nothing has been written yet. WriteFile (or WriteBd) produces the optimized PDF.
pdf.writeFile("qa_output/grand_canyon_optimized.pdf") catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
const fac = try chilkat.FileAccess.init();
defer fac.deinit();
const size_before = json_out.intOf("fileSize");
const size_after = fac.fileSize("qa_output/grand_canyon_optimized.pdf");
std.debug.print("before: {d}\n", .{size_before});
std.debug.print("after: {d}\n", .{size_after});
std.debug.print("saved: {d}\n", .{size_before - size_after});
// What the options themselves account for. This is smaller than the real saving above, because the
// rewrite's own gains (object streams, the cross-reference stream, the old sections left behind)
// belong to no single option.
std.debug.print("bytesSaved (options only): {d}\n", .{json_out.intOf("bytesSaved")});
}