Skip to content

PDF Merge — Zig source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

// pdf-merge — Zig port: classic-xref concatenation (polyglot showcase: Zig).
// Zig (0.17+), standard library only. Display source — part of CosmoDev's
// polyglot tool pages.
//
// Mirrored from the live Go twin at cli/pdf-merge/pdf-merge.go (the API
// ground truth — the two are kept in lock-step and share test vectors with
// src/lib/pdf-merge.test.ts): v1 scope merges classic xref-table PDFs only —
// cross-reference streams (/Type /XRef), object streams (/Type /ObjStm),
// hybrid-reference files (/XRefStm), and /Encrypt are rejected. Object
// headers are located by line-anchored scan ("N G obj" at the start of a
// line). The embedded main() driver is self-contained and exercises only
// the pure helpers.
const std = @import("std");

pub const ErrorKind = enum { invalid, encrypted, unsupported };

pub const empty_message = "Nothing to merge.";
pub const encrypted_message = "This PDF is password-protected. Unlock it first.";
pub const invalid_message = "Not a readable PDF file.";
pub const unsupported_message = "pdf-merge: unsupported PDF (v1 merges classic " ++
    "xref-table PDFs only — cross-reference streams, object streams, and " ++
    "encrypted files are not supported)";

/// The user-facing message for a rejected input, by error.
pub fn errorMessage(e: PdfError) []const u8 {
    return switch (e) {
        error.Empty => empty_message,
        error.Unsupported => unsupported_message,
        error.OutOfMemory => "out of memory",
        error.Invalid => invalid_message,
    };
}

/// The classification for a rejected input, by error (the TS ErrorKind).
pub fn errorKind(e: PdfError) ErrorKind {
    return switch (e) {
        error.Unsupported => .unsupported,
        error.Empty, error.OutOfMemory, error.Invalid => .invalid,
    };
}

/// Errors the merge can fail with (Zig error unions stand in for the TS
/// PdfToolError('encrypted'/'invalid') and the go twin's ErrUnsupported).
pub const PdfError = error{ Invalid, Unsupported, Empty, OutOfMemory };

/// Pure classifier — encrypted vs invalid, from the raw error message.
/// Case-insensitive scan for the same two keywords the TS regex
/// /encrypt|password/i looks for. null (no message) -> invalid.
pub fn classifyLoadError(msg: ?[]const u8) ErrorKind {
    const m = msg orelse return .invalid;
    if (std.ascii.findIgnoreCase(m, "encrypt") != null or
        std.ascii.findIgnoreCase(m, "password") != null) return .encrypted;
    return .invalid;
}

/// The mapped (kind, message) pair — the Zig twin of the TS mapError().
pub const MappedError = struct { kind: ErrorKind, message: []const u8 };

pub fn mapError(raw: []const u8) MappedError {
    const kind = classifyLoadError(raw);
    return .{
        .kind = kind,
        .message = if (kind == .encrypted) encrypted_message else invalid_message,
    };
}

const Int = struct { value: i64, len: usize };

/// Parse a decimal integer at the start of s; null when s does not begin
/// with digits.
fn parseIntAt(s: []const u8) ?Int {
    var i: usize = 0;
    var neg = false;
    if (s.len > 0 and (s[0] == '-' or s[0] == '+')) {
        neg = s[0] == '-';
        i = 1;
    }
    var v: i64 = 0;
    var any = false;
    while (i < s.len and isDigit(s[i])) : (i += 1) {
        v = v * 10 + @as(i64, s[i] - '0');
        any = true;
    }
    if (!any) return null;
    return .{ .value = if (neg) -v else v, .len = i };
}

fn isWs(c: u8) bool {
    return c == ' ' or c == '\t' or c == '\r' or c == '\n';
}

fn isDigit(c: u8) bool {
    return c >= '0' and c <= '9';
}

fn isDelim(b: u8) bool { // the go twin's isDelim: whitespace or '>'
    return isWs(b) or b == '>';
}

