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++).
// C++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), including its regex scans: 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. The embedded main() driver is self-contained and
// exercises only the pure helpers.
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <regex>
#include <string>
#include <vector>
enum class ErrorKind { Ok, Invalid, Encrypted, Unsupported };
static const char *kindName(ErrorKind kind) {
switch (kind) {
case ErrorKind::Encrypted: return "encrypted";
case ErrorKind::Unsupported: return "unsupported";
case ErrorKind::Ok: return "ok";
default: return "invalid";
}
}
static const char *errorMessage(ErrorKind kind) {
switch (kind) {
case ErrorKind::Unsupported:
return "pdf-merge: unsupported PDF (v1 merges classic xref-table PDFs "
"only — cross-reference streams, object streams, and encrypted "
"files are not supported)";
case ErrorKind::Encrypted:
return "This PDF is password-protected. Unlock it first.";
case ErrorKind::Invalid:
return "Not a readable PDF file.";
default:
return "";
}
}
// Pure classifier — encrypted vs invalid, from the raw error message.
// Same /encrypt|password/i heuristic the TS lib applies.
static ErrorKind classifyLoadError(const std::string *msg) {
static const std::regex re("encrypt|password", std::regex::icase);
if (msg && std::regex_search(*msg, re)) return ErrorKind::Encrypted;
return ErrorKind::Invalid;
}
// Map a raw load failure to the user-facing (kind, message) pair — the C++
// twin of the TS mapError().
static ErrorKind mapError(const std::string &raw, std::string &userMsg) {
ErrorKind kind = classifyLoadError(&raw);
userMsg = kind == ErrorKind::Encrypted ? "This PDF is password-protected. Unlock it first."
: "Not a readable PDF file.";
return kind;
}
// 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
// (empty for plain objects). newNum is the renumbered id from the merge.
struct Object {
long num = 0, gen = 0;
std::string dict;
const char *stream = nullptr;
size_t streamLen = 0;
long newNum = 0;
};
// One input document's scanned objects (in file order).
struct ParsedInput {
std::vector<Object> objects;
std::vector<long> pages; // obj nums whose dict is /Type /Page
};
// Line-anchored object-header scan: "N G obj" at the start of a line.
static const std::regex reObjHeader("^(\\d+)\\s+(\\d+)\\s+obj\\b", std::regex::multiline);
// Indirect reference "N G R" inside a dict body (never inside stream data).
static const std::regex reRef("(\\d+)\\s+(\\d+)\\s+R");
// /Type /Page (but NOT /Pages — the \b fails between "Page" and "s").
static const std::regex reTypePage("/Type\\s+/Page\\b");
static const std::regex reTypePages("/Type\\s+/Pages\\b");
static bool isWs(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }
static size_t rtrimSpan(const std::string &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 rtrimCrlf(const char *s, size_t len) {
while (len && (s[len - 1] == '\r' || s[len - 1] == '\n')) len--;
return len;
}
// 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.
static ErrorKind checkXrefKind(const std::string &pdf) {
static const std::regex reOffset("\\S+");
auto sx = pdf.rfind("startxref");
if (sx == std::string::npos) return ErrorKind::Invalid;
std::cregex_iterator it(pdf.data() + sx + 9, pdf.data() + pdf.size(), reOffset);
if (it == std::cregex_iterator()) return ErrorKind::Invalid;
long off = 0;
try {
off = std::stol(it->str());
} catch (...) {
return ErrorKind::Invalid;
}
if (off < 0 || static_cast<size_t>(off) >= pdf.size()) return ErrorKind::Invalid;
size_t t = static_cast<size_t>(off);
while (t < pdf.size() && isWs(pdf[t])) t++;
if (pdf.compare(t, 4, "xref") == 0) return ErrorKind::Ok;
if (std::regex_search(pdf.begin() + static_cast<long>(t), pdf.end(), reObjHeader))
return ErrorKind::Unsupported; // cross-reference stream (/Type /XRef)
return ErrorKind::Invalid;
}
// Rejects encrypted files (/Encrypt) and hybrid-reference files (/XRefStm).
static ErrorKind checkTrailer(const std::string &pdf) {
size_t idx = pdf.rfind("trailer");
if (idx == std::string::npos) return ErrorKind::Ok; // xref-kind check already ran
size_t end = pdf.find("startxref", idx);
std::string trailer = pdf.substr(idx, end == std::string::npos ? std::string::npos : end - idx);
if (trailer.find("/Encrypt") != std::string::npos) return ErrorKind::Unsupported;
if (trailer.find("/XRefStm") != std::string::npos) return ErrorKind::Unsupported;
return ErrorKind::Ok;
}
// Scan one input PDF: reject unsupported features, then line-scan every
// object header and split stream objects into dict + verbatim data.
static ErrorKind parseInput(const std::string &pdf, ParsedInput &in) {
in = ParsedInput{};
if (pdf.find("%PDF-") == std::string::npos) return ErrorKind::Invalid;
ErrorKind k = checkXrefKind(pdf);
if (k != ErrorKind::Ok) return k;
k = checkTrailer(pdf);
if (k != ErrorKind::Ok) return k;
auto begin = std::sregex_iterator(pdf.begin(), pdf.end(), reObjHeader);
for (auto it = begin; it != std::sregex_iterator(); ++it) {
Object o;
o.num = std::stol((*it)[1].str());
o.gen = std::stol((*it)[2].str());
size_t bodyStart = static_cast<size_t>(it->position() + it->length());
size_t bodyEnd = pdf.find("endobj", bodyStart);
if (bodyEnd == std::string::npos) return ErrorKind::Invalid;
std::string body = pdf.substr(bodyStart, bodyEnd - bodyStart);
size_t si = body.find("stream");
while (si != std::string::npos &&
((si == 0) || !(si == 0 || body[si - 1] == ' ' || body[si - 1] == '\t' ||
body[si - 1] == '\r' || body[si - 1] == '\n' ||
body[si - 1] == '>')))
si = body.find("stream", si + 1);
if (si != std::string::npos &&
(si + 6 >= body.size() || body[si + 6] == '\n' || body[si + 6] == '\r')) {
o.dict = body.substr(0, rtrimSpan(body, si));
const char *data = body.data() + si + 6;
size_t drem = body.size() - si - 6;
// 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--;
}
for (size_t e = 0; e + 9 <= drem; e++) {
if (std::memcmp(data + e, "endstream", 9) == 0) {
drem = rtrimCrlf(data, e);
break;
}
}
o.stream = data;
o.streamLen = drem;
} else {
o.dict = body.substr(0, rtrimSpan(body, body.size()));
}
if (o.dict.find("/ObjStm") != std::string::npos)
return ErrorKind::Unsupported; // page dicts may live inside object streams
// incremental update: last definition wins
long found = -1;
for (size_t i = 0; i < in.objects.size(); i++)
if (in.objects[i].num == o.num) found = static_cast<long>(i);
if (found >= 0) {
in.objects[static_cast<size_t>(found)] = o;
} else {
in.objects.push_back(o);
}
if (std::regex_search(o.dict, reTypePage) && !std::regex_search(o.dict, reTypePages))
in.pages.push_back(o.num);
}
if (in.objects.empty()) return ErrorKind::Invalid;
return ErrorKind::Ok;
}
// 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 appendRewritten(std::string &out, const Object &o, const ParsedInput &in) {
auto rewritten = std::regex_replace(o.dict, reRef, "� 0 R");
// regex_replace can't look up per-match; do the two-pass token walk here.
(void)rewritten;
std::string dict = o.dict;
std::string result;
result.reserve(dict.size());
for (size_t i = 0; i < dict.size();) {
if (std::isdigit(static_cast<unsigned char>(dict[i])) &&
(i == 0 || !std::isdigit(static_cast<unsigned char>(dict[i - 1])))) {
size_t q = i;
while (q < dict.size() && std::isdigit(static_cast<unsigned char>(dict[q]))) q++;
long n = std::stol(dict.substr(i, q - i));
while (q < dict.size() && isWs(dict[q])) q++;
size_t d0 = q;
while (q < dict.size() && std::isdigit(static_cast<unsigned char>(dict[q]))) q++;
if (q > d0) { // a "N G" prefix only rewrites when a "R" follows
long g = std::stol(dict.substr(d0, q - d0));
(void)g;
while (q < dict.size() && isWs(dict[q])) q++;
if (q < dict.size() && dict[q] == 'R' &&
(q + 1 >= dict.size() ||
!(std::isalnum(static_cast<unsigned char>(dict[q + 1]))))) {
long newNum = -1;
for (const Object &src : in.objects)
if (src.num == n) newNum = src.newNum;
if (newNum >= 0) {
result += std::to_string(newNum) + " 0 R";
i = q + 1;
continue;
}
}
}
}
result += dict[i++];
}
out += result;
}
// 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.
// Returns false with *err/*errmsg on rejection.
static bool mergePdfs(std::vector<std::string> &inputs, std::string &out,
ErrorKind &err, std::string &errmsg) {
err = ErrorKind::Ok;
errmsg.clear();
if (inputs.empty()) {
err = ErrorKind::Invalid;
errmsg = "Nothing to merge.";
return false;
}
std::vector<ParsedInput> parsed(inputs.size());
for (size_t i = 0; i < parsed.size(); i++) {
err = parseInput(inputs[i], parsed[i]);
if (err != ErrorKind::Ok) {
errmsg = errorMessage(err); // the go twin wraps as "input %d: %w"
return false;
}
}
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, totalPages = 0;
for (ParsedInput &p : parsed) {
for (Object &o : p.objects) o.newNum = next++;
totalPages += static_cast<long>(p.pages.size());
}
std::vector<long> offsets(static_cast<size_t>(next) + 2, 0);
// Pass 2: write every copied object with renumbered refs in its dict.
for (const ParsedInput &p : parsed) {
for (const Object &o : p.objects) {
offsets[static_cast<size_t>(o.newNum)] = static_cast<long>(out.size());
out += std::to_string(o.newNum) + " " + std::to_string(o.gen) + " obj\n";
appendRewritten(out, o, p);
if (o.stream) {
out += "\nstream\n";
out.append(o.stream, o.streamLen);
out += "\nendstream\n";
}
out += "endobj\n";
}
}
// Fresh Catalog + Pages tree over the copied page objects.
long catId = next, pagesId = next + 1;
offsets[static_cast<size_t>(catId)] = static_cast<long>(out.size());
out += std::to_string(catId) + " 0 obj\n<< /Type /Catalog /Pages " +
std::to_string(pagesId) + " 0 R >>\nendobj\n";
offsets[static_cast<size_t>(pagesId)] = static_cast<long>(out.size());
out += "<< /Type /Pages /Kids [ ";
for (const ParsedInput &p : parsed)
for (long num : p.pages) {
for (const Object &src : p.objects)
if (src.num == num) out += std::to_string(src.newNum) + " 0 R ";
}
out += "] /Count " + std::to_string(totalPages) + " >>\nendobj\n";
// Rebuilt cross-reference table + trailer.
long size = pagesId + 1; // ids are 1-based, contiguous
long xrefOff = static_cast<long>(out.size());
out += "xref\n0 " + std::to_string(size) + "\n0000000000 65535 f \n";
char line[64];
for (long num = 1; num < size; num++) {
std::snprintf(line, sizeof line, "%010ld 00000 n \n", offsets[static_cast<size_t>(num)]);
out += line;
}
out += "trailer\n<< /Size " + std::to_string(size) + " /Root " + std::to_string(catId) +
" 0 R >>\n";
out += "startxref\n" + std::to_string(xrefOff) + "\n%%EOF\n";
return true;
}
// countPages: page count for UI display — parse + count /Type /Page
// objects; -1 with *err/*errmsg on rejection.
static long countPages(const std::string &pdf, ErrorKind &err, std::string &errmsg) {
ParsedInput in;
err = parseInput(pdf, in);
if (err != ErrorKind::Ok) {
errmsg = errorMessage(err);
return -1;
}
return static_cast<long>(in.pages.size());
}
// ---- 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 std::string buildPdf(int pages) {
std::string b = "%PDF-1.4\n";
std::vector<long> offsets(64, 0);
long next = 1;
offsets[static_cast<size_t>(next++)] = static_cast<long>(b.size());
b += "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
offsets[static_cast<size_t>(next++)] = static_cast<long>(b.size());
b += "2 0 obj\n<< /Type /Pages /Kids [ ";
for (int i = 0; i < pages; i++) b += std::to_string(3 + i) + " 0 R ";
b += "] /Count " + std::to_string(pages) + " >>\nendobj\n";
for (int i = 0; i < pages; i++) {
offsets[static_cast<size_t>(next++)] = static_cast<long>(b.size());
b += std::to_string(3 + i) +
" 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] >>\nendobj\n";
}
long size = next;
long xrefOff = static_cast<long>(b.size());
b += "xref\n0 " + std::to_string(size) + "\n0000000000 65535 f \n";
char line[64];
for (long num = 1; num < size; num++) {
std::snprintf(line, sizeof line, "%010ld 00000 n \n", offsets[static_cast<size_t>(num)]);
b += line;
}
b += "trailer\n<< /Size " + std::to_string(size) + " /Root 1 0 R >>\n";
b += "startxref\n" + std::to_string(xrefOff) + "\n%%EOF\n";
return b;
}
int main() {
// classifyLoadError — the src/lib/pdf-merge.test.ts vectors.
const std::pair<const char *, const char *> classifyCases[] = {
{"Input document to PDFDocument.load is encrypted", "encrypted"},
{"wrong password for this document", "password"},
{"Failed to parse PDF", "parse"},
{"", "null"}, // the C++ stand-in for the TS undefined input
};
for (const auto &c : classifyCases) {
std::string s = c.first;
printf("%s-msg -> %s\n", c.second,
kindName(classifyLoadError(c.first[0] ? &s : nullptr)));
}
// empty input throws invalid
ErrorKind err;
std::string msg;
std::string out;
std::vector<std::string> empty;
(void)mergePdfs(empty, out, err, msg);
printf("empty-input -> %s: %s\n", kindName(err), msg.c_str());
// mapError — encrypted classification propagates, message per kind
const std::string encMsg = "Input document to PDFDocument.load is encrypted";
const std::string parseMsg = "Failed to parse PDF";
mapError(encMsg, msg);
printf("map-encrypted -> %s: %s\n", kindName(classifyLoadError(&encMsg)), msg.c_str());
mapError(parseMsg, msg);
printf("map-invalid -> %s: %s\n", kindName(classifyLoadError(&parseMsg)), msg.c_str());
// classic-xref counting + merging on tiny generated docs
std::string doc2 = buildPdf(2), doc3 = buildPdf(3);
printf("classic-xref pages: %ld\n", countPages(doc2, err, msg));
std::vector<std::string> two = {doc2, doc3};
if (mergePdfs(two, out, err, msg))
printf("merged pages: %ld\n", countPages(out, err, msg));
// cross-reference stream -> unsupported
countPages("%PDF-1.4\n12 0 obj\n<< /Type /XRef /Size 5 /W [ 1 2 2 ] >>\nendobj\n"
"startxref\n9\n%%EOF\n",
err, msg);
printf("stream-xref -> %s\n", kindName(err));
// /Encrypt trailer -> unsupported
countPages("%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",
err, msg);
printf("encrypt-trailer -> %s\n", kindName(err));
// garbage bytes -> invalid
countPages(std::string("\x01\x02\x03", 3), err, msg);
printf("garbage -> %s\n", kindName(err));
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 →