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

Unicode C
#include <C_CkPdfW.h>
#include <C_CkJsonObjectW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkPdfW pdf;
    HCkJsonObjectW json;
    HCkJsonObjectW jsonOut;
    int fileSize;
    int estimated;

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

    pdf = CkPdfW_Create();
    success = CkPdfW_LoadFile(pdf,L"qa_data/pdf/watersense_accomplishments.pdf");
    if (success == FALSE) {
        wprintf(L"%s\n",CkPdfW_lastErrorText(pdf));
        CkPdfW_Dispose(pdf);
        return;
    }

    json = CkJsonObjectW_Create();
    jsonOut = CkJsonObjectW_Create();
    success = CkPdfW_Optimize(pdf,L"audit",json,jsonOut);
    if (success == FALSE) {
        wprintf(L"%s\n",CkPdfW_lastErrorText(pdf));
        CkPdfW_Dispose(pdf);
        CkJsonObjectW_Dispose(json);
        CkJsonObjectW_Dispose(jsonOut);
        return;
    }

    fileSize = CkJsonObjectW_IntOf(jsonOut,L"fileSize");
    estimated = CkJsonObjectW_IntOf(jsonOut,L"estimatedSavings.total");
    wprintf(L"fileSize:  %d\n",fileSize);
    wprintf(L"estimated: %d\n",estimated);

    //  Only bother when at least a tenth of the file would go.
    if (estimated > (fileSize / 10)) {
        wprintf(L"Worth optimizing.\n");
        success = CkPdfW_Optimize(pdf,L"optimize",json,jsonOut);
        if (success == FALSE) {
            wprintf(L"%s\n",CkPdfW_lastErrorText(pdf));
            CkPdfW_Dispose(pdf);
            CkJsonObjectW_Dispose(json);
            CkJsonObjectW_Dispose(jsonOut);
            return;
        }

        success = CkPdfW_WriteFile(pdf,L"qa_output/watersense_optimized.pdf");
        if (success == FALSE) {
            wprintf(L"%s\n",CkPdfW_lastErrorText(pdf));
            CkPdfW_Dispose(pdf);
            CkJsonObjectW_Dispose(json);
            CkJsonObjectW_Dispose(jsonOut);
            return;
        }

        wprintf(L"bytesSaved: %d\n",CkJsonObjectW_IntOf(jsonOut,L"bytesSaved"));
    }
    else {
        wprintf(L"Already small enough; left as it is.\n");
    }



    CkPdfW_Dispose(pdf);
    CkJsonObjectW_Dispose(json);
    CkJsonObjectW_Dispose(jsonOut);

    }