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

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 Xojo Plugin Downloads

Xojo Plugin
Dim success As Boolean
success = 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

Dim pdf As New Chilkat.Pdf
success = pdf.LoadFile("qa_data/pdf/watersense_accomplishments.pdf")
If (success = False) Then
    System.DebugLog(pdf.LastErrorText)
    Return
End If

Dim json As New Chilkat.JsonObject
Dim jsonOut As New Chilkat.JsonObject
success = pdf.Optimize("audit",json,jsonOut)
If (success = False) Then
    System.DebugLog(pdf.LastErrorText)
    Return
End If

Dim fileSize As Int32
fileSize = jsonOut.IntOf("fileSize")
Dim estimated As Int32
estimated = jsonOut.IntOf("estimatedSavings.total")
System.DebugLog("fileSize:  " + Str(fileSize))
System.DebugLog("estimated: " + Str(estimated))

//  Only bother when at least a tenth of the file would go.
If (estimated > (fileSize / 10)) Then
    System.DebugLog("Worth optimizing.")
    success = pdf.Optimize("optimize",json,jsonOut)
    If (success = False) Then
        System.DebugLog(pdf.LastErrorText)
        Return
    End If

    success = pdf.WriteFile("qa_output/watersense_optimized.pdf")
    If (success = False) Then
        System.DebugLog(pdf.LastErrorText)
        Return
    End If

    System.DebugLog("bytesSaved: " + Str(jsonOut.IntOf("bytesSaved")))
Else
    System.DebugLog("Already small enough; left as it is.")
End If