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

Deflate Compression Level When Optimizing a PDF

See more PDF Optimization Examples

Demonstrates compressionLevel, which is the deflate level (1 to 9, 9 by default) used for every stream the optimizer re-encodes. Level 9 is the smallest and the slowest; level 1 is the quickest. The difference is usually a percent or two, so level 9 is the right default for a file that will be downloaded many times, and a lower level is worth considering only when a server optimizes PDFs on the fly. A value outside 1 to 9 is an error.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\FileAccess;
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

$fac = new FileAccess();
$json = new JsonObject();
$jsonOut = new JsonObject();

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

    $json->UpdateInt('compressionLevel', 1);
    $pdf1->Optimize('optimize', $json, $jsonOut);

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

echo 'level 1: ', $fac->FileSize('qa_output/watersense_level1.pdf'), "\n";

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

    $json->UpdateInt('compressionLevel', 9);
    $pdf9->Optimize('optimize', $json, $jsonOut);

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

echo 'level 9: ', $fac->FileSize('qa_output/watersense_level9.pdf'), "\n";

// A level outside 1..9 fails, and LastErrorText says why.
$pdfBad = new Pdf();
try {
    $pdfBad->LoadFile('qa_data/pdf/watersense_accomplishments.pdf');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$json->UpdateInt('compressionLevel', 12);
try {
    $pdfBad->Optimize('optimize', $json, $jsonOut);
} catch (\Chilkat2\Exception $e) {
    echo "compressionLevel 12 was refused, as it should be.\n";
}