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

Watermark a Signed PDF Without Breaking the Signature

See more PDF Watermark Examples

Demonstrates the one approach a signed PDF accepts while its signatures are being preserved. Adding a watermark to the page content rewrites the page, which invalidates every existing signature, so with PreserveSignatures true (the default) only the annotation approach is allowed: an annotation is added as an incremental update that leaves the signed bytes untouched. Removing anything is refused for the same reason. Set PreserveSignatures to false to allow the other approaches, and the signatures in the file stop verifying.

Chilkat Lua Downloads

Lua
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()
json:update_string("type", "text")
json:update_string("text", "PAID")
json:update_string("id", "paid")
json:update_string("color", "#2E7D32")
json:update_string("position.align", "topRight")
json:update_number("position.margin", "36")

-- An artifact watermark changes the page content, so it is refused while the signatures matter.
json:update_string("approach", "artifact")
success = pdf:watermark("add", json, jsonOut)
if not success then
    print("The artifact approach was refused on a signed PDF, as it should be.")
end

-- An annotation is added without touching the signed bytes.
json:update_string("approach", "annotation")
success = pdf:watermark("add", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

print("annotation added, pages: " .. jsonOut:string_of("pages"))

success = pdf:write_file("qa_output/invoice_paid.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

-- The signature still verifies: the original bytes are unchanged and the annotation was appended.
local check = chilkat.Pdf.new()
success = check:load_file("qa_output/invoice_paid.pdf")
if not success then
    print(check.last_error_text)
    return
end

local sigInfo = chilkat.JsonObject.new()
local verified = check:verify_signature(0, sigInfo)
print("signature still verifies: " .. tostring(verified))

-- Sample output:

-- signatures: 1
-- The artifact approach was refused on a signed PDF, as it should be.
-- annotation added, pages: 1
-- signature still verifies: True