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 <CkPdfW.h>
#include <CkJsonObjectW.h>

void ChilkatSample(void)
    {
    bool 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

    CkPdfW pdf;
    success = pdf.LoadFile(L"qa_data/pdf/watersense_accomplishments.pdf");
    if (success == false) {
        wprintf(L"%s\n",pdf.lastErrorText());
        return;
    }

    CkJsonObjectW json;
    CkJsonObjectW jsonOut;
    success = pdf.Optimize(L"audit",json,jsonOut);
    if (success == false) {
        wprintf(L"%s\n",pdf.lastErrorText());
        return;
    }

    int fileSize = jsonOut.IntOf(L"fileSize");
    int estimated = jsonOut.IntOf(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 = pdf.Optimize(L"optimize",json,jsonOut);
        if (success == false) {
            wprintf(L"%s\n",pdf.lastErrorText());
            return;
        }

        success = pdf.WriteFile(L"qa_output/watersense_optimized.pdf");
        if (success == false) {
            wprintf(L"%s\n",pdf.lastErrorText());
            return;
        }

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