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

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Pdf;

public class ChilkatExample {

    public static void main(String[] args) {
        // 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 pdf = new Pdf();
        try {
            pdf.loadFile("qa_data/pdf/watersense_accomplishments.pdf");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        JsonObject json = new JsonObject();
        JsonObject jsonOut = new JsonObject();
        try {
            pdf.optimize("audit", json, jsonOut);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int fileSize = jsonOut.intOf("fileSize");
        int estimated = jsonOut.intOf("estimatedSavings.total");
        System.out.println("fileSize:  " + fileSize);
        System.out.println("estimated: " + estimated);

        // Only bother when at least a tenth of the file would go.
        if (estimated > (fileSize / 10)) {
            System.out.println("Worth optimizing.");
            try {
                pdf.optimize("optimize", json, jsonOut);

                pdf.writeFile("qa_output/watersense_optimized.pdf");
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            System.out.println("bytesSaved: " + jsonOut.intOf("bytesSaved"));
        } else {
            System.out.println("Already small enough; left as it is.");
        }
    }
}