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

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 B4X Downloads

B4X
Dim success As Boolean = 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 invoice_signed.pdf

Dim pdf As ChilkatPdf
pdf.Initialize("pdf")
success = pdf.LoadFile("qa_data/pdf/invoice_signed.pdf")
If success = False Then
    Log(pdf.LastErrorText)
    Return
End If


Log("signatures: " & pdf.NumSignatures)

Dim json As ChilkatJsonObject
json.Initialize
Dim jsonOut As ChilkatJsonObject
jsonOut.Initialize

'  An audit changes nothing, so it is allowed on a signed PDF.
success = pdf.Optimize("audit", json, jsonOut)
If success = False Then
    Log(pdf.LastErrorText)
    Return
End If

Log("audit ok, estimated savings: " & jsonOut.IntOf("estimatedSavings.total"))

'  Optimizing is refused while PreserveSignatures is true.
success = pdf.Optimize("optimize", json, jsonOut)
If success = False Then
    Log("Refused while PreserveSignatures is true.")
End If


'  Allow the rewrite.  Do this only when the signatures no longer matter -- an invoice being
'  archived, say, where the signed original is kept elsewhere.
pdf.PreserveSignatures = False
success = pdf.Optimize("optimize", json, jsonOut)
If success = False Then
    Log(pdf.LastErrorText)
    Return
End If

success = pdf.WriteFile("qa_output/invoice_optimized.pdf")
If success = False Then
    Log(pdf.LastErrorText)
    Return
End If

Log("optimized, bytesSaved: " & jsonOut.IntOf("bytesSaved"))

'  The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
Dim pdf2 As ChilkatPdf
pdf2.Initialize("pdf2")
success = pdf2.LoadFile("qa_output/invoice_optimized.pdf")
If success = False Then
    Log(pdf2.LastErrorText)
    Return
End If

Log("signatures after: " & pdf2.NumSignatures)

Dim sigInfo As ChilkatJsonObject
sigInfo.Initialize
Dim verified As Boolean = pdf2.VerifySignature(0, sigInfo)
Log("verifies after optimizing: " & verified)