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

Remove PDF Objects Nothing Refers To

See more PDF Optimization Examples

Demonstrates removeUnreferenced. When a page, an image or a whole section is replaced in an editor, the objects it used often stay in the file with nothing pointing at them any more. They are not old revisions -- they are in the current revision, simply unreachable -- so only a reachability walk from the document catalog finds them. In a publication assembled over several editing passes this is frequently the largest single saving.

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

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

local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()
success = pdf:optimize("audit", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

print("fileSize: " .. jsonOut:int_of("fileSize"))
print("removeUnreferenced would save: " .. jsonOut:int_of("estimatedSavings.removeUnreferenced"))

-- Optimize with the defaults and see how many objects were actually dropped.
success = pdf:optimize("optimize", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

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

print("objects removed: " .. jsonOut:int_of("actions.removeUnreferenced.count"))
print("bytes saved:     " .. jsonOut:int_of("actions.removeUnreferenced.bytesSaved"))

-- Nothing a page needs is ever removed: the walk starts at the document catalog and follows every
-- reference, including the ones in annotations, the structure tree, named destinations and the
-- optional-content configuration.
print("pages after: " .. pdf.num_pages)