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

Optimizing a Signed PDF (PreserveSignatures)

See more PDF Optimization Examples

Demonstrates what happens when a signed PDF is optimized. Optimizing rewrites the document, and a rewrite breaks every existing digital signature, so with PreserveSignatures true (the default) Optimize refuses and LastErrorText says why. Setting PreserveSignatures to false allows it, and the signature that was in the file no longer verifies afterwards. "audit" is always allowed, because it changes nothing.

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 invoice_signed.pdf

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

  print('signatures: ${pdf.numSignatures}');

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

  // An audit changes nothing, so it is allowed on a signed PDF.
  try {
    pdf.optimize('audit', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('audit ok, estimated savings: ${jsonOut.intOf('estimatedSavings.total')}');

  // Optimizing is refused while PreserveSignatures is true.
  try {
    pdf.optimize('optimize', json, jsonOut);
  } on ChilkatException {
    print('Refused while PreserveSignatures is true.');
  }

  // Allow the rewrite.  Do this only when the signatures no longer matter -- an invoice being
  // archived, say, where the signed original is kept elsewhere.
  pdf.preserveSignatures = false;
  try {
    pdf.optimize('optimize', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

  print('optimized, bytesSaved: ${jsonOut.intOf('bytesSaved')}');

  // The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
  final pdf2 = CkPdf();
  try {
    pdf2.loadFile('qa_output/invoice_optimized.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('signatures after: ${pdf2.numSignatures}');

  final sigInfo = CkJsonObject();
  var verified = true;
  try {
    pdf2.verifySignature(0, sigInfo);
  } on ChilkatException {
    verified = false;
  }
  print('verifies after optimizing: $verified');
}