Tcl Requires Chilkat v11.7.0+
Tcl
Optimizing a Signed PDF (PreserveSignatures)
See more PDF Optimization Examples
Demonstrates what happens when a signed PDF is optimized. Optimizing rewrites the document, and a rewrite breaks every existing digital signature, so with PreserveSignatures true (the default) Optimize refuses and LastErrorText says why. Setting PreserveSignatures to false allows it, and the signature that was in the file no longer verifies afterwards. "audit" is always allowed, because it changes nothing.Chilkat Tcl Downloads
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 invoice_signed.pdf
set pdf [new_CkPdf]
set success [CkPdf_LoadFile $pdf "qa_data/pdf/invoice_signed.pdf"]
if {$success == 0} then {
puts [CkPdf_lastErrorText $pdf]
delete_CkPdf $pdf
exit
}
puts "signatures: [CkPdf_get_NumSignatures $pdf]"
set json [new_CkJsonObject]
set jsonOut [new_CkJsonObject]
# An audit changes nothing, so it is allowed on a signed PDF.
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
}
puts "audit ok, estimated savings: [CkJsonObject_IntOf $jsonOut estimatedSavings.total]"
# Optimizing is refused while PreserveSignatures is true.
set success [CkPdf_Optimize $pdf "optimize" $json $jsonOut]
if {$success == 0} then {
puts "Refused while PreserveSignatures is true."
}
# Allow the rewrite. Do this only when the signatures no longer matter -- an invoice being
# archived, say, where the signed original is kept elsewhere.
CkPdf_put_PreserveSignatures $pdf 0
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/invoice_optimized.pdf"]
if {$success == 0} then {
puts [CkPdf_lastErrorText $pdf]
delete_CkPdf $pdf
delete_CkJsonObject $json
delete_CkJsonObject $jsonOut
exit
}
puts "optimized, bytesSaved: [CkJsonObject_IntOf $jsonOut bytesSaved]"
# The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
set pdf2 [new_CkPdf]
set success [CkPdf_LoadFile $pdf2 "qa_output/invoice_optimized.pdf"]
if {$success == 0} then {
puts [CkPdf_lastErrorText $pdf2]
delete_CkPdf $pdf
delete_CkJsonObject $json
delete_CkJsonObject $jsonOut
delete_CkPdf $pdf2
exit
}
puts "signatures after: [CkPdf_get_NumSignatures $pdf2]"
set sigInfo [new_CkJsonObject]
set verified [CkPdf_VerifySignature $pdf2 0 $sigInfo]
puts "verifies after optimizing: $verified"
delete_CkPdf $pdf
delete_CkJsonObject $json
delete_CkJsonObject $jsonOut
delete_CkPdf $pdf2
delete_CkJsonObject $sigInfo