Beranda > Delphi > Sending a text file directly to the printer

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, nil) then
    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;

Iklan
Kategori:Delphi
  1. Belum ada komentar.
  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: