Last Modification: December 11, 1999

How do I print a line at a time rather than a full page?

Most Windows documentation shows you how to print using GDI which necessitates an entire page be printed. If you're implementing an application which requires simple text output for a logging type application, and your printer can accept pure text, then you can quite easily use the lower level printer functions as illustrated in this sample:


#include <winspool.h>

BOOL PrintStringDirect( LPCSTR Str,
			LPTSTR PrinterName,
			LPSTR DeviceName )
{
	BOOL bRet = FALSE;
	HANDLE hPrinter;

	if ( OpenPrinter( PrinterName, &hPrinter, NULL ) )
	{
		DOC_INFO_1 doc_info = {0};

		doc_info.pDocName = "The Document Name";
		doc_info.pOutputFile = DeviceName;

		DWORD jobid = StartDocPrinter( hPrinter, 1,
				(LPBYTE) &doc_info );

		if ( jobid != 0 )
		{
			DWORD written;
			DWORD dwNumBytes = lstrlen( Str );

			WritePrinter( hPrinter,
				(void*) Str,
				dwNumBytes, &written );

			if ( written == dwNumBytes )
			{
				bRet = TRUE;
			}
		}

		EndDocPrinter(hPrinter);
		ClosePrinter(hPrinter);
	}

	return bRet;
}
which you can use like this:

PrintStringDirect( "Print this line to the printer\r\n",
		"HP DeskJet 850C", "LPT1:" );