PDF Split — C source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.
/* pdf-split — C port: page-range planner + naming for the split-by-plan tool.
C11, stdlib only. Port of src/lib/pdf-split.ts — same logic as this dir's
typescript.ts and the live Go twin at cli/pdf-split/pdf-split.go. No
idiomatic C PDF library exists, so like the Go twin only the pure planner
(parse_page_ranges) and naming pass (plan_names) are ported; the byte-level
split executor stays out of scope. The caller frees every result. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* PdfToolError: a coded, user-facing error (TS: PdfToolError from
src/lib/pdf-errors.ts). The planner only ever raises code "invalid" —
"encrypted" is load-time only. */
typedef struct {
const char *code;
char message[256];
} PdfToolError;
/* A planned split: ragged 2-D array of 1-based page numbers, one group per
output file. */
typedef struct {
int **groups;
int *lengths;
int count;
} Plan;
static int fail(PdfToolError *err, const char *msg) {
if (err != NULL) {
err->code = "invalid";
snprintf(err->message, sizeof err->message, "%s", msg);
}
return 0;
}
static int failf(PdfToolError *err, const char *fmt, ...) {
if (err != NULL) {
va_list ap;
va_start(ap, fmt);
err->code = "invalid";
vsnprintf(err->message, sizeof err->message, fmt, ap);
va_end(ap);
}
return 0;
}
/* The inclusive 1-based range [a..b] (the TS range() helper). */
static int *span_range(int a, int b, int *len) {
int *pages = malloc((size_t) (b - a + 1) * sizeof *pages);
for (int p = a; p <= b; p++) pages[p - a] = p;
*len = b - a + 1;
return pages;
}
static char *trim_dup(const char *s) {
while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n') s++;
size_t n = strlen(s);
while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || s[n - 1] == '\r' || s[n - 1] == '\n')) n--;
char *out = malloc(n + 1);
memcpy(out, s, n);
out[n] = '\0';
return out;
}
/* Digit-run parse: "12" → 12, anything else → 0. Callers pre-check with
all_digits, so this mirrors the anchored TS regexes. */
static int all_digits(const char *s) {
if (*s == '\0') return 0;
for (const char *p = s; *p != '\0'; p++) {
if (*p < '0' || *p > '9') return 0;
}
return 1;
}
static int parse_num(const char *s) {
int n = 0;
for (const char *p = s; *p != '\0'; p++) n = n * 10 + (*p - '0');
return n;
}
/* Parse one token: a single page, or an a-b span (1-based, inclusive).
Returns a malloc'd group or NULL after recording the error. */
static int *parse_token(const char *t, int page_count, int *len, PdfToolError *err) {
if (all_digits(t)) {
int page = parse_num(t);
if (page < 1 || page > page_count) {
failf(err, "Page %d is out of range (1\342\200\223%d).", page, page_count);
return NULL;
}
*len = 1;
int *group = malloc(sizeof *group);
group[0] = page;
return group;
}
const char *dash = strchr(t, '-');
if (dash != NULL && strchr(dash + 1, '-') == NULL) {
char *a = strndup(t, (size_t) (dash - t));
char *b = strdup(dash + 1);
if (all_digits(a) && all_digits(b)) {
int lo = parse_num(a), hi = parse_num(b);
free(a);
free(b);
if (hi < lo) {
failf(err, "Range %d-%d descends \342\200\224 use a-b with a \342\211\244 b.", lo, hi);
return NULL;
}
if (lo < 1 || hi > page_count) {
failf(err, "Range %d-%d is out of range (1\342\200\223%d).", lo, hi, page_count);
return NULL;
}
return span_range(lo, hi, len);
}
free(a);
free(b);
}
failf(err, "\"%s\" is not a page, a-b range, \"all\", or \"N/chunk\".", t);
return NULL;
}
/* Pure planner — no PDF parsing on this path. Grammar:
*
* 'all' -> [[1],[2],..,[page_count]]
* 'N/chunk' -> groups of N pages in order (last group may be short)
* 'a-b,c-d,e' -> [[a..b],[c..d],[e]] (1-based, inclusive)
*
* Returns 1 and fills *out on success; returns 0 with err filled (the same
* error classes as the TS planner) on failure. */
int parse_page_ranges(const char *spec, int page_count, Plan *out, PdfToolError *err) {
char *trimmed = trim_dup(spec);
if (*trimmed == '\0') {
free(trimmed);
return fail(err, "Enter a page range first.");
}
if (strcmp(trimmed, "all") == 0) {
out->count = page_count;
out->groups = malloc((size_t) page_count * sizeof *out->groups);
out->lengths = malloc((size_t) page_count * sizeof *out->lengths);
for (int i = 0; i < page_count; i++) {
out->groups[i] = malloc(sizeof **out->groups);
out->groups[i][0] = i + 1;
out->lengths[i] = 1;
}
free(trimmed);
return 1;
}
/* 'N/chunk' — fixed-size groups in order (last may be short). */
size_t n = strlen(trimmed);
const char suffix[] = "/chunk";
if (n > strlen(suffix) && strcmp(trimmed + n - strlen(suffix), suffix) == 0) {
char *prefix = strndup(trimmed, n - strlen(suffix));
if (!all_digits(prefix)) {
free(prefix);
free(trimmed);
return failf(err, "\"%s\" is not a page, a-b range, \"all\", or \"N/chunk\".", trimmed);
}
int size = parse_num(prefix);
free(prefix);
if (size < 1 || size > page_count) {
free(trimmed);
return failf(err, "Chunk size must be between 1 and %d.", page_count);
}
int capacity = page_count / size + 1;
out->count = 0;
out->groups = malloc((size_t) capacity * sizeof *out->groups);
out->lengths = malloc((size_t) capacity * sizeof *out->lengths);
for (int start = 1; start <= page_count; start += size) {
int len;
int end = start + size - 1 < page_count ? start + size - 1 : page_count;
out->groups[out->count] = span_range(start, end, &len);
out->lengths[out->count] = len;
out->count++;
}
free(trimmed);
return 1;
}
/* Comma-separated tokens: pages and a-b spans. */
int capacity = 1;
for (const char *p = trimmed; *p != '\0'; p++) {
if (*p == ',') capacity++;
}
out->count = 0;
out->groups = malloc((size_t) capacity * sizeof *out->groups);
out->lengths = malloc((size_t) capacity * sizeof *out->lengths);
char *cursor = trimmed;
while (cursor != NULL) {
char *comma = strchr(cursor, ',');
char *token;
if (comma != NULL) {
token = strndup(cursor, (size_t) (comma - cursor));
cursor = comma + 1;
} else {
token = strdup(cursor);
cursor = NULL;
}
char *t = trim_dup(token);
free(token);
int len;
int *group = parse_token(t, page_count, &len, err);
free(t);
if (group == NULL) {
free(trimmed);
return 0;
}
out->groups[out->count] = group;
out->lengths[out->count] = len;
out->count++;
}
free(trimmed);
return 1;
}
/* Free a plan returned by parse_page_ranges. */
void plan_free(Plan *plan) {
for (int i = 0; i < plan->count; i++) free(plan->groups[i]);
free(plan->groups);
free(plan->lengths);
plan->groups = NULL;
plan->lengths = NULL;
plan->count = 0;
}
/* Chunk-shaped = partition of 1..n into equal runs of >=2 pages (last may be
short). Size-1 "chunks" are indistinguishable from 'all' — those stay
page-N. */
static int chunk_shaped(const Plan *plan) {
if (plan->count < 2) return 0;
int size = plan->lengths[0];
if (size < 2) return 0;
int next = 1;
for (int i = 0; i < plan->count; i++) {
const int *g = plan->groups[i];
int len = plan->lengths[i];
if (g[0] != next) return 0;
next = g[len - 1] + 1;
if (i < plan->count - 1 && len != size) return 0;
if (i == plan->count - 1 && len > size) return 0;
}
return 1;
}
/* Pure naming for a planned split — the single source of truth shared by the
TS splitPdf and the island's live preview. Single page -> 'page-N.pdf';
chunk-shaped plan -> 'chunk-K.pdf' (K 1-based); contiguous group ->
'pages-A-B.pdf'; otherwise 'pages-A,B.pdf' (joined). Returns a malloc'd
array of plan->count malloc'd strings; the caller frees everything. */
char **plan_names(const Plan *plan) {
int chunk = chunk_shaped(plan);
char **names = malloc((size_t) plan->count * sizeof *names);
for (int i = 0; i < plan->count; i++) {
const int *g = plan->groups[i];
int len = plan->lengths[i];
char buf[256];
if (chunk) {
snprintf(buf, sizeof buf, "chunk-%d.pdf", i + 1);
} else if (len == 1) {
snprintf(buf, sizeof buf, "page-%d.pdf", g[0]);
} else if (g[len - 1] - g[0] + 1 == len) {
snprintf(buf, sizeof buf, "pages-%d-%d.pdf", g[0], g[len - 1]);
} else {
int used = snprintf(buf, sizeof buf, "pages-");
for (int j = 0; j < len && used < (int) sizeof buf - 8; j++) {
used += snprintf(buf + used, sizeof buf - (size_t) used, "%s%d", j > 0 ? "," : "", g[j]);
}
snprintf(buf + used, sizeof buf - (size_t) used, ".pdf");
}
names[i] = strdup(buf);
}
return names;
}
/* SplitPdf would extract each group into its own output PDF. v1 does not
implement byte-level page extraction — see header — so it always fails
with code "unsupported", mirroring the Go twin's ErrUnsupported. Callers
should use parse_page_ranges + plan_names to preview a plan and wait for
the executor to land. */
int split_pdf(const unsigned char *pdf, size_t pdf_len, const Plan *plan, PdfToolError *err) {
(void) pdf;
(void) pdf_len;
(void) plan;
if (err != NULL) {
err->code = "unsupported";
snprintf(err->message, sizeof err->message, "%s",
"pdf-split: byte-level page extraction is not implemented in v1");
}
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 →