Sample code for 30+ languages & platforms
PureBasic 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 PureBasic Downloads

PureBasic
IncludeFile "CkPdf.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 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

    pdf.i = CkPdf::ckCreate()
    If pdf.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPdf::ckLoadFile(pdf,"qa_data/pdf/watersense_accomplishments.pdf")
    If success = 0
        Debug CkPdf::ckLastErrorText(pdf)
        CkPdf::ckDispose(pdf)
        ProcedureReturn
    EndIf

    json.i = CkJsonObject::ckCreate()
    If json.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    jsonOut.i = CkJsonObject::ckCreate()
    If jsonOut.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPdf::ckOptimize(pdf,"audit",json,jsonOut)
    If success = 0
        Debug CkPdf::ckLastErrorText(pdf)
        CkPdf::ckDispose(pdf)
        CkJsonObject::ckDispose(json)
        CkJsonObject::ckDispose(jsonOut)
        ProcedureReturn
    EndIf

    fileSize.i = CkJsonObject::ckIntOf(jsonOut,"fileSize")
    estimated.i = CkJsonObject::ckIntOf(jsonOut,"estimatedSavings.total")
    Debug "fileSize:  " + Str(fileSize)
    Debug "estimated: " + Str(estimated)

    ;  Only bother when at least a tenth of the file would go.
    If estimated > (fileSize / 10)
        Debug "Worth optimizing."
        success = CkPdf::ckOptimize(pdf,"optimize",json,jsonOut)
        If success = 0
            Debug CkPdf::ckLastErrorText(pdf)
            CkPdf::ckDispose(pdf)
            CkJsonObject::ckDispose(json)
            CkJsonObject::ckDispose(jsonOut)
            ProcedureReturn
        EndIf

        success = CkPdf::ckWriteFile(pdf,"qa_output/watersense_optimized.pdf")
        If success = 0
            Debug CkPdf::ckLastErrorText(pdf)
            CkPdf::ckDispose(pdf)
            CkJsonObject::ckDispose(json)
            CkJsonObject::ckDispose(jsonOut)
            ProcedureReturn
        EndIf

        Debug "bytesSaved: " + Str(CkJsonObject::ckIntOf(jsonOut,"bytesSaved"))
    Else
        Debug "Already small enough; left as it is."
    EndIf



    CkPdf::ckDispose(pdf)
    CkJsonObject::ckDispose(json)
    CkJsonObject::ckDispose(jsonOut)


    ProcedureReturn
EndProcedure