B4X Requires Chilkat v11.7.0+
B4X
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 B4X Downloads
Dim success As Boolean = 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
Dim pdf As ChilkatPdf
pdf.Initialize("pdf")
' The password must be set before loading.
pdf.UserPassword = "secret"
success = pdf.LoadFile("qa_data/pdf/encrypted_user_password.pdf")
If success = False Then
Log(pdf.LastErrorText)
Return
End If
' What security does the file have, and may it be modified?
Dim json As ChilkatJsonObject
json.Initialize
Dim jsonOut As ChilkatJsonObject
jsonOut.Initialize
success = pdf.Protection("getInfo", json, jsonOut)
If success = False Then
Log(pdf.LastErrorText)
Return
End If
Log("encrypted: " & jsonOut.BoolOf("loaded.encrypted"))
Log("method: " & jsonOut.StringOf("loaded.method"))
Log("openedWith: " & jsonOut.StringOf("loaded.openedWith"))
Log("may modify: " & jsonOut.BoolOf("loaded.permissions.modify"))
success = pdf.Optimize("optimize", json, jsonOut)
If success = False Then
Log(pdf.LastErrorText)
Return
End If
success = pdf.WriteFile("qa_output/encrypted_optimized.pdf")
If success = False Then
Log(pdf.LastErrorText)
Return
End If
Log("bytesSaved: " & jsonOut.IntOf("bytesSaved"))
' The output is still encrypted with the same security: loading it without the password fails.
Dim noPassword As ChilkatPdf
noPassword.Initialize("noPassword")
success = noPassword.LoadFile("qa_output/encrypted_optimized.pdf")
Dim q As ChilkatJsonObject
q.Initialize
Dim qOut As ChilkatJsonObject
qOut.Initialize
success = noPassword.ExtractText("assess", q, qOut)
Log("passwordRequired without the password: " & qOut.BoolOf("quality.passwordRequired"))
' With the password it reads normally.
Dim withPassword As ChilkatPdf
withPassword.Initialize("withPassword")
withPassword.UserPassword = "secret"
success = withPassword.LoadFile("qa_output/encrypted_optimized.pdf")
If success = False Then
Log(withPassword.LastErrorText)
Return
End If
Log("pages: " & withPassword.NumPages)