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

React Native
import { JsonObject, Pdf } from '@chilkat/react-native'

function chilkatExample() {
  // 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

  const pdf = new Pdf();
  try {
    pdf.loadFile('qa_data/pdf/watersense_accomplishments.pdf');
  } catch {
    console.log(pdf.lastErrorText);
    return;
  }

  const json = new JsonObject();
  const jsonOut = new JsonObject();
  try {
    pdf.optimize('audit', json, jsonOut);
  } catch {
    console.log(pdf.lastErrorText);
    return;
  }

  const fileSize = jsonOut.intOf('fileSize');
  const estimated = jsonOut.intOf('estimatedSavings.total');
  console.log(`fileSize:  ${fileSize}`);
  console.log(`estimated: ${estimated}`);

  // Only bother when at least a tenth of the file would go.
  if (estimated > (Math.trunc(fileSize / 10))) {
    console.log('Worth optimizing.');
    try {
      pdf.optimize('optimize', json, jsonOut);
    } catch {
      console.log(pdf.lastErrorText);
      return;
    }

    try {
      pdf.writeFile('qa_output/watersense_optimized.pdf');
    } catch {
      console.log(pdf.lastErrorText);
      return;
    }

    console.log(`bytesSaved: ${jsonOut.intOf('bytesSaved')}`);
  } else {
    console.log('Already small enough; left as it is.');
  }
}