Skip to content

PDF Split — PHP source

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

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

<?php
/**
 * pdf-split — split one PDF into many by page plan with FPDI
 * (setasign/Fpdi on FPDF). Authored snippet mirroring src/lib/pdf-split.ts:
 * the planner (parsePageRanges + planNames) is a pure port of the TS grammar
 * — 'all', 'N/chunk', or comma-separated 'a-b' ranges and single pages
 * (1-based, inclusive) — and splitPdf stamps each planned group's pages into
 * a fresh FPDI document with the same naming rules.
 */

declare(strict_types=1);

use setasign\Fpdi\Fpdi;

/** Load failure kind: 'encrypted' (password-protected) or 'invalid' (unparseable). */
final class PdfToolError extends RuntimeException
{
    public function __construct(
        public readonly string $code_, // 'encrypted' | 'invalid'
        string $message,
    ) {
        parent::__construct($message);
    }
}

/** Pure classifier — encrypted vs invalid, from the raw error message. */
function classifyLoadError(?string $msg): string
{
    return ($msg !== null && preg_match('/encrypt|password/i', $msg) === 1)
        ? 'encrypted'
        : 'invalid';
}

/** Map a thrown parse error to a user-facing PdfToolError. */
function mapError(Throwable $e): PdfToolError
{
    $kind = classifyLoadError($e->getMessage());
    return new PdfToolError(
        $kind,
        $kind === 'encrypted'
            ? 'This PDF is password-protected. Unlock it first.'
            : 'Not a readable PDF file.'
    );
}

/** The 1-based pages [a..b], inclusive. @return list<int> */
function pageRange(int $a, int $b): array
{
    return range($a, $b);
}

/**
 * Pure planner — grammar (mirrors parsePageRanges in src/lib/pdf-split.ts):
 *   'all'       -> [[1], [2], ..., [pageCount]]
 *   'N/chunk'   -> groups of N pages in order (last group may be short)
 *   'a-b,c-d,e' -> explicit groups (1-based, inclusive)
 *
 * @return list<list<int>>
 */
function parsePageRanges(string $spec, int $pageCount): array
{
    $trimmed = trim($spec);
    if ($trimmed === '') {
        throw new PdfToolError('invalid', 'Enter a page range first.');
    }
    if ($trimmed === 'all') {
        $groups = [];
        for ($p = 1; $p <= $pageCount; $p++) {
            $groups[] = [$p];
        }
        return $groups;
    }
    if (preg_match('/^(\d+)\/chunk$/', $trimmed, $m) === 1) {
        $size = (int) $m[1];
        if ($size < 1 || $size > $pageCount) {
            throw new PdfToolError('invalid', "Chunk size must be between 1 and {$pageCount}.");
        }
        $groups = [];
        for ($start = 1; $start <= $pageCount; $start += $size) {
            $groups[] = pageRange($start, min($start + $size - 1, $pageCount));
        }
        return $groups;
    }
    $groups = [];
    foreach (explode(',', $trimmed) as $token) {
        $t = trim($token);
        if (preg_match('/^\d+$/', $t) === 1) {
            $page = (int) $t;
            if ($page < 1 || $page > $pageCount) {
                throw new PdfToolError('invalid', "Page {$page} is out of range (1–{$pageCount}).");
            }
            $groups[] = [$page];
        } elseif (preg_match('/^(\d+)-(\d+)$/', $t, $m) === 1) {
            $a = (int) $m[1];
            $b = (int) $m[2];
            if ($b < $a) {
                throw new PdfToolError('invalid', "Range {$a}-{$b} descends — use a-b with a ≤ b.");
            }
            if ($a < 1 || $b > $pageCount) {
                throw new PdfToolError('invalid', "Range {$a}-{$b} is out of range (1–{$pageCount}).");
            }
            $groups[] = pageRange($a, $b);
        } else {
            throw new PdfToolError('invalid', "\"{$t}\" is not a page, a-b range, \"all\", or \"N/chunk\".");
        }
    }
    return $groups;
}

