Java Requires Chilkat v11.7.0+
Chilkat2 Java
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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Pdf;
public class ChilkatExample {
public static void main(String[] args) {
// 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
Pdf pdf = new Pdf();
// The password must be set before loading.
pdf.setUserPassword("secret");
try {
pdf.loadFile("qa_data/pdf/encrypted_user_password.pdf");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// What security does the file have, and may it be modified?
JsonObject json = new JsonObject();
JsonObject jsonOut = new JsonObject();
try {
pdf.protection("getInfo", json, jsonOut);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("encrypted: " + jsonOut.boolOf("loaded.encrypted"));
System.out.println("method: " + jsonOut.stringOf("loaded.method"));
System.out.println("openedWith: " + jsonOut.stringOf("loaded.openedWith"));
System.out.println("may modify: " + jsonOut.boolOf("loaded.permissions.modify"));
try {
pdf.optimize("optimize", json, jsonOut);
pdf.writeFile("qa_output/encrypted_optimized.pdf");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("bytesSaved: " + jsonOut.intOf("bytesSaved"));
// The output is still encrypted with the same security: loading it without the password fails.
Pdf noPassword = new Pdf();
noPassword.loadFile("qa_output/encrypted_optimized.pdf");
JsonObject q = new JsonObject();
JsonObject qOut = new JsonObject();
noPassword.extractText("assess", q, qOut);
System.out.println("passwordRequired without the password: " + qOut.boolOf("quality.passwordRequired"));
// With the password it reads normally.
Pdf withPassword = new Pdf();
withPassword.setUserPassword("secret");
try {
withPassword.loadFile("qa_output/encrypted_optimized.pdf");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("pages: " + withPassword.getNumPages());
}
}