Skip to content

PDF Split — Go source

Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.

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

// Package pdfsplit is the Go twin of CosmoDev's src/lib/pdf-split.ts (dual
// source: the web lib is TypeScript (pdf-lib), the CLI lib is Go — kept in
// lock-step). Pure + deterministic, never panics. ParsePageRanges and
// PlanNames mirror the TS planner EXACTLY — same grammar ('all', 'N/chunk',
// 'a-b,c'), same error classes — and the table-driven tests in pdf-split_test.go
// copy their vectors verbatim from src/lib/pdf-split.test.ts.
//
// v1 scope: the byte-level split EXECUTOR is not implemented. SplitPDF always
// returns ErrUnsupported (v1 has no page-extraction engine for classic xref
// PDFs, and stream-xref inputs are out of scope entirely); the twin exposes
// the planner + naming for library use.
package pdfsplit

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

// PdfToolError mirrors the TS PdfToolError from src/lib/pdf-errors.ts: a
// coded, user-facing error. The planner only ever raises Code "invalid".
type PdfToolError struct {
	Code    string // "invalid" (the TS union also has "encrypted", load-time only)
	Message string
}

func (e *PdfToolError) Error() string { return e.Message }

func invalidf(format string, args ...any) *PdfToolError {
	return &PdfToolError{Code: "invalid", Message: fmt.Sprintf(format, args...)}
}

// ErrUnsupported is returned by SplitPDF: byte-level page extraction is not
// implemented in v1 (see package doc). It mirrors pdf-merge's ErrUnsupported.
var ErrUnsupported = errors.New("pdf-split: byte-level page extraction is not implemented in v1")

var (
	reChunk  = regexp.MustCompile(`^(\d+)/chunk$`)
	reSingle = regexp.MustCompile(`^\d+$`)
	reSpan   = regexp.MustCompile(`^(\d+)-(\d+)$`)
)

// ParsePageRanges is the pure planner — no PDF parsing on this path. Grammar:
//
//	'all'       → [[1],[2],…,[pageCount]]
//	'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)
//
// It returns a *PdfToolError with Code "invalid" on empty/whitespace specs,
// unparseable tokens, descending ranges, and any page outside 1..pageCount —
// the same error classes as the TS planner.
func ParsePageRanges(spec string, pageCount int) ([][]int, error) {
	trimmed := strings.TrimSpace(spec)
	if trimmed == "" {
		return nil, &PdfToolError{Code: "invalid", Message: "Enter a page range first."}
	}

	if trimmed == "all" {
		groups := make([][]int, pageCount)
		for i := range groups {
			groups[i] = []int{i + 1}
		}
		return groups, nil
	}

	if m := reChunk.FindStringSubmatch(trimmed); m != nil {
		size, ok := parsePageNum(m[1], pageCount)
		if !ok || size < 1 || size > pageCount {
			return nil, invalidf("Chunk size must be between 1 and %d.", pageCount)
		}
		var groups [][]int
		for start := 1; start <= pageCount; start += size {
			end := min(start+size-1, pageCount)
			groups = append(groups, spanRange(start, end))
		}
		return groups, nil
	}

	tokens := strings.Split(trimmed, ",")
	groups := make([][]int, 0, len(tokens))
	for _, token := range tokens {
		t := strings.TrimSpace(token)
		if reSingle.MatchString(t) {
			page, ok := parsePageNum(t, pageCount)
			if !ok || page < 1 || page > pageCount {
				return nil, invalidf("Page %s is out of range (1–%d).", t, pageCount)
			}
			groups = append(groups, []int{page})
			continue
		}
		if m := reSpan.FindStringSubmatch(t); m != nil {
			a, aOK := parsePageNum(m[1], pageCount)
			b, bOK := parsePageNum(m[2], pageCount)
			if !aOK || !bOK || b < a {
				return nil, invalidf("Range %s-%s descends — use a-b with a ≤ b.", m[1], m[2])
			}
			if a < 1 || b > pageCount {
				return nil, invalidf("Range %s-%s is out of range (1–%d).", m[1], m[2], pageCount)
			}
			groups = append(groups, spanRange(a, b))
			continue
		}
		return nil, invalidf("%q is not a page, a-b range, \"all\", or \"N/chunk\".", t)
	}
	return groups, nil
}

// parsePageNum parses a digit token; digit-run overflow (TS Numbers never
// overflow at these sizes) maps to not-ok, which callers report as
// out-of-range — the closest TS behaviour for astronomically large numbers.
func parsePageNum(s string, _ int) (int, bool) {
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0, false
	}
	return n, true
}

// spanRange builds the inclusive 1-based range [a..b] (the TS range() helper).
func spanRange(a, b int) []int {
	pages := make([]int, 0, b-a+1)
	for p := a; p <= b; p++ {
		pages = append(pages, p)
	}
	return pages
}

// PlanNames is the 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).
func PlanNames(groups [][]int) []string {
	chunk := chunkShaped(groups)
	names := make([]string, len(groups))
	for i, g := range groups {
		switch {
		case chunk:
			names[i] = fmt.Sprintf("chunk-%d.pdf", i+1)
		case len(g) == 1:
			names[i] = fmt.Sprintf("page-%d.pdf", g[0])
		case g[len(g)-1]-g[0]+1 == len(g):
			names[i] = fmt.Sprintf("pages-%d-%d.pdf", g[0], g[len(g)-1])
		default:
			parts := make([]string, len(g))
			for j, p := range g {
				parts[j] = strconv.Itoa(p)
			}
			names[i] = "pages-" + strings.Join(parts, ",") + ".pdf"
		}
	}
	return names
}

// chunkShaped reports whether groups are a partition of 1..n into equal runs
// of ≥2 pages (last may be short) — mirrors the TS chunkShaped helper.
func chunkShaped(groups [][]int) bool {
	if len(groups) < 2 {
		return false
	}
	size := len(groups[0])
	// Size-1 "chunks" are indistinguishable from 'all' — those stay page-N.
	if size < 2 {
		return false
	}
	next := 1
	for i, g := range groups {
		if g[0] != next {
			return false
		}
		next = g[len(g)-1] + 1
		if i < len(groups)-1 && len(g) != size {
			return false
		}
		if i == len(groups)-1 && len(g) > size {
			return false
		}
	}
	return true
}

// SplitPDF would extract each group into its own output PDF. v1 does not
// implement byte-level page extraction — see package doc — so it always
// returns ErrUnsupported. Callers should use ParsePageRanges + PlanNames to
// preview a plan and wait for the executor to land.
func SplitPDF(pdf []byte, groups [][]int) ([][]byte, error) {
	_ = pdf
	_ = groups
	return nil, ErrUnsupported
}

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 →