/**
 * 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.
 *
 * @param list<list<int>> $groups
 */
function chunkShaped(array $groups): bool
{
    if (count($groups) < 2) {
        return false;
    }
    $size = count($groups[0]);
    if ($size < 2) {
        return false;
    }
    $next = 1;
    foreach ($groups as $i => $group) {
        if ($group[0] !== $next) {
            return false;
        }
        $next = $group[count($group) - 1] + 1;
        if ($i < count($groups) - 1 && count($group) !== $size) {
            return false;
        }
        if ($i === count($groups) - 1 && count($group) > $size) {
            return false;
        }
    }
    return true;
}

/**
 * Pure naming pass: single page -> 'page-N.pdf'; chunk-shaped plan ->
 * 'chunk-K.pdf'; contiguous group -> 'pages-A-B.pdf'; else 'pages-A,B.pdf'.
 *
 * @param list<list<int>> $groups
 * @return list<string>
 */
function planNames(array $groups): array
{
    $chunk = chunkShaped($groups);
    $names = [];
    foreach ($groups as $i => $group) {
        if ($chunk) {
            $names[] = 'chunk-' . ($i + 1) . '.pdf';
        } elseif (count($group) === 1) {
            $names[] = "page-{$group[0]}.pdf";
        } elseif ($group[count($group) - 1] - $group[0] + 1 === count($group)) {
            $names[] = 'pages-' . $group[0] . '-' . $group[count($group) - 1] . '.pdf';
        } else {
            $names[] = 'pages-' . implode(',', $group) . '.pdf';
        }
    }
    return $names;
}

/**
 * One output PDF per group: the source is written to a temp file (FPDI reads
 * from a path), each planned page is imported as a template and stamped onto
 * a fresh page of the output. Mirrors splitPdf() in src/lib/pdf-split.ts.
 *
 * @param list<list<int>> $groups
 * @return list<array{name: string, bytes: string, pageCount: int}>
 */
function splitPdf(string $bytes, array $groups): array
{
    if ($groups === []) {
        throw new PdfToolError('invalid', 'Nothing to split — plan at least one page.');
    }
    $srcPath = tempnam(sys_get_temp_dir(), 'pdfsplit');
    if ($srcPath === false) {
        throw new PdfToolError('invalid', 'Could not create a temp file.');
    }
    file_put_contents($srcPath, $bytes);
    try {
        $probe = new Fpdi();
        try {
            $total = $probe->setSourceFile($srcPath);
        } catch (Throwable $e) {
            throw mapError($e);
        }
        $names = planNames($groups);
        $outs = [];
        foreach ($groups as $i => $group) {
            foreach ($group as $page) {
                if ($page < 1 || $page > $total) {
                    throw new PdfToolError('invalid', "Page {$page} is out of range (1–{$total}).");
                }
            }
            $pdf = new Fpdi();
            $pdf->setSourceFile($srcPath);
            foreach ($group as $page) {
                $tpl = $pdf->importPage($page);
                $size = $pdf->getTemplateSize($tpl);
                $pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
                $pdf->useTemplate($tpl);
            }
            $outs[] = [
                'name' => $names[$i],
                'bytes' => $pdf->Output('S'),
                'pageCount' => $pdf->getNumPages(),
            ];
        }
        return $outs;
    } finally {
        @unlink($srcPath);
    }
}

/** Page count for UI display — the PHP twin of the TS countPages() helper. */
function countPages(string $bytes): int
{
    $srcPath = tempnam(sys_get_temp_dir(), 'pdfsplit');
    if ($srcPath === false) {
        throw new PdfToolError('invalid', 'Could not create a temp file.');
    }
    file_put_contents($srcPath, $bytes);
    try {
        $pdf = new Fpdi();
        return $pdf->setSourceFile($srcPath);
    } catch (Throwable $e) {
        throw mapError($e);
    } finally {
        @unlink($srcPath);
    }
}

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 →