Skip to content

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. C++17, standard library 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.
#include <cstdint>
#include <regex>
#include <stdexcept>
#include <string>
#include <vector>

// 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.
class PdfToolError : public std::runtime_error {
public:
    PdfToolError(std::string code, const std::string &message)
        : std::runtime_error(message), code_(std::move(code)) {}

    const std::string &code() const { return code_; }

private:
    std::string code_;
};

// SplitPDF is not implemented in v1 (see header): byte-level page extraction
// has no stdlib engine, mirroring the Go twin's ErrUnsupported.
class UnsupportedError : public std::runtime_error {
public:
    UnsupportedError()
        : std::runtime_error("pdf-split: byte-level page extraction is not implemented in v1") {}
};

namespace {

const std::regex &chunk_re() {
    static const std::regex re(R"(^(\d+)/chunk$)");
    return re;
}
const std::regex &single_re() {
    static const std::regex re(R"(^\d+$)");
    return re;
}
const std::regex &span_re() {
    static const std::regex re(R"(^(\d+)-(\d+)$)");
    return re;
}

PdfToolError invalid(const std::string &message) { return PdfToolError("invalid", message); }

// The inclusive 1-based range [a..b] (the TS range() helper).
std::vector<int> span_range(int a, int b) {
    std::vector<int> pages;
    for (int p = a; p <= b; ++p) pages.push_back(p);
    return pages;
}

} // namespace

// 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)
//
// Throws PdfToolError("invalid", ...) on empty/whitespace specs, unparseable
// tokens, descending ranges, and any page outside 1..page_count — the same
// error classes as the TS planner.
std::vector<std::vector<int>> parse_page_ranges(const std::string &spec, int page_count) {
    const std::string trimmed = [](const std::string &s) {
        const auto begin = s.find_first_not_of(" \t\r\n");
        if (begin == std::string::npos) return std::string();
        const auto end = s.find_last_not_of(" \t\r\n");
        return s.substr(begin, end - begin + 1);
    }(spec);
    if (trimmed.empty()) throw invalid("Enter a page range first.");

    if (trimmed == "all") {
        std::vector<std::vector<int>> groups;
        for (int p = 1; p <= page_count; ++p) groups.push_back({p});
        return groups;
    }

    std::smatch m;
    if (std::regex_match(trimmed, m, chunk_re())) {
        const int size = std::stoi(m[1].str());
        if (size < 1 || size > page_count) {
            throw invalid("Chunk size must be between 1 and " + std::to_string(page_count) + ".");
        }
        std::vector<std::vector<int>> groups;
        for (int start = 1; start <= page_count; start += size) {
            groups.push_back(span_range(start, std::min(start + size - 1, page_count)));
        }
        return groups;
    }

    std::vector<std::vector<int>> groups;
    size_t pos = 0;
    while (true) {
        size_t comma = trimmed.find(',', pos);
        std::string token = trimmed.substr(pos, comma == std::string::npos ? comma : comma - pos);
        // Trim the token, then dispatch like the TS planner.
        const auto begin = token.find_first_not_of(" \t\r\n");
        if (begin == std::string::npos) {
            throw invalid("\"\" is not a page, a-b range, \"all\", or \"N/chunk\".");
        }
        const auto end = token.find_last_not_of(" \t\r\n");
        const std::string t = token.substr(begin, end - begin + 1);

        if (std::regex_match(t, m, single_re())) {
            const int page = std::stoi(t);
            if (page < 1 || page > page_count) {
                throw invalid("Page " + std::to_string(page) + " is out of range (1\342\200\223" +
                              std::to_string(page_count) + ").");
            }
            groups.push_back({page});
        } else if (std::regex_match(t, m, span_re())) {
            const int a = std::stoi(m[1].str());
            const int b = std::stoi(m[2].str());
            if (b < a) {
                throw invalid("Range " + std::to_string(a) + "-" + std::to_string(b) +
                              " descends \342\200\224 use a-b with a \342\211\244 b.");
            }
            if (a < 1 || b > page_count) {
                throw invalid("Range " + std::to_string(a) + "-" + std::to_string(b) +
                              " is out of range (1\342\200\223" + std::to_string(page_count) + ").");
            }
            groups.push_back(span_range(a, b));
        } else {
            throw invalid("\"" + t + "\" is not a page, a-b range, \"all\", or \"N/chunk\".");
        }

        if (comma == std::string::npos) break;
        pos = comma + 1;
    }
    return groups;
}

namespace {

// 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.
bool chunk_shaped(const std::vector<std::vector<int>> &groups) {
    if (groups.size() < 2) return false;
    const size_t size = groups[0].size();
    if (size < 2) return false;
    int next = 1;
    for (size_t i = 0; i < groups.size(); ++i) {
        const auto &g = groups[i];
        if (g.front() != next) return false;
        next = g.back() + 1;
        if (i + 1 < groups.size() && g.size() != size) return false;
        if (i + 1 == groups.size() && g.size() > size) return false;
    }
    return true;
}

} // namespace

// 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).
std::vector<std::string> plan_names(const std::vector<std::vector<int>> &groups) {
    const bool chunk = chunk_shaped(groups);
    std::vector<std::string> names;
    names.reserve(groups.size());
    for (size_t i = 0; i < groups.size(); ++i) {
        const auto &g = groups[i];
        if (chunk) {
            names.push_back("chunk-" + std::to_string(i + 1) + ".pdf");
        } else if (g.size() == 1) {
            names.push_back("page-" + std::to_string(g.front()) + ".pdf");
        } else if (static_cast<size_t>(g.back() - g.front() + 1) == g.size()) {
            names.push_back("pages-" + std::to_string(g.front()) + "-" + std::to_string(g.back()) + ".pdf");
        } else {
            std::string joined = "pages-";
            for (size_t j = 0; j < g.size(); ++j) {
                if (j > 0) joined += ',';
                joined += std::to_string(g[j]);
            }
            names.push_back(joined + ".pdf");
        }
    }
    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 throws
// UnsupportedError. Callers should use parse_page_ranges + plan_names to
// preview a plan and wait for the executor to land.
std::vector<std::vector<std::uint8_t>> split_pdf(const std::vector<std::uint8_t> &pdf,
                                                 const std::vector<std::vector<int>> &groups) {
    (void) pdf;
    (void) groups;
    throw UnsupportedError();
}

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 →