After going through this post, you should be having your first printed page, that you printed through code like me!
There are a set of API’s provided by Microsoft for working with printers. Some functions are listed below…
- GetDefaultPrinter
- SetDefaultPrinter
- OpenPrinter – Returns a handle for a given printer name
- ClosePrinter – Use this instead of CloseHandle
- GetPrinter – Returns printer details based on the level that you have chosen
- CreateDC – Create a printer DC to draw onto it, windows works with devices using device contexts as you should be knowing
- StartDoc – Start fresh document
- StartPage – Start a page
- EndPage – End a page
- EndDoc – End of document
I’ve used these functions in this function that I am demonstrating here, it’s well commented so should be easy for you to understand.
void PrintTest( LPCTSTR lpctszStringToPrint )
{
ASSERT( lpctszStringToPrint );
// Get default printer name
TCHAR szDefPrinterName[MAX_PATH] = { 0 };
DWORD Size = MAX_PATH;
GetDefaultPrinter( szDefPrinterName, &Size );
// Get a handle to default printer by passing it's name to OpenPrinter
HANDLE hPrinter = NULL;
VERIFY( OpenPrinter( szDefPrinterName, &hPrinter, NULL ));
// Get printer information, like driver name and port number
LPPRINTER_INFO_2 pPrnInfo2 = 0;
Size = 0;
// First get size to be allocated
GetPrinter( hPrinter, 2, NULL, 0, &Size );
// Allocate based on returned size
pPrnInfo2 = (LPPRINTER_INFO_2)new BYTE[Size];
// Now get real information
GetPrinter( hPrinter, 2, (LPBYTE)pPrnInfo2, Size, &Size );
// Prepare a document information structure for our document
DOCINFO DocInf = { 0 };
DocInf.cbSize = sizeof( DocInf );
DocInf.lpszDocName = _T( "Test doc" ); // Name of document
// We use CreateDC to create a printer dc by passing
// device name of our default printer
CDC dcPrn;
VERIFY( dcPrn.Attach( CreateDC( pPrnInfo2->pDriverName, pPrnInfo2->pPrinterName, pPrnInfo2->pPortName, pPrnInfo2->pDevMode )));
// Start printing stuff //
StartDoc( dcPrn, &DocInf );// Fresh document
StartPage( dcPrn ); // Fresh page
// Draw a sample string
dcPrn.TextOut( 5, 5, lpctszStringToPrint, _tcslen( lpctszStringToPrint ));
EndPage( dcPrn );// Done with this page
EndDoc( dcPrn );// Done with this document
// End printing stuff //
// Free allocated buffer
delete [] LPBYTE( pPrnInfo2 );
// Note: always pair OpenPrinter and ClosePrinter, do not use CloseHandle for
// closing opened printer handle
ClosePrinter( hPrinter );
}// End PrintTest
// The calling part
int main()
{
PrintTest( _T( "Hello Mr. Printer, this is my first page, thanks to Nibu."));
}
You should be having a printer for testing this 😉 , if you do have one then check out 🙂 . As always these are just basic principles to get you going. The whole printer thingie is worth a book! This much should get you going. All the best!