Sample code for 30+ languages & platforms
AutoIt 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 AutoIt Downloads

AutoIt
Local $bSuccess = False

;  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

$oPdf = ObjCreate("Chilkat.Pdf")
$bSuccess = $oPdf.LoadFile("qa_data/pdf/watersense_accomplishments.pdf")
If ($bSuccess = False) Then
    ConsoleWrite($oPdf.LastErrorText & @CRLF)
    Exit
EndIf

$oJson = ObjCreate("Chilkat.JsonObject")
$oJsonOut = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oPdf.Optimize("audit",$oJson,$oJsonOut)
If ($bSuccess = False) Then
    ConsoleWrite($oPdf.LastErrorText & @CRLF)
    Exit
EndIf

Local $iFileSize = $oJsonOut.IntOf("fileSize")
Local $iEstimated = $oJsonOut.IntOf("estimatedSavings.total")
ConsoleWrite("fileSize:  " & $iFileSize & @CRLF)
ConsoleWrite("estimated: " & $iEstimated & @CRLF)

;  Only bother when at least a tenth of the file would go.
If ($iEstimated > ($iFileSize / 10)) Then
    ConsoleWrite("Worth optimizing." & @CRLF)
    $bSuccess = $oPdf.Optimize("optimize",$oJson,$oJsonOut)
    If ($bSuccess = False) Then
        ConsoleWrite($oPdf.LastErrorText & @CRLF)
        Exit
    EndIf

    $bSuccess = $oPdf.WriteFile("qa_output/watersense_optimized.pdf")
    If ($bSuccess = False) Then
        ConsoleWrite($oPdf.LastErrorText & @CRLF)
        Exit
    EndIf

    ConsoleWrite("bytesSaved: " & $oJsonOut.IntOf("bytesSaved") & @CRLF)
Else
    ConsoleWrite("Already small enough; left as it is." & @CRLF)
EndIf