PHP ActiveX Requires Chilkat v11.7.0+
PHP ActiveX
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 ActiveX Downloads
<?php
$success = 0;
// 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 COM("Chilkat.Pdf");
$success = $pdf->LoadFile('qa_data/pdf/watersense_accomplishments.pdf');
if ($success == 0) {
print $pdf->LastErrorText . "\n";
exit;
}
$json = new COM("Chilkat.JsonObject");
$jsonOut = new COM("Chilkat.JsonObject");
$success = $pdf->Optimize('audit',$json,$jsonOut);
if ($success == 0) {
print $pdf->LastErrorText . "\n";
exit;
}
$fileSize = $jsonOut->IntOf('fileSize');
$estimated = $jsonOut->IntOf('estimatedSavings.total');
print 'fileSize: ' . $fileSize . "\n";
print 'estimated: ' . $estimated . "\n";
// Only bother when at least a tenth of the file would go.
if ($estimated > ($fileSize / 10)) {
print 'Worth optimizing.' . "\n";
$success = $pdf->Optimize('optimize',$json,$jsonOut);
if ($success == 0) {
print $pdf->LastErrorText . "\n";
exit;
}
$success = $pdf->WriteFile('qa_output/watersense_optimized.pdf');
if ($success == 0) {
print $pdf->LastErrorText . "\n";
exit;
}
print 'bytesSaved: ' . $jsonOut->IntOf('bytesSaved') . "\n";
}
else {
print 'Already small enough; left as it is.' . "\n";
}
?>