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

Optimize a PDF Without Rewriting It (Incremental Update)

See more PDF Optimization Examples

Demonstrates the one combination of options that does not rewrite the file. With dropOldRevisions false and objectStreams "disable", the optimized objects are appended to the original bytes as an incremental update: every byte of the input is still there, byte for byte, followed by the changes and a new cross-reference section. That is what keeps an existing digital signature valid, and what lets a reader that has the original cached fetch only the tail. The file gets a little larger before it gets smaller, so this is for compatibility, not for size.

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]

CkJsonObject_UpdateBool $json "dropOldRevisions" 0
CkJsonObject_UpdateString $json "objectStreams" "disable"

set jsonOut [new_CkJsonObject]

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_incremental.pdf"]
if {$success == 0} then {
    puts [CkPdf_lastErrorText $pdf]
    delete_CkPdf $pdf
    delete_CkJsonObject $json
    delete_CkJsonObject $jsonOut
    exit
}

set fac [new_CkFileAccess]

puts "original: [CkJsonObject_IntOf $jsonOut fileSize]"
puts "written:  [CkFileAccess_FileSize $fac qa_output/watersense_incremental.pdf]"

#  Everything the optimizer changed is in the appended part; the original bytes are the start of the
#  new file.  Any other combination of options -- dropOldRevisions, or generated object streams --
#  rewrites the document instead.
puts "bytesSaved: [CkJsonObject_IntOf $jsonOut bytesSaved]"

delete_CkPdf $pdf
delete_CkJsonObject $json
delete_CkJsonObject $jsonOut
delete_CkFileAccess $fac