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

Remove PDF Objects Nothing Refers To

See more PDF Optimization Examples

Demonstrates removeUnreferenced. When a page, an image or a whole section is replaced in an editor, the objects it used often stay in the file with nothing pointing at them any more. They are not old revisions -- they are in the current revision, simply unreachable -- so only a reachability walk from the document catalog finds them. In a publication assembled over several editing passes this is frequently the largest single saving.

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Pdf
oleobject loo_Json
oleobject loo_JsonOut

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

loo_Pdf = create oleobject
li_rc = loo_Pdf.ConnectToNewObject("Chilkat.Pdf")
if li_rc < 0 then
    destroy loo_Pdf
    MessageBox("Error","Connecting to COM object failed")
    return
end if
li_Success = loo_Pdf.LoadFile("qa_data/pdf/watersense_accomplishments.pdf")
if li_Success = 0 then
    Write-Debug loo_Pdf.LastErrorText
    destroy loo_Pdf
    return
end if

loo_Json = create oleobject
li_rc = loo_Json.ConnectToNewObject("Chilkat.JsonObject")

loo_JsonOut = create oleobject
li_rc = loo_JsonOut.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_Pdf.Optimize("audit",loo_Json,loo_JsonOut)
if li_Success = 0 then
    Write-Debug loo_Pdf.LastErrorText
    destroy loo_Pdf
    destroy loo_Json
    destroy loo_JsonOut
    return
end if

Write-Debug "fileSize: " + string(loo_JsonOut.IntOf("fileSize"))
Write-Debug "removeUnreferenced would save: " + string(loo_JsonOut.IntOf("estimatedSavings.removeUnreferenced"))

//  Optimize with the defaults and see how many objects were actually dropped.
li_Success = loo_Pdf.Optimize("optimize",loo_Json,loo_JsonOut)
if li_Success = 0 then
    Write-Debug loo_Pdf.LastErrorText
    destroy loo_Pdf
    destroy loo_Json
    destroy loo_JsonOut
    return
end if

li_Success = loo_Pdf.WriteFile("qa_output/watersense_optimized.pdf")
if li_Success = 0 then
    Write-Debug loo_Pdf.LastErrorText
    destroy loo_Pdf
    destroy loo_Json
    destroy loo_JsonOut
    return
end if

Write-Debug "objects removed: " + string(loo_JsonOut.IntOf("actions.removeUnreferenced.count"))
Write-Debug "bytes saved:     " + string(loo_JsonOut.IntOf("actions.removeUnreferenced.bytesSaved"))

//  Nothing a page needs is ever removed: the walk starts at the document catalog and follows every
//  reference, including the ones in annotations, the structure tree, named destinations and the
//  optional-content configuration.
Write-Debug "pages after: " + string(loo_Pdf.NumPages)


destroy loo_Pdf
destroy loo_Json
destroy loo_JsonOut