Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.7.0+

Audit a PDF First, Optimize Only If It Is Worth It

See more PDF Optimization Examples

Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.

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 watersense_accomplishments.pdf

CkoPdf *pdf = [[CkoPdf alloc] init];
success = [pdf LoadFile: @"qa_data/pdf/watersense_accomplishments.pdf"];
if (success == NO) {
    NSLog(@"%@",pdf.LastErrorText);
    return;
}

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

int fileSize = [[jsonOut IntOf: @"fileSize"] intValue];
int estimated = [[jsonOut IntOf: @"estimatedSavings.total"] intValue];
NSLog(@"%@%d",@"fileSize:  ",fileSize);
NSLog(@"%@%d",@"estimated: ",estimated);

//  Only bother when at least a tenth of the file would go.
if (estimated > (fileSize / 10)) {
    NSLog(@"%@",@"Worth optimizing.");
    success = [pdf Optimize: @"optimize" jsonIn: json jsonOut: jsonOut];
    if (success == NO) {
        NSLog(@"%@",pdf.LastErrorText);
        return;
    }

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

    NSLog(@"%@%d",@"bytesSaved: ",[[jsonOut IntOf: @"bytesSaved"] intValue]);
}
else {
    NSLog(@"%@",@"Already small enough; left as it is.");
}