{ Copyright (c)2000 by Przemyslaw Jankowski }
{ e-mail: pjank@aurora.put.poznan.pl        }
unit rawprint;
{$B-,H+}

interface

uses SysUtils;


type
  ERAWPrintError = class(Exception);
  ERAWPrintErrorPrinterName = class(ERAWPrintError);


procedure RAWPrint(PrinterName, DocumentTitle, DocumentData: string);
// PrinterName - the name of the printer you want to use
//               to use the default printer - leave this blank
// DocumentTitle - the text that is listed in the Print Manager
// DocumentData - the text you want to send to the printer


implementation

uses WinSpool, Windows;

const
  // ENGLISH //
  errNoDefaultPrinter = 'No default printer found.';
  errOpenPrinter = 'The printer "%s" is not available.';
  errPrintError  = 'Error printing the document "%s".';

  // POLISH  //
  //errNoDefaultPrinter = 'Brak domyślnej drukarki.';
  //errOpenPrinter = 'Drukarka "%s" jest niedostępna.';
  //errPrintError  = 'Błąd przy drukowaniu "%s".';


function DefaultPrinter:string;
var PrinterInfo: PPrinterInfo5;
    BytesCount: DWord;
    StructCount: DWord;
begin
  BytesCount:= 0;
  EnumPrinters(PRINTER_ENUM_DEFAULT, nil, 5, nil, 0, BytesCount, StructCount);
  if (BytesCount<>0) then begin
    PrinterInfo:= AllocMem(BytesCount);
    try
      if EnumPrinters(PRINTER_ENUM_DEFAULT, nil, 5, PrinterInfo, BytesCount, BytesCount, StructCount)
         and (StructCount=1)
      then Result:= PrinterInfo^.pPrinterName
      else raise ERAWPrintErrorPrinterName.Create(errNoDefaultPrinter);
    finally
      FreeMem(PrinterInfo);
    end
  end
end;


procedure RAWPrint(PrinterName, DocumentTitle, DocumentData: string);
var hPrinter: DWord;
    DocInfo: TDocInfo1;
    dwJob: Integer;
    dwBytesWritten: DWord;
  procedure PrintError;
  begin
    raise ERAWPrintError.Create(Format(errPrintError, [DocumentTitle]));
  end;
begin
  if PrinterName='' then PrinterName:= DefaultPrinter;
  if not OpenPrinter(PChar(PrinterName), hPrinter, nil) then
    raise ERAWPrintErrorPrinterName.Create(Format(errOpenPrinter, [PrinterName]));
  try
    DocInfo.pOutputFile:= nil;
    DocInfo.pDatatype:= 'RAW';
    DocInfo.pDocName:= PChar(DocumentTitle);
    dwJob:= StartDocPrinter(hPrinter, 1, @DocInfo);
    if (dwJob=0) then PrintError;
    try
      if not StartPagePrinter(hPrinter) then PrintError;
      try
        if not WritePrinter(hPrinter, Pointer(DocumentData), Length(DocumentData), dwBytesWritten)
          then PrintError;
        if (LongInt(dwBytesWritten)<Length(DocumentData))
          then PrintError;
      finally
        if not EndPagePrinter(hPrinter) then PrintError;
      end;
    finally
      if not EndDocPrinter(hPrinter) then PrintError;
    end;
  finally
    ClosePrinter(hPrinter);
  end;
end;


end.