fn trimRightWs(s: []const u8) []const u8 {
    return std.mem.trimEnd(u8, s, " \t\r\n");
}

fn trimRightEol(s: []const u8) []const u8 {
    return std.mem.trimEnd(u8, s, "\r\n");
}

/// One copied source object. dict holds everything from the end of the
/// "N G obj" header to either "endobj" (plain object) or the "stream"
/// keyword (stream object); stream points into the caller's input bytes
/// (null for plain objects). new_num is the renumbered id from the merge.
const Object = struct {
    num: i64,
    gen: i64,
    dict: []const u8,
    stream: ?[]const u8 = null,
    new_num: i64 = 0,
};

/// One input document's scanned objects (in file order). The buffers are
/// allocated to the full header-count capacity; *_len are the live counts
/// (the incremental-update "last definition wins" rule can only shrink).
const ParsedInput = struct {
    objects: []Object,
    objects_len: usize = 0,
    pages: []i64, // obj nums whose dict is /Type /Page
    pages_len: usize = 0,

    fn objectsSlice(self: *const ParsedInput) []Object {
        return self.objects[0..self.objects_len];
    }

    fn pagesSlice(self: *const ParsedInput) []i64 {
        return self.pages[0..self.pages_len];
    }

    fn deinit(self: *const ParsedInput, gpa: std.mem.Allocator) void {
        gpa.free(self.objects);
        gpa.free(self.pages);
    }
};

const Header = struct { num: i64, gen: i64, len: usize };

/// Line-anchored object-header match: "N G obj" at the start of s, through
/// the end of the "obj" keyword.
fn lineHeader(s: []const u8) ?Header {
    const p1 = parseIntAt(s) orelse return null;
    var q = p1.len;
    while (q < s.len and isWs(s[q])) q += 1;
    const p2 = parseIntAt(s[q..]) orelse return null;
    q += p2.len;
    while (q < s.len and isWs(s[q])) q += 1;
    if (q + 3 > s.len or !std.mem.eql(u8, s[q .. q + 3], "obj")) return null;
    q += 3;
    return .{ .num = p1.value, .gen = p2.value, .len = q };
}

/// /Type /Page but NOT /Pages — the go twin's reTypePage \b trick, done by
/// requiring the character after "/Page" to be a non-identifier.
fn dictIsPage(dict: []const u8) bool {
    var i: usize = 0;
    while (std.mem.indexOfPos(u8, dict, i, "/Type")) |t| {
        var q = t + 5;
        while (q < dict.len and isWs(dict[q])) q += 1;
        if (q + 5 <= dict.len and std.mem.eql(u8, dict[q .. q + 5], "/Page")) {
            const after: u8 = if (q + 5 < dict.len) dict[q + 5] else 0;
            if (!isDigit(after) and !std.ascii.isAlphabetic(after)) return true;
        }
        i = t + 5;
    }
    return false;
}

/// Index of the dict-terminating "stream" keyword (whitespace/'>' before
/// it, EOL after it), or null for a plain object.
fn findStreamKeyword(body: []const u8) ?usize {
    var i: usize = 0;
    while (i + 6 <= body.len) : (i += 1) {
        if (!std.mem.eql(u8, body[i .. i + 6], "stream")) continue;
        if (i == 0 or !isDelim(body[i - 1])) continue;
        if (i + 6 < body.len and (body[i + 6] == '\n' or body[i + 6] == '\r')) return i;
    }
    return null;
}

