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

Remove a PDF's Old Revisions

See more PDF Optimization Examples

Demonstrates dropOldRevisions. A PDF that has been edited and saved several times carries every earlier revision: the superseded objects are still in the file, reachable through the older cross-reference sections. The audit reports them as "oldRevisions", and dropping them is often the single largest saving in a real document. Dropping them requires a full rewrite, which is why it invalidates existing digital signatures.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oPdf
LOCAL oJson
LOCAL oJsonOut
LOCAL oFac

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 grand_canyon_hiking_guide.pdf

oPdf := CreateObject("Chilkat.Pdf")
nSuccess := oPdf:LoadFile("qa_data/pdf/grand_canyon_hiking_guide.pdf")
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    RETURN
ENDIF

//  How much of this file is superseded revisions?
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

? "fileSize:     " + Str(oJsonOut:IntOf("fileSize"))
? "oldRevisions: " + Str(oJsonOut:IntOf("usage.oldRevisions.bytes"))

//  Drop them, and nothing else, so that the saving is attributable.
oJson:UpdateBool("compressUncompressed", 0)
oJson:UpdateBool("recompressFlate", 0)
oJson:UpdateBool("replaceLegacyFilters", 0)
oJson:UpdateBool("imagePredictors", 0)
oJson:UpdateBool("dedupeStreams", 0)
oJson:UpdateBool("dedupeObjects", 0)
oJson:UpdateBool("removeUnreferenced", 0)
oJson:UpdateBool("removeUnusedResources", 0)
oJson:UpdateBool("removeUnusedLayers", 0)
oJson:UpdateBool("coalesceContent", 0)
oJson:UpdateBool("tidyContent", 0)
oJson:UpdateBool("subsetFonts", 0)
oJson:UpdateBool("dropOldRevisions", 1)

nSuccess := oPdf:Optimize("optimize", oJson, oJsonOut)
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

nSuccess := oPdf:WriteFile("qa_output/grand_canyon_one_revision.pdf")
IF (nSuccess == 0)
    ? oPdf:LastErrorText
    oPdf:destroy()
    oJson:destroy()
    oJsonOut:destroy()
    RETURN
ENDIF

//  The saving is an estimate: what the old revisions occupied is known exactly, but the writer
//  decides the final layout.  Measure the written file for the real number.
oFac := CreateObject("Chilkat.FileAccess")
? "bytesSaved (reported): " + Str(oJsonOut:IntOf("bytesSaved"))
? "written file:          " + Str(oFac:FileSize("qa_output/grand_canyon_one_revision.pdf"))

oPdf:destroy()
oJson:destroy()
oJsonOut:destroy()
oFac:destroy()