Mega Code Archive

 
Categories / Delphi / Printing
 

How to send data directly to the printer without the PASSTHROUGH command

Title: How to send data directly to the printer without the PASSTHROUGH command Question: How can you send data directly to the printer. While your printer driver doesn't support PASSTHROUGH. Answer: I had the problem I wanted to write directly to my Barcode-Printer. This, because the Barcode-Printer needs codes to transform to different Barcodes. Delphi only allows you to write on the canvas which ofcourse didn't work. So I tried the Escape functions. The PASSTHROUGH command wasn't supported by my printer driver. Further exploration brought me to the MS pages. The URL: http://msdn.microsoft.com/library/psdk/gdi/prntspol_93g2.htm gives the solution. I translated it to Delphi-code and here it is: Uses WinSpool; Function RawDataToPrinter( szPrinterName : String; DataStr : String; dwCount : Integer) : Boolean; // http://msdn.microsoft.com/library/psdk/gdi/prntspol_93g2.htm // // RawDataToPrinter - sends binary data directly to a printer // // szPrinterName: NULL-terminated string specifying printer name // lpData: Pointer to raw data bytes // dwCount Length of lpData in bytes // // Returns: TRUE for success, FALSE for failure. // Var hPrinter : THandle; DocInfo : TDocInfo1; dwBytesWritten : Integer; lpData : Array[0..255] of Char; Begin // Copy DataStr to lpData StrPCopy(lpData,DataStr); // Need a handle to the printer. If( Not OpenPrinter( PChar(szPrinterName), hPrinter, nil ) ) Then Begin Result := FALSE; Exit; End; // Fill in the structure with info about this "document." DocInfo.pDocName := 'My Document'; DocInfo.pOutputFile := nil; DocInfo.pDatatype := 'RAW'; // Inform the spooler the document is beginning. If( StartDocPrinter( hPrinter, 1, @DocInfo ) Begin ClosePrinter( hPrinter ); Result := FALSE; Exit; End; // Start a page. If( Not StartPagePrinter( hPrinter ) ) Then Begin EndDocPrinter( hPrinter ); ClosePrinter( hPrinter ); Result := FALSE; Exit; End; // Send the data to the printer. If( Not WritePrinter( hPrinter, @lpData, dwCount, dwBytesWritten ) ) Then Begin EndPagePrinter( hPrinter ); EndDocPrinter( hPrinter ); ClosePrinter( hPrinter ); Result := FALSE; Exit; End; // End the page. If( Not EndPagePrinter( hPrinter ) ) Then Begin EndDocPrinter( hPrinter ); ClosePrinter( hPrinter ); Result := FALSE; Exit; End; // Inform the spooler that the document is ending. If( Not EndDocPrinter( hPrinter ) ) Then Begin ClosePrinter( hPrinter ); Result := FALSE; Exit; End; // Tidy up the printer handle. ClosePrinter( hPrinter ); // Check to see if correct number of bytes were written. If( dwBytesWritten dwCount ) Then Begin Result := FALSE; Exit; End; Result := TRUE; End;