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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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

  final fac = CkFileAccess();
  final json = CkJsonObject();
  final jsonOut = CkJsonObject();

  final pdf1 = CkPdf();
  try {
    pdf1.loadFile('qa_data/pdf/watersense_accomplishments.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  json.updateInt('compressionLevel', 1);
  try {
    pdf1.optimize('optimize', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    pdf1.writeFile('qa_output/watersense_level1.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('level 1: ${fac.fileSize('qa_output/watersense_level1.pdf')}');

  final pdf9 = CkPdf();
  try {
    pdf9.loadFile('qa_data/pdf/watersense_accomplishments.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  json.updateInt('compressionLevel', 9);
  try {
    pdf9.optimize('optimize', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    pdf9.writeFile('qa_output/watersense_level9.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('level 9: ${fac.fileSize('qa_output/watersense_level9.pdf')}');

  // A level outside 1..9 fails, and LastErrorText says why.
  final pdfBad = CkPdf();
  try {
    pdfBad.loadFile('qa_data/pdf/watersense_accomplishments.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  json.updateInt('compressionLevel', 12);
  try {
    pdfBad.optimize('optimize', json, jsonOut);
  } on ChilkatException {
    print('compressionLevel 12 was refused, as it should be.');
  }
}