Dart Requires Chilkat v11.7.0+
Dart
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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// 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
final pdf = CkPdf();
// The password must be set before loading.
pdf.userPassword = 'secret';
try {
pdf.loadFile('qa_data/pdf/encrypted_user_password.pdf');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// What security does the file have, and may it be modified?
final json = CkJsonObject();
final jsonOut = CkJsonObject();
try {
pdf.protection('getInfo', json, jsonOut);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('encrypted: ${jsonOut.boolOf('loaded.encrypted')}');
print('method: ${jsonOut.stringOf('loaded.method')}');
print('openedWith: ${jsonOut.stringOf('loaded.openedWith')}');
print('may modify: ${jsonOut.boolOf('loaded.permissions.modify')}');
try {
pdf.optimize('optimize', json, jsonOut);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
try {
pdf.writeFile('qa_output/encrypted_optimized.pdf');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('bytesSaved: ${jsonOut.intOf('bytesSaved')}');
// The output is still encrypted with the same security: loading it without the password fails.
final noPassword = CkPdf();
noPassword.loadFile('qa_output/encrypted_optimized.pdf');
final q = CkJsonObject();
final qOut = CkJsonObject();
noPassword.extractText('assess', q, qOut);
print('passwordRequired without the password: ${qOut.boolOf('quality.passwordRequired')}');
// With the password it reads normally.
final withPassword = CkPdf();
withPassword.userPassword = 'secret';
try {
withPassword.loadFile('qa_output/encrypted_optimized.pdf');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('pages: ${withPassword.numPages}');
}