Printing Data in with AssignPrn RTL
Sample printing code below is very, very basic with nothing fancy and nothing based on reporting components. Delphi's simplest technique to produce a printout: assigning a file to the printer with the AssignPrn RTL procedure. The sample has a unidirectional SQLDataSet component,hooked to an InterBase connection and based on the following SQL statements: select d.Department, e.full_name, e.job_name, e.hire_date from Employee e inner join department d on d.dept_no = e.dept_no the printing routine requires three(3) parameters, see code below: procedure TNavigator.PrintAllButtonClick (Sender: TObject); var Font: TFont; begin // set progressBar range EmplCountData.Open; try ProgressBar1.Max := EmplCountData.Fields[0].AsInteger; finally EmplCountData.Close; end; Font := TFont.Create; try Font.Name := 'Courier New'; Font.size := 9; PrintOutDataSet(EmplData, ProgressBar1, Font); finally Font.Free; end; end; here is the code, which uses three(3) nested try / finally blocks to release all the resources properly: procedure PrintOutDataSet (data: TDataSet; progress: TProgressBar; Font: TFont; maxSize: Integer = 30); var PrintFile: TextFile; I: Integer; sizeStr: String; oldFont: TFontRecall; begin // assign the printer to a file AssignPrn(PrintFile); Rewrite(PrintFile); // set the font and keep the original one oldFont := TFontRecall.create(Printer.Canvas.Font); try Printer.Canvas.Font := Font; try data.Open; try // print header (field names) // in bold Printer.canvas.Font.Style := [fsBold]; for I := 0 to data.FieldCount -1 do begin sizeStr := IntToStr(min (data.Fields[i].DisplayWidth, maxSize)); write(PrintFile, Format ('%-' + sizeStr + 's', [data.Fields[i].FieldName] )); end; writeln (PrintFile); // for each record of the dataset Print.Canvas.Font.Style := []; while not data.EOF do begin // print out each field of the record for I := 0 to dataFieldCount -1 do begin sizeStr := IntToStr( min (data.Fields[i].displaywidth,maxSize)); write(PrintFile, format('%-' + sizeStr + 's', [data.Fields[i].AsString])); end; writeln(PrintFile); // advance progress bar progress.Position := progress.Position + 1; data.next; end; finally // close the dataset data.close; end; finally // reassign the original printer font oldFont.Free; end; finally // close the printer file System.CloseFile(PrintFile); end; end; |

