Sample code for 30+ languages & platforms
Java Requires Chilkat v11.7.0+

Deflate Compression Level When Optimizing a PDF

See more PDF Optimization Examples

Demonstrates compressionLevel, which is the deflate level (1 to 9, 9 by default) used for every stream the optimizer re-encodes. Level 9 is the smallest and the slowest; level 1 is the quickest. The difference is usually a percent or two, so level 9 is the right default for a file that will be downloaded many times, and a lower level is worth considering only when a server optimizes PDFs on the fly. A value outside 1 to 9 is an error.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.FileAccess;
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

        FileAccess fac = new FileAccess();
        JsonObject json = new JsonObject();
        JsonObject jsonOut = new JsonObject();

        Pdf pdf1 = new Pdf();
        try {
            pdf1.loadFile("qa_data/pdf/watersense_accomplishments.pdf");

            json.updateInt("compressionLevel", 1);
            pdf1.optimize("optimize", json, jsonOut);

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

        System.out.println("level 1: " + fac.fileSize("qa_output/watersense_level1.pdf"));

        Pdf pdf9 = new Pdf();
        try {
            pdf9.loadFile("qa_data/pdf/watersense_accomplishments.pdf");

            json.updateInt("compressionLevel", 9);
            pdf9.optimize("optimize", json, jsonOut);

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

        System.out.println("level 9: " + fac.fileSize("qa_output/watersense_level9.pdf"));

        // A level outside 1..9 fails, and LastErrorText says why.
        Pdf pdfBad = new Pdf();
        try {
            pdfBad.loadFile("qa_data/pdf/watersense_accomplishments.pdf");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        json.updateInt("compressionLevel", 12);
        try {
            pdfBad.optimize("optimize", json, jsonOut);
        } catch (ChilkatException e) {
            System.out.println("compressionLevel 12 was refused, as it should be.");
        }
    }
}