Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.7.0+

Audit a PDF First, Optimize Only If It Is Worth It

See more PDF Optimization Examples

Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\JsonObject;
use Chilkat2\Pdf;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// The PDF used in this example is available at watersense_accomplishments.pdf

$pdf = new Pdf();
try {
    $pdf->LoadFile('qa_data/pdf/watersense_accomplishments.pdf');

    $json = new JsonObject();
    $jsonOut = new JsonObject();
    $pdf->Optimize('audit', $json, $jsonOut);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$fileSize = $jsonOut->IntOf('fileSize');
$estimated = $jsonOut->IntOf('estimatedSavings.total');
echo 'fileSize:  ', $fileSize, "\n";
echo 'estimated: ', $estimated, "\n";

// Only bother when at least a tenth of the file would go.
if ($estimated > (intdiv($fileSize, 10))) {
    echo "Worth optimizing.\n";
    try {
        $pdf->Optimize('optimize', $json, $jsonOut);

        $pdf->WriteFile('qa_output/watersense_optimized.pdf');
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }

    echo 'bytesSaved: ', $jsonOut->IntOf('bytesSaved'), "\n";
} else {
    echo "Already small enough; left as it is.\n";
}