/// Follow the last startxref offset: a classic PDF points at the "xref"
/// keyword; a PDF 1.5+ xref stream points at "N G obj" whose dict is
/// /Type /XRef — reject before scanning so stream-xref files fail fast.
fn checkXrefKind(pdf: []const u8) PdfError!void {
    const sx = std.mem.lastIndexOf(u8, pdf, "startxref") orelse return error.Invalid;
    var i = sx + "startxref".len;
    while (i < pdf.len and isWs(pdf[i])) i += 1;
    const parsed = parseIntAt(pdf[i..]) orelse return error.Invalid;
    if (parsed.value < 0) return error.Invalid;
    const off: usize = @intCast(parsed.value);
    if (off >= pdf.len) return error.Invalid;
    var t = off;
    while (t < pdf.len and isWs(pdf[t])) t += 1;
    if (t + 4 <= pdf.len and std.mem.eql(u8, pdf[t .. t + 4], "xref")) return;
    // cross-reference stream: the offset points at an object header
    var q = t;
    if (parseIntAt(pdf[q..])) |p1| {
        q += p1.len;
        while (q < pdf.len and isWs(pdf[q])) q += 1;
        if (parseIntAt(pdf[q..])) |p2| {
            q += p2.len;
            while (q < pdf.len and isWs(pdf[q])) q += 1;
            if (q + 3 <= pdf.len and std.mem.eql(u8, pdf[q .. q + 3], "obj"))
                return error.Unsupported;
        }
    }
    return error.Invalid;
}

/// Rejects encrypted files (/Encrypt) and hybrid-reference files
/// (/XRefStm) from the classic trailer dictionary.
fn checkTrailer(pdf: []const u8) PdfError!void {
    const tr = std.mem.lastIndexOf(u8, pdf, "trailer") orelse return;
    var trailer = pdf[tr..];
    if (std.mem.indexOf(u8, trailer, "startxref")) |end| trailer = trailer[0..end];
    if (std.mem.indexOf(u8, trailer, "/Encrypt") != null) return error.Unsupported;
    if (std.mem.indexOf(u8, trailer, "/XRefStm") != null) return error.Unsupported;
}

/// Scan one input PDF: reject unsupported features, then line-scan every
/// object header and split stream objects into dict + verbatim data.
fn parseInput(gpa: std.mem.Allocator, pdf: []const u8) PdfError!ParsedInput {
    if (std.mem.indexOf(u8, pdf, "%PDF-") == null) return error.Invalid;
    try checkXrefKind(pdf);
    try checkTrailer(pdf);

    // Count line-anchored headers, then fill pre-allocated arrays.
    var count: usize = 0;
    var pos: usize = 0;
    while (pos < pdf.len) : (pos += 1) {
        if (!(pos == 0 or pdf[pos - 1] == '\n')) continue;
        if (lineHeader(pdf[pos..]) != null) count += 1;
    }
    var in = ParsedInput{
        .objects = try gpa.alloc(Object, count),
        .pages = try gpa.alloc(i64, count),
    };
    errdefer in.deinit(gpa);

    pos = 0;
    while (pos < pdf.len) : (pos += 1) {
        if (!(pos == 0 or pdf[pos - 1] == '\n')) continue;
        const hdr = lineHeader(pdf[pos..]) orelse continue;
        var q = pos + hdr.len;
        while (q < pdf.len and isWs(pdf[q])) q += 1;
        const endobj = std.mem.indexOfPos(u8, pdf, q, "endobj") orelse return error.Invalid;
        const body = pdf[q..endobj];

        var dict: []const u8 = undefined;
        var stream: ?[]const u8 = null;
        if (findStreamKeyword(body)) |si| {
            dict = trimRightWs(body[0..si]);
            var data = body[si + 6 ..];
            // spec: the stream keyword is followed by CRLF or LF (not a lone CR)
            if (data.len >= 2 and data[0] == '\r' and data[1] == '\n') {
                data = data[2..];
            } else if (data.len >= 1 and data[0] == '\n') {
                data = data[1..];
            }
            if (std.mem.indexOf(u8, data, "endstream")) |ei|
                data = trimRightEol(data[0..ei]);
            stream = data;
        } else {
            dict = trimRightWs(body);
        }
        if (std.mem.indexOf(u8, dict, "/ObjStm") != null)
            return error.Unsupported; // page dicts may live inside object streams

        var found: ?usize = null;
        for (in.objects[0..in.objects_len], 0..) |*o, idx| {
            if (o.num == hdr.num) {
                found = idx;
                break;
            }
        }
        const obj = Object{ .num = hdr.num, .gen = hdr.gen, .dict = dict, .stream = stream };
        if (found) |idx| {
            in.objects[idx] = obj; // incremental update: last definition wins
        } else {
            in.objects[in.objects_len] = obj;
            in.objects_len += 1;
        }
        if (dictIsPage(dict)) {
            in.pages[in.pages_len] = hdr.num;
            in.pages_len += 1;
        }
    }
    if (in.objects_len == 0) return error.Invalid;
    return in;
}

