Skip to content

PDF Merge — PHP source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

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

<?php
/**
 * pdf-merge — merge many PDFs into one with FPDI (setasign/Fpdi on FPDF).
 * Authored snippet mirroring src/lib/pdf-merge.ts: empty input rejected,
 * encrypted vs invalid classified from the raw parse error, page count
 * returned for UI display. Each source page is imported as an FPDI template
 * and stamped onto a fresh page of the output in order.
 */

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.'
    );
}

/**
 * Copy every page of every input, in order, into one fresh PDF. Mirrors
 * mergePdfs() in src/lib/pdf-merge.ts.
 *
 * @param list<string> $docs raw PDF bytes, one entry per input document
 * @return array{bytes: string, pageCount: int}
 */
function mergePdfs(array $docs): array
{
    if ($docs === []) {
        throw new PdfToolError('invalid', 'Nothing to merge.');
    }
    $tmpFiles = [];
    try {
        $pdf = new Fpdi();
        foreach ($docs as $i => $bytes) {
            $path = tempnam(sys_get_temp_dir(), 'pdfmerge');
            if ($path === false) {
                throw new PdfToolError('invalid', 'Could not create a temp file.');
            }
            file_put_contents($path, $bytes);
            $tmpFiles[] = $path;
            try {
                $pageCount = $pdf->setSourceFile($path);
            } catch (Throwable $e) {
                throw mapError($e);
            }
            for ($page = 1; $page <= $pageCount; $page++) {
                $tpl = $pdf->importPage($page);
                $size = $pdf->getTemplateSize($tpl);
                $pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
                $pdf->useTemplate($tpl);
            }
        }
        return ['bytes' => $pdf->Output('S'), 'pageCount' => $pdf->getNumPages()];
    } finally {
        foreach ($tmpFiles as $path) {
            @unlink($path);
        }
    }
}

/** Page count for UI display — the PHP twin of the TS countPages() helper. */
function countPages(string $bytes): int
{
    $result = mergePdfs([$bytes]);
    return $result['pageCount'];
}

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 →