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

Deflate Compression Level When Optimizing a PDF

See more PDF Optimization Examples

Demonstrates compressionLevel, which is the deflate level (1 to 9, 9 by default) used for every stream the optimizer re-encodes. Level 9 is the smallest and the slowest; level 1 is the quickest. The difference is usually a percent or two, so level 9 is the right default for a file that will be downloaded many times, and a lower level is worth considering only when a server optimizes PDFs on the fly. A value outside 1 to 9 is an error.

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 fac = chilkat.FileAccess.new()
local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()

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

json:update_int("compressionLevel", 1)
success = pdf1:optimize("optimize", json, jsonOut)
if not success then
    print(pdf1.last_error_text)
    return
end

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

print("level 1: " .. fac:file_size("qa_output/watersense_level1.pdf"))

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

json:update_int("compressionLevel", 9)
success = pdf9:optimize("optimize", json, jsonOut)
if not success then
    print(pdf9.last_error_text)
    return
end

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

print("level 9: " .. fac:file_size("qa_output/watersense_level9.pdf"))

-- A level outside 1..9 fails, and LastErrorText says why.
local pdfBad = chilkat.Pdf.new()
success = pdfBad:load_file("qa_data/pdf/watersense_accomplishments.pdf")
if not success then
    print(pdfBad.last_error_text)
    return
end

json:update_int("compressionLevel", 12)
success = pdfBad:optimize("optimize", json, jsonOut)
if not success then
    print("compressionLevel 12 was refused, as it should be.")
end