fn lookupNewNum(in: *const ParsedInput, num: i64) ?i64 {
    for (in.objectsSlice()) |*o|
        if (o.num == num) return o.new_num;
    return null;
}

/// Map "N G R" indirect references in a dict body to the new numbering.
/// Stream data is never passed through here (content-stream text could
/// contain look-alike tokens). Unknown refs are copied verbatim.
fn appendRewritten(out: []u8, n: *usize, dict: []const u8, in: *const ParsedInput) !void {
    var i: usize = 0;
    while (i < dict.len) {
        if (isDigit(dict[i]) and (i == 0 or !isDigit(dict[i - 1]))) {
            if (parseIntAt(dict[i..])) |p1| {
                var q = i + p1.len;
                while (q < dict.len and isWs(dict[q])) q += 1;
                if (parseIntAt(dict[q..])) |p2| {
                    q += p2.len;
                    while (q < dict.len and isWs(dict[q])) q += 1;
                    const after: u8 = if (q + 1 < dict.len) dict[q + 1] else 0;
                    if (q < dict.len and dict[q] == 'R' and !isDigit(after) and
                        !std.ascii.isAlphabetic(after))
                    {
                        if (lookupNewNum(in, p1.value)) |new_num| {
                            try putf(out, n, "{d} 0 R", .{new_num});
                            i = q + 1;
                            continue;
                        }
                    }
                }
            }
        }
        try put(out, n, dict[i .. i + 1]);
        i += 1;
    }
}

// ---- output buffer helpers ----------------------------------------------

fn put(out: []u8, n: *usize, s: []const u8) PdfError!void {
    if (n.* + s.len > out.len) return error.OutOfMemory;
    @memcpy(out[n.* .. n.* + s.len], s);
    n.* += s.len;
}

fn putf(out: []u8, n: *usize, comptime fmt: []const u8, args: anytype) PdfError!void {
    const s = std.fmt.bufPrint(out[n.*..], fmt, args) catch return error.OutOfMemory;
    n.* += s.len;
}

