Xbase++ Requires Chilkat v11.7.0+
Xbase++
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 Xbase++ Downloads
LOCAL nSuccess
LOCAL oPdf
LOCAL oJson
LOCAL oJsonOut
LOCAL nFileSize
LOCAL nEstimated
nSuccess := 0
// 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
oPdf := CreateObject("Chilkat.Pdf")
nSuccess := oPdf:LoadFile("qa_data/pdf/watersense_accomplishments.pdf")
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
RETURN
ENDIF
oJson := CreateObject("Chilkat.JsonObject")
oJsonOut := CreateObject("Chilkat.JsonObject")
nSuccess := oPdf:Optimize("audit", oJson, oJsonOut)
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
nFileSize := oJsonOut:IntOf("fileSize")
nEstimated := oJsonOut:IntOf("estimatedSavings.total")
? "fileSize: " + Str(nFileSize)
? "estimated: " + Str(nEstimated)
// Only bother when at least a tenth of the file would go.
IF (nEstimated > (nFileSize / 10))
? "Worth optimizing."
nSuccess := oPdf:Optimize("optimize", oJson, oJsonOut)
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
nSuccess := oPdf:WriteFile("qa_output/watersense_optimized.pdf")
IF (nSuccess == 0)
? oPdf:LastErrorText
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
RETURN
ENDIF
? "bytesSaved: " + Str(oJsonOut:IntOf("bytesSaved"))
ELSE
? "Already small enough; left as it is."
ENDIF
oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()