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

Optimizing an Encrypted PDF

See more PDF Optimization Examples

Demonstrates optimizing a PDF that is encrypted. Set the password before loading, exactly as for any other operation; the optimized PDF keeps the security it had, so the output still needs the same password. Because Chilkat honours the permissions recorded in the document, optimizing requires owner rights or the "modify" permission: a PDF opened with a user password that forbids modification can be audited but not optimized.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = 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 encrypted_user_password.pdf

$oPdf = ObjCreate("Chilkat.Pdf")

;  The password must be set before loading.
$oPdf.UserPassword = "secret"
$bSuccess = $oPdf.LoadFile("qa_data/pdf/encrypted_user_password.pdf")
If ($bSuccess = False) Then
    ConsoleWrite($oPdf.LastErrorText & @CRLF)
    Exit
EndIf

;  What security does the file have, and may it be modified?
$oJson = ObjCreate("Chilkat.JsonObject")
$oJsonOut = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oPdf.Protection("getInfo",$oJson,$oJsonOut)
If ($bSuccess = False) Then
    ConsoleWrite($oPdf.LastErrorText & @CRLF)
    Exit
EndIf

ConsoleWrite("encrypted: " & $oJsonOut.BoolOf("loaded.encrypted") & @CRLF)
ConsoleWrite("method:    " & $oJsonOut.StringOf("loaded.method") & @CRLF)
ConsoleWrite("openedWith: " & $oJsonOut.StringOf("loaded.openedWith") & @CRLF)
ConsoleWrite("may modify: " & $oJsonOut.BoolOf("loaded.permissions.modify") & @CRLF)

$bSuccess = $oPdf.Optimize("optimize",$oJson,$oJsonOut)
If ($bSuccess = False) Then
    ConsoleWrite($oPdf.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oPdf.WriteFile("qa_output/encrypted_optimized.pdf")
If ($bSuccess = False) Then
    ConsoleWrite($oPdf.LastErrorText & @CRLF)
    Exit
EndIf

ConsoleWrite("bytesSaved: " & $oJsonOut.IntOf("bytesSaved") & @CRLF)

;  The output is still encrypted with the same security: loading it without the password fails.
$oNoPassword = ObjCreate("Chilkat.Pdf")
$bSuccess = $oNoPassword.LoadFile("qa_output/encrypted_optimized.pdf")
$oQ = ObjCreate("Chilkat.JsonObject")
$oQOut = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oNoPassword.ExtractText("assess",$oQ,$oQOut)
ConsoleWrite("passwordRequired without the password: " & $oQOut.BoolOf("quality.passwordRequired") & @CRLF)

;  With the password it reads normally.
$oWithPassword = ObjCreate("Chilkat.Pdf")
$oWithPassword.UserPassword = "secret"
$bSuccess = $oWithPassword.LoadFile("qa_output/encrypted_optimized.pdf")
If ($bSuccess = False) Then
    ConsoleWrite($oWithPassword.LastErrorText & @CRLF)
    Exit
EndIf

ConsoleWrite("pages: " & $oWithPassword.NumPages & @CRLF)