/// MergePDFs: concatenate unencrypted classic xref-table PDFs into one new
/// document. All of every input's objects are copied (with renumbered ids
/// and rewritten indirect refs in dict bodies), then a fresh Catalog +
/// Pages tree is written whose /Kids are the copied page objects in input
/// order. The returned slice is the full output allocation; *out_len is the
/// document length. The Zig twin of mergePdfs() in src/lib/pdf-merge.ts.
pub fn mergePdfs(gpa: std.mem.Allocator, docs: []const []const u8, out_len: *usize) PdfError![]u8 {
    if (docs.len == 0) return error.Empty;
    const inputs = try gpa.alloc(ParsedInput, docs.len);
    defer gpa.free(inputs);
    var parsed_count: usize = 0;
    errdefer for (inputs[0..parsed_count]) |in| in.deinit(gpa);
    for (docs, 0..) |d, i| {
        inputs[i] = try parseInput(gpa, d);
        parsed_count = i + 1;
    }

    // Output bound: every input byte may be copied (plus rewritten refs can
    // only grow a few bytes per token), plus the rebuilt xref structures.
    var bound: usize = 512;
    for (docs) |d| bound += d.len * 2 + 64;
    const out = try gpa.alloc(u8, bound);
    errdefer gpa.free(out);
    var n: usize = 0;

    try put(out, &n, "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n");

    // Pass 1: assign new object ids across all inputs (sequential from 1).
    var next: i64 = 1;
    var total_pages: usize = 0;
    for (inputs) |*in| {
        for (in.objectsSlice()) |*o| {
            o.new_num = next;
            next += 1;
        }
        total_pages += in.pages_len;
    }
    const offsets = try gpa.alloc(usize, @intCast(next + 2)); // ids 1..next+1 (Catalog + Pages)
    defer gpa.free(offsets);
    @memset(offsets, 0);

    // Pass 2: write every copied object with renumbered refs in its dict.
    for (inputs) |*in| {
        for (in.objectsSlice()) |*o| {
            offsets[@intCast(o.new_num)] = n;
            try putf(out, &n, "{d} {d} obj\n", .{ o.new_num, o.gen });
            try appendRewritten(out, &n, o.dict, in);
            if (o.stream) |data| {
                try put(out, &n, "\nstream\n");
                try put(out, &n, data);
                try put(out, &n, "\nendstream\n");
            }
            try put(out, &n, "endobj\n");
        }
    }

    // Fresh Catalog + Pages tree over the copied page objects.
    const cat_id = next;
    const pages_id = next + 1;
    offsets[@intCast(cat_id)] = n;
    try putf(out, &n, "{d} 0 obj\n<< /Type /Catalog /Pages {d} 0 R >>\nendobj\n", .{ cat_id, pages_id });
    offsets[@intCast(pages_id)] = n;
    try put(out, &n, "<< /Type /Pages /Kids [ ");
    for (inputs) |*in|
        for (in.pagesSlice()) |num| {
            const nn = lookupNewNum(in, num) orelse continue;
            try putf(out, &n, "{d} 0 R ", .{nn});
        };
    try putf(out, &n, "] /Count {d} >>\nendobj\n", .{total_pages});

    // Rebuilt cross-reference table + trailer (ids are 1-based, contiguous).
    const size: usize = @intCast(pages_id + 1);
    const xref_off = n;
    try put(out, &n, "xref\n");
    try putf(out, &n, "0 {d}\n", .{size});
    try put(out, &n, "0000000000 65535 f \n");
    var num: usize = 1;
    while (num < size) : (num += 1)
        try putf(out, &n, "{d:0>10} 00000 n \n", .{offsets[num]});
    try put(out, &n, "trailer\n");
    try putf(out, &n, "<< /Size {d} /Root {d} 0 R >>\n", .{ size, cat_id });
    try putf(out, &n, "startxref\n{d}\n%%EOF\n", .{xref_off});

    for (inputs) |in| in.deinit(gpa);
    out_len.* = n;
    return out;
}

/// countPages: page count for UI display — parse + count /Type /Page
/// objects. The Zig twin of the TS countPages() helper.
pub fn countPages(gpa: std.mem.Allocator, pdf: []const u8) PdfError!usize {
    const in = try parseInput(gpa, pdf);
    defer in.deinit(gpa);
    return in.pages_len;
}

// ---- driver (self-contained; exercises the pure helpers only) ------------

/// Build a minimal classic-xref PDF with `pages` /Type /Page objects — the
/// driver's stand-in for the TS test's makeDoc() helper.
fn buildPdf(buf: []u8, pages: usize) []const u8 {
    var n: usize = 0;
    var offsets: [66]usize = undefined;
    put(buf, &n, "%PDF-1.4\n") catch unreachable;
    var next: usize = 1;
    offsets[next] = n;
    next += 1;
    put(buf, &n, "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n") catch unreachable;
    offsets[next] = n;
    next += 1;
    put(buf, &n, "2 0 obj\n<< /Type /Pages /Kids [ ") catch unreachable;
    var i: usize = 0;
    while (i < pages) : (i += 1)
        putf(buf, &n, "{d} 0 R ", .{3 + i}) catch unreachable;
    putf(buf, &n, "] /Count {d} >>\nendobj\n", .{pages}) catch unreachable;
    i = 0;
    while (i < pages) : (i += 1) {
        offsets[next] = n;
        next += 1;
        putf(buf, &n, "{d} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] >>\nendobj\n", .{3 + i}) catch unreachable;
    }
    const size = next;
    const xref_off = n;
    put(buf, &n, "xref\n") catch unreachable;
    putf(buf, &n, "0 {d}\n", .{size}) catch unreachable;
    put(buf, &n, "0000000000 65535 f \n") catch unreachable;
    num: {
        var k: usize = 1;
        while (k < size) : (k += 1) {
            putf(buf, &n, "{d:0>10} 00000 n \n", .{offsets[k]}) catch break :num;
        }
    }
    put(buf, &n, "trailer\n") catch unreachable;
    putf(buf, &n, "<< /Size {d} /Root 1 0 R >>\n", .{size}) catch unreachable;
    putf(buf, &n, "startxref\n{d}\n%%EOF\n", .{xref_off}) catch unreachable;
    return buf[0..n];
}

