PDF Compress — PHP source
Shrink PDF file sizes in your browser — lossless optimization plus a JPEG quality slider for embedded images. Nothing uploads.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* pdf-compress — qpdf-driven compression for PHP. Honest scope note: PHP has
* no clean client-side recompressor for embedded JPEGs (FPDI stamps pages,
* it does not rewrite image streams), so the closest idiomatic equivalent is
* driving the qpdf binary — `--object-streams=generate --compress-streams=y`
* is the lossless floor the TS pass 1 performs — and porting the
* chooseImageAction decision verbatim so the JPEG walk can be added the
* moment a PHP rasterizer earns its keep.
*/
declare(strict_types=1);
/** 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 qpdf's stderr. */
function classifyLoadError(string $stderr): string
{
return preg_match('/encrypt|password/i', $stderr) === 1
? 'encrypted'
: 'invalid';
}
/** Map a failed qpdf run to a user-facing PdfToolError. */
function mapQpdfError(string $stderr): PdfToolError
{
$kind = classifyLoadError($stderr);
return new PdfToolError(
$kind,
$kind === 'encrypted'
? 'This PDF is password-protected. Unlock it first.'
: 'Not a readable PDF file.'
);
}
/**
* Pure decision: only baseline single-stream JPEGs (/Filter /DCTDecode) are
* recompressible — anything else (Flate, multi-filter arrays, no filter)
* stays byte-for-byte intact. Ported verbatim from chooseImageAction() in
* src/lib/pdf-compress.ts.
*/
function chooseImageAction(string $filter): string
{
return $filter === 'DCTDecode' ? 'recompress' : 'skip';
}
/**
* Lossless floor: re-save through qpdf with object streams generated and
* stream compression on. (The JPEG recompression pass of the TS tool —
* decode + re-encode at lower quality at identical pixel dimensions — has
* no PHP-side equivalent wired here; chooseImageAction above is the hook.)
*
* @return array{bytes: string, total: int}
*/
function compressPdf(string $bytes, float $quality): array
{
$src = tempnam(sys_get_temp_dir(), 'pdfcmp-src');
$dst = tempnam(sys_get_temp_dir(), 'pdfcmp-dst');
if ($src === false || $dst === false) {
throw new PdfToolError('invalid', 'Could not create a temp file.');
}
file_put_contents($src, $bytes);
try {
$cmd = sprintf(
'qpdf %s --object-streams=generate --compress-streams=y %s %s 2>&1',
escapeshellarg($src),
escapeshellarg($dst),
'', // placeholder keeps the ordering obvious: src before dst
);
// qpdf CLI order is: qpdf [options] infile outfile.
$cmd = sprintf(
'qpdf --object-streams=generate --compress-streams=y %s %s 2>&1',
escapeshellarg($src),
escapeshellarg($dst),
);
exec($cmd, $outputLines, $exitCode);
$stderr = implode("\n", $outputLines);
if ($exitCode !== 0) {
throw mapQpdfError($stderr);
}
return ['bytes' => (string) file_get_contents($dst), 'total' => 0];
} finally {
@unlink($src);
@unlink($dst);
}
}
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 →