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

Tcl

load ./chilkat.dll

set 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

set pdf [new_CkPdf]

set success [CkPdf_LoadFile $pdf "qa_data/pdf/watersense_accomplishments.pdf"]
if {$success == 0} then {
    puts [CkPdf_lastErrorText $pdf]
    delete_CkPdf $pdf
    exit
}

set json [new_CkJsonObject]

set jsonOut [new_CkJsonObject]

set success [CkPdf_Optimize $pdf "audit" $json $jsonOut]
if {$success == 0} then {
    puts [CkPdf_lastErrorText $pdf]
    delete_CkPdf $pdf
    delete_CkJsonObject $json
    delete_CkJsonObject $jsonOut
    exit
}

set fileSize [CkJsonObject_IntOf $jsonOut "fileSize"]
set estimated [CkJsonObject_IntOf $jsonOut "estimatedSavings.total"]
puts "fileSize:  $fileSize"
puts "estimated: $estimated"

#  Only bother when at least a tenth of the file would go.
if {$estimated > [expr $fileSize / 10]} then {
    puts "Worth optimizing."
    set success [CkPdf_Optimize $pdf "optimize" $json $jsonOut]
    if {$success == 0} then {
        puts [CkPdf_lastErrorText $pdf]
        delete_CkPdf $pdf
        delete_CkJsonObject $json
        delete_CkJsonObject $jsonOut
        exit
    }

    set success [CkPdf_WriteFile $pdf "qa_output/watersense_optimized.pdf"]
    if {$success == 0} then {
        puts [CkPdf_lastErrorText $pdf]
        delete_CkPdf $pdf
        delete_CkJsonObject $json
        delete_CkJsonObject $jsonOut
        exit
    }

    puts "bytesSaved: [CkJsonObject_IntOf $jsonOut bytesSaved]"
} else {
    puts "Already small enough; left as it is."
}


delete_CkPdf $pdf
delete_CkJsonObject $json
delete_CkJsonObject $jsonOut