Sample code for 30+ languages & platforms
Objective-C 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 Objective-C Downloads

Objective-C
#import <CkoPdf.h>
#import <CkoJsonObject.h>

BOOL success = NO;

//  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

CkoPdf *pdf = [[CkoPdf alloc] init];

//  The password must be set before loading.
pdf.UserPassword = @"secret";
success = [pdf LoadFile: @"qa_data/pdf/encrypted_user_password.pdf"];
if (success == NO) {
    NSLog(@"%@",pdf.LastErrorText);
    return;
}

//  What security does the file have, and may it be modified?
CkoJsonObject *json = [[CkoJsonObject alloc] init];
CkoJsonObject *jsonOut = [[CkoJsonObject alloc] init];
success = [pdf Protection: @"getInfo" jsonIn: json jsonOut: jsonOut];
if (success == NO) {
    NSLog(@"%@",pdf.LastErrorText);
    return;
}

NSLog(@"%@%d",@"encrypted: ",[jsonOut BoolOf: @"loaded.encrypted"]);
NSLog(@"%@%@",@"method:    ",[jsonOut StringOf: @"loaded.method"]);
NSLog(@"%@%@",@"openedWith: ",[jsonOut StringOf: @"loaded.openedWith"]);
NSLog(@"%@%d",@"may modify: ",[jsonOut BoolOf: @"loaded.permissions.modify"]);

success = [pdf Optimize: @"optimize" jsonIn: json jsonOut: jsonOut];
if (success == NO) {
    NSLog(@"%@",pdf.LastErrorText);
    return;
}

success = [pdf WriteFile: @"qa_output/encrypted_optimized.pdf"];
if (success == NO) {
    NSLog(@"%@",pdf.LastErrorText);
    return;
}

NSLog(@"%@%d",@"bytesSaved: ",[[jsonOut IntOf: @"bytesSaved"] intValue]);

//  The output is still encrypted with the same security: loading it without the password fails.
CkoPdf *noPassword = [[CkoPdf alloc] init];
success = [noPassword LoadFile: @"qa_output/encrypted_optimized.pdf"];
CkoJsonObject *q = [[CkoJsonObject alloc] init];
CkoJsonObject *qOut = [[CkoJsonObject alloc] init];
success = [noPassword ExtractText: @"assess" jsonIn: q jsonOut: qOut];
NSLog(@"%@%d",@"passwordRequired without the password: ",[qOut BoolOf: @"quality.passwordRequired"]);

//  With the password it reads normally.
CkoPdf *withPassword = [[CkoPdf alloc] init];
withPassword.UserPassword = @"secret";
success = [withPassword LoadFile: @"qa_output/encrypted_optimized.pdf"];
if (success == NO) {
    NSLog(@"%@",withPassword.LastErrorText);
    return;
}

NSLog(@"%@%d",@"pages: ",[withPassword.NumPages intValue]);