Swift Requires Chilkat v11.7.0+
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// 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
let fac = CkoFileAccess()!
let json = CkoJsonObject()!
let jsonOut = CkoJsonObject()!
let pdf1 = CkoPdf()!
success = pdf1.loadFile(filePath: "qa_data/pdf/watersense_accomplishments.pdf")
if success == false {
print("\(pdf1.lastErrorText!)")
return
}
json.updateInt(jsonPath: "compressionLevel", value: 1)
success = pdf1.optimize(op: "optimize", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf1.lastErrorText!)")
return
}
success = pdf1.writeFile(path: "qa_output/watersense_level1.pdf")
if success == false {
print("\(pdf1.lastErrorText!)")
return
}
print("level 1: \(fac.fileSize(path: "qa_output/watersense_level1.pdf").intValue)")
let pdf9 = CkoPdf()!
success = pdf9.loadFile(filePath: "qa_data/pdf/watersense_accomplishments.pdf")
if success == false {
print("\(pdf9.lastErrorText!)")
return
}
json.updateInt(jsonPath: "compressionLevel", value: 9)
success = pdf9.optimize(op: "optimize", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf9.lastErrorText!)")
return
}
success = pdf9.writeFile(path: "qa_output/watersense_level9.pdf")
if success == false {
print("\(pdf9.lastErrorText!)")
return
}
print("level 9: \(fac.fileSize(path: "qa_output/watersense_level9.pdf").intValue)")
// A level outside 1..9 fails, and LastErrorText says why.
let pdfBad = CkoPdf()!
success = pdfBad.loadFile(filePath: "qa_data/pdf/watersense_accomplishments.pdf")
if success == false {
print("\(pdfBad.lastErrorText!)")
return
}
json.updateInt(jsonPath: "compressionLevel", value: 12)
success = pdfBad.optimize(op: "optimize", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("compressionLevel 12 was refused, as it should be.")
}
}