Como enviar dados diretamente para uma impressora GDI

O exemplo de código mais adiante neste tópico mostra como enviar dados de controle de impressora diretamente para impressoras que usam drivers de impressora baseados em GDI.

As etapas a seguir descrevem como enviar dados diretamente para uma impressora. Essas etapas também são ilustradas no exemplo de código a seguir.

  1. Chame OpenPrinter para obter um identificador para a impressora.
  2. Inicialize uma estrutura DOCINFO com os dados da impressora.
  3. Chame StartDocPrinter para indicar que o aplicativo enviará dados do documento para a impressora.
  4. Chame StartPagePrinter para indicar que o aplicativo enviará uma nova página para a impressora.
  5. Chame WritePrinter para enviar os dados.
  6. Chame EndPagePrinter para indicar que todos os dados da página atual foram enviados.
  7. Chame EndDocPrinter para indicar que todos os dados deste documento foram enviados.
  8. Chame ClosePrinter para liberar os recursos.

Envie dados de controle de impressora diretamente para impressoras que usam drivers de impressora baseados em GDI.

// 
// 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. 
//  
BOOL RawDataToPrinter(LPTSTR szPrinterName, LPBYTE lpData, DWORD dwCount)
{
    BOOL     bStatus = FALSE;
    HANDLE     hPrinter = NULL;
    DOC_INFO_1 DocInfo;
    DWORD      dwJob = 0L;
    DWORD      dwBytesWritten = 0L;

    // Open a handle to the printer. 
    bStatus = OpenPrinter( szPrinterName, &hPrinter, NULL );
    if (bStatus) {
        // Fill in the structure with info about this "document." 
        DocInfo.pDocName = (LPTSTR)_T("My Document");
        DocInfo.pOutputFile = NULL;
        DocInfo.pDatatype = (LPTSTR)_T("RAW");

        // Inform the spooler the document is beginning. 
        dwJob = StartDocPrinter( hPrinter, 1, (LPBYTE)&DocInfo );
        if (dwJob > 0) {
            // Start a page. 
            bStatus = StartPagePrinter( hPrinter );
            if (bStatus) {
                // Send the data to the printer. 
                bStatus = WritePrinter( hPrinter, lpData, dwCount, &dwBytesWritten);
                EndPagePrinter (hPrinter);
            }
            // Inform the spooler that the document is ending. 
            EndDocPrinter( hPrinter );
        }
        // Close the printer handle. 
        ClosePrinter( hPrinter );
    }
    // Check to see if correct number of bytes were written. 
    if (!bStatus || (dwBytesWritten != dwCount)) {
        bStatus = FALSE;
    } else {
        bStatus = TRUE;
    }
    return bStatus;
}

ClosePrinter

EndDocPrinter

EndPagePrinter

OpenPrinter

StartDocPrinter

StartPagePrinter

WritePrinter