pub fn main() !void {
    var fba_buf: [1 << 20]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&fba_buf);
    const gpa = fba.allocator();

    // classifyLoadError — the src/lib/pdf-merge.test.ts vectors.
    const cases = [_]struct { msg: ?[]const u8, label: []const u8 }{
        .{ .msg = "Input document to PDFDocument.load is encrypted", .label = "encrypted" },
        .{ .msg = "wrong password for this document", .label = "password" },
        .{ .msg = "Failed to parse PDF", .label = "parse" },
        .{ .msg = null, .label = "null" },
    };
    for (cases) |c|
        std.debug.print("{s}-msg -> {s}\n", .{ c.label, @tagName(classifyLoadError(c.msg)) });

    // empty input throws invalid
    var out_len: usize = 0;
    if (mergePdfs(gpa, &.{}, &out_len)) |_| unreachable else |e|
        std.debug.print("empty-input -> {s}: {s}\n", .{ @tagName(errorKind(e)), errorMessage(e) });

    // mapError — encrypted classification propagates, message per kind
    const mapped_enc = mapError("Input document to PDFDocument.load is encrypted");
    std.debug.print("map-encrypted -> {s}: {s}\n", .{ @tagName(mapped_enc.kind), mapped_enc.message });
    const mapped_inv = mapError("Failed to parse PDF");
    std.debug.print("map-invalid -> {s}: {s}\n", .{ @tagName(mapped_inv.kind), mapped_inv.message });

    // classic-xref counting + merging on tiny generated docs
    var buf_a: [8192]u8 = undefined;
    var buf_b: [8192]u8 = undefined;
    const doc2 = buildPdf(&buf_a, 2);
    const doc3 = buildPdf(&buf_b, 3);
    std.debug.print("classic-xref pages: {d}\n", .{try countPages(gpa, doc2)});
    const docs = [_][]const u8{ doc2, doc3 };
    const merged = try mergePdfs(gpa, &docs, &out_len);
    defer gpa.free(merged);
    std.debug.print("merged pages: {d}\n", .{try countPages(gpa, merged[0..out_len])});

    // cross-reference stream -> unsupported
    if (countPages(gpa, "%PDF-1.4\n12 0 obj\n<< /Type /XRef /Size 5 /W [ 1 2 2 ] >>\nendobj\n" ++
        "startxref\n9\n%%EOF\n")) |_| unreachable
    else |e| std.debug.print("stream-xref -> {s}\n", .{@tagName(errorKind(e))});

    // /Encrypt trailer -> unsupported
    if (countPages(gpa, "%PDF-1.4\nxref\n0 1\n0000000000 65535 f \ntrailer\n" ++
        "<< /Size 2 /Root 1 0 R /Encrypt 9 0 R >>\nstartxref\n9\n%%EOF\n")) |_| unreachable
    else |e| std.debug.print("encrypt-trailer -> {s}\n", .{@tagName(errorKind(e))});

    // garbage bytes -> invalid
    if (countPages(gpa, "\x01\x02\x03")) |_| unreachable
    else |e| std.debug.print("garbage -> {s}\n", .{@tagName(errorKind(e))});
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →