Delphi ActiveX Requires Chilkat v11.7.0+
Delphi ActiveX
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 Delphi ActiveX Downloads
var
success: Integer;
pdf: TChilkatPdf;
json: TChilkatJsonObject;
jsonOut: TChilkatJsonObject;
fileSize: Integer;
estimated: Integer;
begin
success := 0;
// 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 := TChilkatPdf.Create(Self);
success := pdf.LoadFile('qa_data/pdf/watersense_accomplishments.pdf');
if (success = 0) then
begin
Memo1.Lines.Add(pdf.LastErrorText);
Exit;
end;
json := TChilkatJsonObject.Create(Self);
jsonOut := TChilkatJsonObject.Create(Self);
success := pdf.Optimize('audit',json.ControlInterface,jsonOut.ControlInterface);
if (success = 0) then
begin
Memo1.Lines.Add(pdf.LastErrorText);
Exit;
end;
fileSize := jsonOut.IntOf('fileSize');
estimated := jsonOut.IntOf('estimatedSavings.total');
Memo1.Lines.Add('fileSize: ' + IntToStr(fileSize));
Memo1.Lines.Add('estimated: ' + IntToStr(estimated));
// Only bother when at least a tenth of the file would go.
if (estimated > (fileSize / 10)) then
begin
Memo1.Lines.Add('Worth optimizing.');
success := pdf.Optimize('optimize',json.ControlInterface,jsonOut.ControlInterface);
if (success = 0) then
begin
Memo1.Lines.Add(pdf.LastErrorText);
Exit;
end;
success := pdf.WriteFile('qa_output/watersense_optimized.pdf');
if (success = 0) then
begin
Memo1.Lines.Add(pdf.LastErrorText);
Exit;
end;
Memo1.Lines.Add('bytesSaved: ' + IntToStr(jsonOut.IntOf('bytesSaved')));
end
else
begin
Memo1.Lines.Add('Already small enough; left as it is.');
end;