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

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean 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

    CkPdf pdf = new CkPdf();
    success = pdf.LoadFile("qa_data/pdf/watersense_accomplishments.pdf");
    if (success == false) {
        System.out.println(pdf.lastErrorText());
        return;
        }

    CkJsonObject json = new CkJsonObject();
    CkJsonObject jsonOut = new CkJsonObject();
    success = pdf.Optimize("audit",json,jsonOut);
    if (success == false) {
        System.out.println(pdf.lastErrorText());
        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.");
        success = pdf.Optimize("optimize",json,jsonOut);
        if (success == false) {
            System.out.println(pdf.lastErrorText());
            return;
            }

        success = pdf.WriteFile("qa_output/watersense_optimized.pdf");
        if (success == false) {
            System.out.println(pdf.lastErrorText());
            return;
            }

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