Lazarus Pascal Requires Chilkat v11.7.0+
Lazarus Pascal
Extract PDF Text to a StringBuilder and Save to a File
See more PDF Text Extraction Examples
Demonstrates ExtractTextSb, which writes the extracted text to a StringBuilder instead of returning it as a JSON string. Use it for large documents. The JSON output still receives the quality report.Chilkat Lazarus Pascal Downloads
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.StringBuilder,
Chilkat.Pdf,
Chilkat.JsonObject;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
pdf: TPdf;
json: TJsonObject;
sbText: TStringBuilder;
jsonOut: TJsonObject;
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 long_report.pdf
pdf := TPdf.Create;
success := pdf.LoadFile('qa_data/pdf/long_report.pdf');
if (success = False) then
begin
WriteLn(pdf.LastErrorText);
Exit;
end;
WriteLn('Number of pages: ' + pdf.NumPages);
// ExtractTextSb takes the same operation and options as ExtractText, but the text
// goes to a StringBuilder. This avoids building a very large JSON string for
// documents with many pages.
json := TJsonObject.Create;
sbText := TStringBuilder.Create;
jsonOut := TJsonObject.Create;
success := pdf.ExtractTextSb('text',json,sbText,jsonOut);
if (success = False) then
begin
WriteLn(pdf.LastErrorText);
Exit;
end;
WriteLn('Extracted ' + sbText.Length + ' characters.');
// Save the text to a file.
success := sbText.WriteFile('qa_output/long_report.txt','utf-8',False);
if (success = False) then
begin
WriteLn(sbText.LastErrorText);
Exit;
end;
// The JSON output does not contain the text, but it still has the quality report.
WriteLn('Quality: ' + jsonOut.StringOf('quality.rating'));
WriteLn('Pages with no text (need OCR): [' + jsonOut.StringOf('quality.pagesNeedingOcr') + ']');
// Sample output:
// Number of pages: 3
// Extracted 4522 characters.
// Quality: good
// Pages with no text (need OCR): []
pdf.Free;
json.Free;
sbText.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.