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

Visual FoxPro
LOCAL lnSuccess
LOCAL loPdf
LOCAL loJson
LOCAL loJsonOut
LOCAL lnFileSize
LOCAL lnEstimated

lnSuccess = 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

loPdf = CreateObject('Chilkat.Pdf')
lnSuccess = loPdf.LoadFile("qa_data/pdf/watersense_accomplishments.pdf")
IF (lnSuccess = 0) THEN
    ? loPdf.LastErrorText
    RELEASE loPdf
    CANCEL
ENDIF

loJson = CreateObject('Chilkat.JsonObject')
loJsonOut = CreateObject('Chilkat.JsonObject')
lnSuccess = loPdf.Optimize("audit",loJson,loJsonOut)
IF (lnSuccess = 0) THEN
    ? loPdf.LastErrorText
    RELEASE loPdf
    RELEASE loJson
    RELEASE loJsonOut
    CANCEL
ENDIF

lnFileSize = loJsonOut.IntOf("fileSize")
lnEstimated = loJsonOut.IntOf("estimatedSavings.total")
? "fileSize:  " + STR(lnFileSize)
? "estimated: " + STR(lnEstimated)

*  Only bother when at least a tenth of the file would go.
IF (lnEstimated > (lnFileSize / 10)) THEN
    ? "Worth optimizing."
    lnSuccess = loPdf.Optimize("optimize",loJson,loJsonOut)
    IF (lnSuccess = 0) THEN
        ? loPdf.LastErrorText
        RELEASE loPdf
        RELEASE loJson
        RELEASE loJsonOut
        CANCEL
    ENDIF

    lnSuccess = loPdf.WriteFile("qa_output/watersense_optimized.pdf")
    IF (lnSuccess = 0) THEN
        ? loPdf.LastErrorText
        RELEASE loPdf
        RELEASE loJson
        RELEASE loJsonOut
        CANCEL
    ENDIF

    ? "bytesSaved: " + STR(loJsonOut.IntOf("bytesSaved"))
ELSE
    ? "Already small enough; left as it is."
ENDIF

RELEASE loPdf
RELEASE loJson
RELEASE loJsonOut