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

Password-Protect a PDF with AES-256 Encryption

See more PDF Protection Examples

Demonstrates the simplest way to encrypt a PDF so that it needs a password to open. The passwords come from the UserPassword and OwnerPassword properties, and Protection with the encrypt operation and an empty JSON uses the defaults: AES-256, everything encrypted, every permission granted. Protection only records the security the PDF will be saved with. Nothing is encrypted until WriteFile is called.

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

local pdf = chilkat.Pdf.new()
local success = pdf:load_file("qa_data/pdf/two_page_memo.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

-- The passwords are taken from these two properties at the time Protection is called.
-- The user password opens the PDF.  The owner password opens it too, and is the one needed
-- later to change or remove the protection.
pdf.user_password = "user-secret"
pdf.owner_password = "owner-secret"

-- An empty JSON asks for the defaults: AES-256, everything encrypted, every permission granted.
local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()
success = pdf:protection("encrypt", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

-- Nothing has been encrypted yet.  "pending" describes the security the PDF will be saved with.
print("algorithm: " .. jsonOut:string_of("pending.algorithm"))
print("PDF version: " .. jsonOut:string_of("pending.pdfVersion"))
print("password needed to open: " .. tostring(jsonOut:bool_of("pending.userPasswordRequired")))

-- Writing the file applies it.
success = pdf:write_file("qa_output/memo_encrypted.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

-- PreLoadCheck reports a file's encryption without loading it, and needs no password.
local checker = chilkat.Pdf.new()
local info = chilkat.JsonObject.new()
success = checker:pre_load_check("qa_output/memo_encrypted.pdf", info)
if not success then
    print(checker.last_error_text)
    return
end

print("encrypted: " .. tostring(info:bool_of("encrypted")))
print("openPasswordRequired: " .. tostring(info:bool_of("openPasswordRequired")))

-- With the password, the PDF opens normally.
local reader = chilkat.Pdf.new()
reader.user_password = "user-secret"
success = reader:load_file("qa_output/memo_encrypted.pdf")
if not success then
    print(reader.last_error_text)
    return
end

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

-- Sample output:

-- algorithm: aes-256
-- PDF version: 1.7
-- password needed to open: True
-- encrypted: True
-- openPasswordRequired: True
-- pages: 2