Skip to content

PDF Merge — C source

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

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

/* pdf-merge — C port: classic-xref concatenation (polyglot showcase: C).
   C11, stdlib only. Display source — part of CosmoDev's polyglot tool pages.

   Mirrors the self-contained classic-xref approach of the live Go twin at
   cli/pdf-merge/pdf-merge.go (API ground truth — the two are kept in
   lock-step and share test vectors with src/lib/pdf-merge.test.ts):
   inputs using PDF 1.5+ cross-reference streams (/Type /XRef), object
   streams (/Type /ObjStm), hybrid-reference files (/XRefStm), or /Encrypt
   are rejected as unsupported; everything else must be a classic
   xref-table PDF. 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. */
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {
    PDF_OK = 0,
    PDF_ERROR_INVALID,    /* not a readable PDF file */
    PDF_ERROR_ENCRYPTED,  /* password-protected (raw-message classification) */
    PDF_ERROR_UNSUPPORTED /* v1 merges classic xref-table PDFs only */
} pdf_error_kind;

#define MSG_EMPTY     "Nothing to merge."
#define MSG_ENCRYPTED "This PDF is password-protected. Unlock it first."
#define MSG_INVALID   "Not a readable PDF file."

static const char *unsupported_message(void) {
    return "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 kind. */
static const char *error_message(pdf_error_kind kind) {
    switch (kind) {
    case PDF_ERROR_UNSUPPORTED:  return unsupported_message();
    case PDF_ERROR_ENCRYPTED:    return MSG_ENCRYPTED;
    case PDF_ERROR_INVALID:      return MSG_INVALID;
    default:                     return "";
    }
}

static const char *kind_name(pdf_error_kind kind) {
    switch (kind) {
    case PDF_ERROR_ENCRYPTED:   return "encrypted";
    case PDF_ERROR_UNSUPPORTED: return "unsupported";
    default:                    return "invalid";
    }
}

static int ilower_eq(const char *p, const char *lower, size_t n) {
    for (size_t i = 0; i < n; i++)
        if (tolower((unsigned char)p[i]) != lower[i]) return 0;
    return 1;
}

/* 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. */
static pdf_error_kind classify_load_error(const char *msg) {
    if (msg) {
        size_t n = strlen(msg);
        for (size_t i = 0; i + 7 <= n; i++)
            if (ilower_eq(msg + i, "encrypt", 7)) return PDF_ERROR_ENCRYPTED;
        for (size_t i = 0; i + 8 <= n; i++)
            if (ilower_eq(msg + i, "password", 8)) return PDF_ERROR_ENCRYPTED;
    }
    return PDF_ERROR_INVALID;
}

/* Map a raw load failure to the user-facing (kind, message) pair — the C
   twin of the TS mapError(). */
static pdf_error_kind map_error(const char *raw, const char **user_msg) {
    pdf_error_kind kind = classify_load_error(raw);
    *user_msg = kind == PDF_ERROR_ENCRYPTED ? MSG_ENCRYPTED : MSG_INVALID;
    return kind;
}

/* ---- growable byte buffer -------------------------------------------- */

typedef struct {
    char *data;
    size_t len, cap;
} buf;

static void buf_append(buf *b, const void *p, size_t n) {
    if (b->len + n > b->cap) {
        size_t cap = b->cap ? b->cap * 2 : 256;
        while (cap < b->len + n) cap *= 2;
        char *grown = realloc(b->data, cap);
        if (!grown) {
            free(b->data);
            exit(1); /* display code: out-of-memory aborts */
        }
        b->data = grown;
        b->cap = cap;
    }
    if (n) memcpy(b->data + b->len, p, n);
    b->len += n;
}

static void buf_str(buf *b, const char *s) { buf_append(b, s, strlen(s)); }

static void buf_fmt(buf *b, const char *fmt, ...) {
    char tmp[256];
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(tmp, sizeof tmp, fmt, ap);
    va_end(ap);
    if (n > 0) buf_append(b, tmp, (size_t)n);
}

/* ---- byte-scan helpers (stdlib C has no regex) ------------------------ */

/* First occurrence of needle in hay[0..haylen), or NULL. */
static const char *find_mem(const char *hay, size_t haylen, const char *needle) {
    size_t n = strlen(needle);
    if (n == 0 || haylen < n) return n == 0 ? hay : NULL;
    for (size_t i = 0; i + n <= haylen; i++)
        if (hay[i] == needle[0] && memcmp(hay + i, needle, n) == 0) return hay + i;
    return NULL;
}

/* Last occurrence of needle in hay[0..haylen), or NULL. */
static const char *rfind_mem(const char *hay, size_t haylen, const char *needle) {
    size_t n = strlen(needle);
    if (haylen < n) return NULL;
    for (size_t i = haylen - n + 1; i-- > 0;)
        if (hay[i] == needle[0] && memcmp(hay + i, needle, n) == 0) return hay + i;
    return NULL;
}

static int is_ws(char c) {
    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}

static int is_delim(char b) { /* the go twin's isDelim: EOL or '>' */
    return is_ws(b) || b == '>';
}

/* Parse a decimal long at s[0..len); 0 on failure, else 1 with *out and *used. */
static int parse_long(const char *s, size_t len, long *out, size_t *used) {
    size_t i = 0;
    int neg = 0;
    if (len && (s[0] == '-' || s[0] == '+')) {
        neg = s[0] == '-';
        i = 1;
    }
    long v = 0;
    int any = 0;
    for (; i < len && isdigit((unsigned char)s[i]); i++) {
        v = v * 10 + (s[i] - '0');
        any = 1;
    }
    if (!any) return 0;
    *out = neg ? -v : v;
    *used = i;
    return 1;
}

static size_t rtrim_span(const char *s, size_t len) {
    while (len && (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r' ||
                   s[len - 1] == '\n'))
        len--;
    return len;
}

static size_t rtrim_crlf(const char *s, size_t len) {
    while (len && (s[len - 1] == '\r' || s[len - 1] == '\n')) len--;
    return len;
}

/* ---- parsed input ------------------------------------------------------ */

/* 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 assigned during
   the merge. */
typedef struct {
    long num, gen;
    buf dict;
    const char *stream;
    size_t stream_len;
    long new_num;
} object;

typedef struct {
    object *objects;
    size_t n_objects, cap_objects;
    long *pages; /* obj nums whose dict is /Type /Page */
    size_t n_pages, cap_pages;
} parsed_input;

static void push_object(parsed_input *in, object o) {
    if (in->n_objects == in->cap_objects) {
        in->cap_objects = in->cap_objects ? in->cap_objects * 2 : 8;
        in->objects = realloc(in->objects, in->cap_objects * sizeof *in->objects);
        if (!in->objects) exit(1);
    }
    in->objects[in->n_objects++] = o;
}

static void push_page(parsed_input *in, long num) {
    if (in->n_pages == in->cap_pages) {
        in->cap_pages = in->cap_pages ? in->cap_pages * 2 : 8;
        in->pages = realloc(in->pages, in->cap_pages * sizeof *in->pages);
        if (!in->pages) exit(1);
    }
    in->pages[in->n_pages++] = num;
}

static void free_input(parsed_input *in) {
    for (size_t i = 0; i < in->n_objects; i++) free(in->objects[i].dict.data);
    free(in->objects);
    free(in->pages);
    memset(in, 0, sizeof *in);
}

/* Index of the dict-terminating "stream" keyword (whitespace/'>' before
   it, EOL after it), or -1 for a plain object. */
static long find_stream_keyword(const char *body, size_t len) {
    for (size_t i = 0; i + 6 <= len; i++) {
        if (memcmp(body + i, "stream", 6) != 0) continue;
        if (i == 0 || !is_delim(body[i - 1])) continue;
        if (i + 6 < len && (body[i + 6] == '\n' || body[i + 6] == '\r')) return (long)i;
    }
    return -1;
}

/* /Type /Page but NOT /Pages — the go twin's reTypePage \b trick, done by
   requiring the character after "/Page" to be a non-identifier. */
static int dict_is_page(const buf *dict) {
    const char *p = dict->data;
    size_t len = dict->len, i = 0;
    while (i + 5 <= len) {
        if (memcmp(p + i, "/Type", 5) != 0) {
            i++;
            continue;
        }
        size_t q = i + 5;
        while (q < len && is_ws(p[q])) q++;
        if (q + 5 <= len && memcmp(p + q, "/Page", 5) == 0) {
            char after = q + 5 < len ? p[q + 5] : '\0';
            if (!isalpha((unsigned char)after) && !isdigit((unsigned char)after)) return 1;
        }
        i += 5;
    }
    return 0;
}

/* 0 (PDF_OK) when the last startxref offset points at the classic "xref"
   keyword; UNSUPPORTED when it points at "N G obj" (a PDF 1.5+
   cross-reference stream, /Type /XRef); INVALID otherwise. */
static pdf_error_kind check_xref_kind(const char *pdf, size_t len) {
    const char *sx = rfind_mem(pdf, len, "startxref");
    if (!sx) return PDF_ERROR_INVALID;
    size_t off = (size_t)(sx - pdf) + strlen("startxref");
    while (off < len && is_ws(pdf[off])) off++;
    long target;
    size_t used;
    if (!parse_long(pdf + off, len - off, &target, &used)) return PDF_ERROR_INVALID;
    if (target < 0 || (size_t)target >= len) return PDF_ERROR_INVALID;
    size_t t = (size_t)target;
    while (t < len && is_ws(pdf[t])) t++;
    if (t + 4 <= len && memcmp(pdf + t, "xref", 4) == 0) return PDF_OK;
    /* cross-reference stream: the offset points at an object header */
    long n, g;
    size_t c1, c2;
    if (parse_long(pdf + t, len - t, &n, &c1)) {
        size_t q = t + c1;
        while (q < len && is_ws(pdf[q])) q++;
        if (parse_long(pdf + q, len - q, &g, &c2)) {
            q += c2;
            while (q < len && is_ws(pdf[q])) q++;
            if (q + 3 <= len && memcmp(pdf + q, "obj", 3) == 0) return PDF_ERROR_UNSUPPORTED;
        }
    }
    return PDF_ERROR_INVALID;
}

/* Rejects encrypted files (/Encrypt) and hybrid-reference files
   (/XRefStm) from the classic trailer dictionary. */
static pdf_error_kind check_trailer(const char *pdf, size_t len) {
    const char *tr = rfind_mem(pdf, len, "trailer");
    if (!tr) return PDF_OK; /* no classic trailer — the xref-kind check ran */
    size_t tlen = len - (size_t)(tr - pdf);
    const char *sx = find_mem(tr, tlen, "startxref");
    if (sx) tlen = (size_t)(sx - tr);
    if (find_mem(tr, tlen, "/Encrypt")) return PDF_ERROR_UNSUPPORTED;
    if (find_mem(tr, tlen, "/XRefStm")) return PDF_ERROR_UNSUPPORTED;
    return PDF_OK;
}

/* Scan one input PDF: reject unsupported features, then line-scan every
   object header and split stream objects into dict + verbatim data. */
static pdf_error_kind parse_input(const char *pdf, size_t len, parsed_input *in) {
    memset(in, 0, sizeof *in);
    if (!find_mem(pdf, len, "%PDF-")) return PDF_ERROR_INVALID;
    pdf_error_kind k = check_xref_kind(pdf, len);
    if (k != PDF_OK) return k;
    k = check_trailer(pdf, len);
    if (k != PDF_OK) return k;

    for (size_t pos = 0; pos < len; pos++) {
        /* line-anchored scan: "N G obj" at the start of a line */
        if (!(pos == 0 || pdf[pos - 1] == '\n')) continue;
        long num, gen;
        size_t c1, c2;
        if (!parse_long(pdf + pos, len - pos, &num, &c1)) continue;
        size_t q = pos + c1;
        while (q < len && is_ws(pdf[q])) q++;
        if (!parse_long(pdf + q, len - q, &gen, &c2)) continue;
        q += c2;
        while (q < len && is_ws(pdf[q])) q++;
        if (q + 3 > len || memcmp(pdf + q, "obj", 3) != 0) continue;
        q += 3;
        while (q < len && is_ws(pdf[q])) q++;

        const char *body = pdf + q;
        size_t blen = len - q;
        const char *endobj = find_mem(body, blen, "endobj");
        if (!endobj) return PDF_ERROR_INVALID;
        size_t body_len = (size_t)(endobj - body);

        object o;
        memset(&o, 0, sizeof o);
        o.num = num;
        o.gen = gen;
        long si = find_stream_keyword(body, body_len);
        if (si >= 0) {
            buf_append(&o.dict, body, rtrim_span(body, (size_t)si));
            const char *data = body + si + strlen("stream");
            size_t drem = body_len - (size_t)si - strlen("stream");
            /* spec: the stream keyword is followed by CRLF or LF (not a lone CR) */
            if (drem >= 2 && data[0] == '\r' && data[1] == '\n') {
                data += 2;
                drem -= 2;
            } else if (drem >= 1 && data[0] == '\n') {
                data++;
                drem--;
            }
            const char *es = find_mem(data, drem, "endstream");
            if (es) drem = rtrim_crlf(data, (size_t)(es - data));
            o.stream = data;
            o.stream_len = drem;
        } else {
            buf_append(&o.dict, body, rtrim_span(body, body_len));
        }
        if (find_mem(o.dict.data, o.dict.len, "/ObjStm")) {
            free_input(in); /* page dicts may live inside object streams */
            return PDF_ERROR_UNSUPPORTED;
        }
        /* incremental update: last definition wins */
        long found = -1;
        for (size_t i = 0; i < in->n_objects; i++)
            if (in->objects[i].num == num) {
                found = (long)i;
                break;
            }
        if (found >= 0) {
            free(in->objects[found].dict.data);
            in->objects[found] = o;
        } else {
            push_object(in, o);
        }
        if (dict_is_page(&o.dict)) push_page(in, num);
    }
    if (in->n_objects == 0) return PDF_ERROR_INVALID;
    return PDF_OK;
}

static long lookup_new_num(const parsed_input *in, long num) {
    for (size_t i = 0; i < in->n_objects; i++)
        if (in->objects[i].num == num) return in->objects[i].new_num;
    return -1;
}

/* 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. */
static void append_rewritten(buf *out, const object *o, const parsed_input *in) {
    const char *d = o->dict.data;
    size_t len = o->dict.len, i = 0;
    while (i < len) {
        if (isdigit((unsigned char)d[i]) &&
            (i == 0 || !isdigit((unsigned char)d[i - 1]))) {
            long n, g;
            size_t c1, c2;
            if (parse_long(d + i, len - i, &n, &c1)) {
                size_t q = i + c1;
                while (q < len && is_ws(d[q])) q++;
                (void)parse_long(d + q, len - q, &g, &c2);
                if (parse_long(d + q, len - q, &g, &c2)) {
                    q += c2;
                    while (q < len && is_ws(d[q])) q++;
                    char after = q + 1 < len ? d[q + 1] : '\0';
                    if (q < len && d[q] == 'R' && !isalpha((unsigned char)after) &&
                        !isdigit((unsigned char)after)) {
                        long new_n = lookup_new_num(in, n);
                        if (new_n >= 0) {
                            buf_fmt(out, "%ld 0 R", new_n);
                            i = q + 1;
                            continue;
                        }
                    }
                }
            }
        }
        buf_append(out, d + i, 1);
        i++;
    }
}

/* MergePDFs: concatenate unencrypted classic xref-table PDFs into one new
   document and return its bytes (malloc'd; caller frees). 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 C twin of
   mergePdfs() in src/lib/pdf-merge.ts. On rejection returns NULL with
   *err and *errmsg describing the failure. */
static unsigned char *merge_pdfs(const unsigned char *const *docs, const size_t *lens,
                                 size_t n_docs, size_t *out_len, pdf_error_kind *err,
                                 const char **errmsg) {
    *err = PDF_OK;
    *errmsg = "";
    if (n_docs == 0) {
        *err = PDF_ERROR_INVALID;
        *errmsg = MSG_EMPTY;
        return NULL;
    }
    parsed_input *inputs = calloc(n_docs, sizeof *inputs);
    if (!inputs) exit(1);
    for (size_t i = 0; i < n_docs; i++) {
        *err = parse_input((const char *)docs[i], lens[i], &inputs[i]);
        if (*err != PDF_OK) {
            *errmsg = error_message(*err); /* the go twin wraps as "input %d: %w" */
            for (size_t j = 0; j <= i; j++) free_input(&inputs[j]);
            free(inputs);
            return NULL;
        }
    }

    buf out = {0};
    buf_str(&out, "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n");

    /* Pass 1: assign new object ids across all inputs (sequential from 1). */
    long next = 1;
    long total_pages = 0;
    for (size_t i = 0; i < n_docs; i++) {
        for (size_t j = 0; j < inputs[i].n_objects; j++)
            inputs[i].objects[j].new_num = next++;
        total_pages += (long)inputs[i].n_pages;
    }
    long *offsets = calloc((size_t)next + 2, sizeof *offsets); /* indexed by new id */

    /* Pass 2: write every copied object with renumbered refs in its dict. */
    for (size_t i = 0; i < n_docs; i++) {
        for (size_t j = 0; j < inputs[i].n_objects; j++) {
            const object *o = &inputs[i].objects[j];
            offsets[o->new_num] = (long)out.len;
            buf_fmt(&out, "%ld %ld obj\n", o->new_num, o->gen);
            append_rewritten(&out, o, &inputs[i]);
            if (o->stream) {
                buf_str(&out, "\nstream\n");
                buf_append(&out, o->stream, o->stream_len);
                buf_str(&out, "\nendstream\n");
            }
            buf_str(&out, "endobj\n");
        }
    }

    /* Fresh Catalog + Pages tree over the copied page objects. */
    long cat_id = next, pages_id = next + 1;
    offsets[cat_id] = (long)out.len;
    buf_fmt(&out, "%ld 0 obj\n<< /Type /Catalog /Pages %ld 0 R >>\nendobj\n", cat_id,
            pages_id);
    offsets[pages_id] = (long)out.len;
    buf_str(&out, "<< /Type /Pages /Kids [ ");
    for (size_t i = 0; i < n_docs; i++)
        for (size_t p = 0; p < inputs[i].n_pages; p++) {
            long nn = lookup_new_num(&inputs[i], inputs[i].pages[p]);
            if (nn >= 0) buf_fmt(&out, "%ld 0 R ", nn);
        }
    buf_fmt(&out, "] /Count %ld >>\nendobj\n", total_pages);

    /* Rebuilt cross-reference table + trailer. */
    long size = pages_id + 1; /* ids are 1-based, contiguous */
    long xref_off = (long)out.len;
    buf_str(&out, "xref\n");
    buf_fmt(&out, "0 %ld\n", size);
    buf_str(&out, "0000000000 65535 f \n");
    for (long num = 1; num < size; num++)
        buf_fmt(&out, "%010ld 00000 n \n", offsets[num]);
    buf_str(&out, "trailer\n");
    buf_fmt(&out, "<< /Size %ld /Root %ld 0 R >>\n", size, cat_id);
    buf_fmt(&out, "startxref\n%ld\n%%%%EOF\n", xref_off);

    for (size_t i = 0; i < n_docs; i++) free_input(&inputs[i]);
    free(inputs);
    free(offsets);
    *out_len = out.len;
    return (unsigned char *)out.data;
}

/* countPages: page count for UI display — parse + count /Type /Page
   objects; -1 with *err and *errmsg on rejection. */
static long count_pages(const unsigned char *pdf, size_t len, pdf_error_kind *err,
                        const char **errmsg) {
    parsed_input in;
    *err = parse_input((const char *)pdf, len, &in);
    if (*err != PDF_OK) {
        *errmsg = error_message(*err);
        return -1;
    }
    long n = (long)in.n_pages;
    free_input(&in);
    return n;
}

/* ---- 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. */
static unsigned char *build_pdf(int pages, size_t *len_out) {
    buf b = {0};
    long offsets[64];
    buf_str(&b, "%PDF-1.4\n");
    long next = 1;
    offsets[next++] = (long)b.len;
    buf_str(&b, "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    offsets[next++] = (long)b.len;
    buf_str(&b, "2 0 obj\n<< /Type /Pages /Kids [ ");
    for (int i = 0; i < pages; i++) buf_fmt(&b, "%d 0 R ", 3 + i);
    buf_fmt(&b, "] /Count %d >>\nendobj\n", pages);
    for (int i = 0; i < pages; i++) {
        offsets[next++] = (long)b.len;
        buf_fmt(&b,
                "%d 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] "
                ">>\nendobj\n",
                3 + i);
    }
    long size = next;
    long xref_off = (long)b.len;
    buf_str(&b, "xref\n");
    buf_fmt(&b, "0 %ld\n", size);
    buf_str(&b, "0000000000 65535 f \n");
    for (long num = 1; num < size; num++)
        buf_fmt(&b, "%010ld 00000 n \n", offsets[num]);
    buf_str(&b, "trailer\n");
    buf_fmt(&b, "<< /Size %ld /Root 1 0 R >>\n", size);
    buf_fmt(&b, "startxref\n%ld\n%%%%EOF\n", xref_off);
    buf_append(&b, "", 1); /* NUL sentinel; the declared length excludes it */
    *len_out = b.len - 1;
    return (unsigned char *)b.data;
}

int main(void) {
    /* classifyLoadError — the src/lib/pdf-merge.test.ts vectors. */
    struct {
        const char *in;
        const char *label;
    } classify_cases[] = {
        {"Input document to PDFDocument.load is encrypted", "encrypted"},
        {"wrong password for this document", "password"},
        {"Failed to parse PDF", "parse"},
        {NULL, "null"},
    };
    for (size_t i = 0; i < sizeof classify_cases / sizeof classify_cases[0]; i++)
        printf("%s-msg -> %s\n", classify_cases[i].label,
               kind_name(classify_load_error(classify_cases[i].in)));

    /* empty input throws invalid */
    pdf_error_kind err;
    const char *msg;
    unsigned char *out = merge_pdfs(NULL, NULL, 0, NULL, &err, &msg);
    printf("empty-input -> %s: %s\n", kind_name(err), msg);

    /* mapError — encrypted classification propagates, message per kind */
    map_error("Input document to PDFDocument.load is encrypted", &msg);
    printf("map-encrypted -> %s: %s\n",
           kind_name(classify_load_error("Input document to PDFDocument.load is encrypted")),
           msg);
    map_error("Failed to parse PDF", &msg);
    printf("map-invalid -> %s: %s\n", kind_name(classify_load_error("Failed to parse PDF")),
           msg);

    /* classic-xref counting + merging on tiny generated docs */
    size_t len_a, len_b, merged_len;
    unsigned char *doc2 = build_pdf(2, &len_a);
    unsigned char *doc3 = build_pdf(3, &len_b);
    printf("classic-xref pages: %ld\n", count_pages(doc2, len_a, &err, &msg));
    const unsigned char *docs[2] = {doc2, doc3};
    size_t lens[2] = {len_a, len_b};
    out = merge_pdfs(docs, lens, 2, &merged_len, &err, &msg);
    if (out) {
        printf("merged pages: %ld\n", count_pages(out, merged_len, &err, &msg));
        free(out);
    }

    /* cross-reference stream -> unsupported */
    static const char stream_xref[] =
        "%PDF-1.4\n12 0 obj\n<< /Type /XRef /Size 5 /W [ 1 2 2 ] >>\nendobj\n"
        "startxref\n9\n%%EOF\n";
    count_pages((const unsigned char *)stream_xref, sizeof stream_xref - 1, &err, &msg);
    printf("stream-xref -> %s\n", kind_name(err));

    /* /Encrypt trailer -> unsupported */
    static const char encrypt_trailer[] =
        "%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";
    count_pages((const unsigned char *)encrypt_trailer, sizeof encrypt_trailer - 1, &err,
                &msg);
    printf("encrypt-trailer -> %s\n", kind_name(err));

    /* garbage bytes -> invalid */
    static const unsigned char garbage[] = {1, 2, 3};
    count_pages(garbage, sizeof garbage, &err, &msg);
    printf("garbage -> %s\n", kind_name(err));

    free(doc2);
    free(doc3);
    return 0;
}

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 →