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

Optimizing an Encrypted PDF

See more PDF Optimization Examples

Demonstrates optimizing a PDF that is encrypted. Set the password before loading, exactly as for any other operation; the optimized PDF keeps the security it had, so the output still needs the same password. Because Chilkat honours the permissions recorded in the document, optimizing requires owner rights or the "modify" permission: a PDF opened with a user password that forbids modification can be audited but not optimized.

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 encrypted_user_password.pdf

local pdf = chilkat.Pdf.new()

-- The password must be set before loading.
pdf.user_password = "secret"
local success = pdf:load_file("qa_data/pdf/encrypted_user_password.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

-- What security does the file have, and may it be modified?
local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()
success = pdf:protection("getInfo", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

print("encrypted: " .. tostring(jsonOut:bool_of("loaded.encrypted")))
print("method:    " .. jsonOut:string_of("loaded.method"))
print("openedWith: " .. jsonOut:string_of("loaded.openedWith"))
print("may modify: " .. tostring(jsonOut:bool_of("loaded.permissions.modify")))

success = pdf:optimize("optimize", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

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

print("bytesSaved: " .. jsonOut:int_of("bytesSaved"))

-- The output is still encrypted with the same security: loading it without the password fails.
local noPassword = chilkat.Pdf.new()
success = noPassword:load_file("qa_output/encrypted_optimized.pdf")
local q = chilkat.JsonObject.new()
local qOut = chilkat.JsonObject.new()
success = noPassword:extract_text("assess", q, qOut)
print("passwordRequired without the password: " .. tostring(qOut:bool_of("quality.passwordRequired")))

-- With the password it reads normally.
local withPassword = chilkat.Pdf.new()
withPassword.user_password = "secret"
success = withPassword:load_file("qa_output/encrypted_optimized.pdf")
if not success then
    print(withPassword.last_error_text)
    return
end

print("pages: " .. withPassword.num_pages)