Lua Requires Chilkat v11.7.0+
Lua
Audit a PDF First, Optimize Only If It Is Worth It
See more PDF Optimization Examples
Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.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 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
local fileSize = jsonOut:int_of("fileSize")
local estimated = jsonOut:int_of("estimatedSavings.total")
print("fileSize: " .. fileSize)
print("estimated: " .. estimated)
-- Only bother when at least a tenth of the file would go.
if estimated > (math.floor(fileSize / 10)) then
print("Worth optimizing.")
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("bytesSaved: " .. jsonOut:int_of("bytesSaved"))
else
print("Already small enough; left as it is.")
end