Sending a text file directly to the printer
   


Have you ever had a text file and you just want to "throw" the file directly to the default printer, but don't want to add all that extra code in all your projects? PrintFile() will do just that for you. Simply pass the name of the text file (Note: text files only!) to the procedure and your done!

{$DEFINE Delphi3Below}
{$IFDEF VER130} //Delphi 5
  {$UNDEF Delphi3Below}
{$ELSE}
  {$IFDEF VER120} //Delphi 4
    {$UNDEF Delphi3Below}
  {$ENDIF}
{$ENDIF}

uses Printers, WinSpool;

procedure PrintFile(const sFileName: string);
{ Prints a text file directly to the default printer. }
const
  BufSize = 16384;
type
  TDoc_Info_1 = record
    pDocName,
    pOutputFile,
    pDataType: pChar; 
  end;
var
{$IFDEF Delphi3Below}

  Count, BytesWritten: cardinal;
{$ELSE}

  Count, BytesWritten: integer;
{$ENDIF}

  hPrinter,
  hDeviceMode: THandle;
  Device,
  Driver,
  Port : array[0..255] of char;
  DocInfo: TDoc_Info_1;
  f: file;
  Buffer: Pointer;
begin
  Printer.PrinterIndex := -1;
  Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
  if not WinSpool.OpenPrinter(@Device, hPrinter, nilthen
    Exit;
  DocInfo.pDocName := 'MyDocument';
  DocInfo.pOutputFile := nil;
  DocInfo.pDatatype := 'RAW';
  if StartDocPrinter(hPrinter, 1, @DocInfo) = 0 then
    begin
      WinSpool.ClosePrinter(hPrinter);
      Exit; 
    end;
  if not StartPagePrinter(hPrinter) then
    begin
      EndDocPrinter(hPrinter);
      WinSpool.ClosePrinter(hPrinter);
      Exit;
    end;
  System.Assign(f, sFileName);
  try
    Reset(f, 1);
    GetMem(Buffer, BufSize);
    while not eof(f) do
      begin
        Blockread(f, Buffer^, BufSize, Count);
        if Count > 0 then
          if not WritePrinter(hPrinter, Buffer, Count, BytesWritten) then
            begin
              EndPagePrinter(hPrinter);
              EndDocPrinter(hPrinter);
              WinSpool.ClosePrinter(hPrinter);
              FreeMem(Buffer, BufSize);
              Exit;
            end;
      end;
    FreeMem(Buffer, BufSize);
    EndDocPrinter(hPrinter);
    WinSpool.ClosePrinter(hPrinter);
  finally
    System.Closefile( f );
  end;
end;


Blue Orb Software

[email protected]