Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Compress Text from StringBuilder to Gzip (BinData Output)

See more Gzip Examples

This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.

The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.

This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
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.Gzip,
  Chilkat.StringBuilder,
  Chilkat.BinData;

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

procedure RunDemo;
var
  success: Boolean;
  gzip: TGzip;
  sb: TStringBuilder;
  bd: TBinData;

begin
  success := False;

  //  This example demonstrates how to compress text contained in a StringBuilder
  //  into Gzip format, storing the compressed result in a BinData object.

  gzip := TGzip.Create;
  sb := TStringBuilder.Create;
  bd := TBinData.Create;

  //  Add some text to the StringBuilder:
  sb.Append('The quick brown fox jumps over the lazy dog.');

  //  Compress the text using UTF-8 encoding:
  success := gzip.CompressSb(sb,'utf-8',bd);
  if (success = False) then
    begin
      WriteLn(gzip.LastErrorText);
      Exit;
    end;

  //  The BinData now contains the Gzip-compressed bytes.
  WriteLn('Compression successful.');
  WriteLn('Compressed size (bytes): ' + bd.NumBytes);

  //  (Optional) Save to a .gz file:
  success := bd.WriteFile('text.gz');
  if (success = False) then
    begin
      WriteLn(bd.LastErrorText);
      Exit;
    end;

  WriteLn('Gzip file written to text.gz');


  gzip.Free;
  sb.Free;
  bd.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.