Lua Requires Chilkat v11.7.0+
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- 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
local pdf = chilkat.Pdf.new()
local success = pdf:load_file("qa_data/pdf/invoice_signed.pdf")
if not success then
print(pdf.last_error_text)
return
end
print("signatures: " .. pdf.num_signatures)
local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()
-- An audit changes nothing, so it is allowed on a signed PDF.
success = pdf:optimize("audit", json, jsonOut)
if not success then
print(pdf.last_error_text)
return
end
print("audit ok, estimated savings: " .. jsonOut:int_of("estimatedSavings.total"))
-- Optimizing is refused while PreserveSignatures is true.
success = pdf:optimize("optimize", json, jsonOut)
if not success then
print("Refused while PreserveSignatures is true.")
end
-- 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.preserve_signatures = false
success = pdf:optimize("optimize", json, jsonOut)
if not success then
print(pdf.last_error_text)
return
end
success = pdf:write_file("qa_output/invoice_optimized.pdf")
if not success then
print(pdf.last_error_text)
return
end
print("optimized, bytesSaved: " .. jsonOut:int_of("bytesSaved"))
-- The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
local pdf2 = chilkat.Pdf.new()
success = pdf2:load_file("qa_output/invoice_optimized.pdf")
if not success then
print(pdf2.last_error_text)
return
end
print("signatures after: " .. pdf2.num_signatures)
local sigInfo = chilkat.JsonObject.new()
local verified = pdf2:verify_signature(0, sigInfo)
print("verifies after optimizing: " .. tostring(verified))