How To…Dyanmically Configure a TextPipeline

Question

“How can I dynamically create and configure a TextPipeline to print from data that I generate at runtime?”

Solution

This example first generates a text file containing sample data, then dynamically creates and configures a TextPipeline to access the text file.

Download: TextPipeDynamicFile.zip

Sample Delphi code:

{------------------------------------------------------------------------------}
{ TForm1.FormCreate }

procedure TForm1.FormCreate(Sender: TObject);
var
  lsFileName: String;
begin

  {assign the file name (ex. current directory + myDataFile.txt)}
  lsFileName := ExtractFilePath(ParamStr(0)) + 'myDataFile.txt';

  {create the data and save it to the file}
  CreateDataFile(lsFileName);

  {create textpipeline}
  myTextPipeline := TppTextPipeline.Create(Self);

  {assign the file name }
  myTextPipeline.FileName := lsFileName;

  {define the field's in order: FieldName, DataType, FieldLength (i.e. max length) }
  myTextPipeline.DefineField('Company',    dtString,   30);
  myTextPipeline.DefineField('Contact',    dtString,   20);
  myTextPipeline.DefineField('Phone',      dtString,   15);
  myTextPipeline.DefineField('Addr1',      dtString,   30);
  myTextPipeline.DefineField('City',       dtString,   15);
  myTextPipeline.DefineField('State',      dtString,   20);


end;

{------------------------------------------------------------------------------}
{ TForm1.CreateDataFile }

procedure TForm1.CreateDataFile(aFileName: String);
var
  lStringList: TStringList;
  liRecord: Integer;
  lsRecord: String;

begin

  lStringList := TStringList.Create;

  for liRecord := 1 to 500 do
    begin
      lsRecord := CreateRecord(liRecord);

      lStringList.Add(lsRecord);
    end;

  {save the data to a text file}
  lStringList.SaveToFile(aFileName);

  lStringList.Free;

end;

{------------------------------------------------------------------------------}
{ TForm1.CreateRecord }

function TForm1.CreateRecord(aRecordNo: Integer): String;
var
  lcDelimiter: Char;
  lsRecordNo: String;

begin

  lcDelimiter := ','; {comma delimiter }
  lsRecordNo  := IntToStr(aRecordNo);

  Result := ('Company-' +  lsRecordNo + lcDelimiter +
             'Contact-' +  lsRecordNo + lcDelimiter +
             'Phone-'   +  lsRecordNo + lcDelimiter +
             'Addr1-'   +  lsRecordNo + lcDelimiter +
             'City-'    +  lsRecordNo + lcDelimiter +
             'State-'   +  lsRecordNo );

end;

{------------------------------------------------------------------------------}
{ TForm1.Button1Click }

procedure TForm1.Button1Click(Sender: TObject);
begin
  ppReport1.DataPipeline := myTextPipeline;
  ppReport1.Print;
end;