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

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Pdf,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  pdf: TPdf;
  json: TJsonObject;
  jsonOut: TJsonObject;
  fileSize: Integer;
  estimated: Integer;

begin
  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

  pdf := TPdf.Create;
  success := pdf.LoadFile('qa_data/pdf/watersense_accomplishments.pdf');
  if (success = False) then
    begin
      WriteLn(pdf.LastErrorText);
      Exit;
    end;

  json := TJsonObject.Create;
  jsonOut := TJsonObject.Create;
  success := pdf.Optimize('audit',json,jsonOut);
  if (success = False) then
    begin
      WriteLn(pdf.LastErrorText);
      Exit;
    end;

  fileSize := jsonOut.IntOf('fileSize');
  estimated := jsonOut.IntOf('estimatedSavings.total');
  WriteLn('fileSize:  ' + fileSize);
  WriteLn('estimated: ' + estimated);

  //  Only bother when at least a tenth of the file would go.
  if (estimated > (fileSize / 10)) then
    begin
      WriteLn('Worth optimizing.');
      success := pdf.Optimize('optimize',json,jsonOut);
      if (success = False) then
        begin
          WriteLn(pdf.LastErrorText);
          Exit;
        end;
      success := pdf.WriteFile('qa_output/watersense_optimized.pdf');
      if (success = False) then
        begin
          WriteLn(pdf.LastErrorText);
          Exit;
        end;
      WriteLn('bytesSaved: ' + jsonOut.IntOf('bytesSaved'));
    end
  else
    begin
      WriteLn('Already small enough; left as it is.');
    end;


  pdf.Free;
  json.Free;
  jsonOut.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.