Click here to Skip to main content
12,760,177 members (33,908 online)
Rate this:
Please Sign up or sign in to vote.
See more: C++ printing
Hi everyone,
I am new to C++ and working on my degree project,
I have run the following code to print hello world to the printer, but nothing is printing, only a blank page.
Whats wrong with the code?

int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow )

	memset( &pd, 0, sizeof( pd ) );

	pd.lStructSize = sizeof( pd );

	 * get rid of PD_RETURNDEFAULT on the line below if you'd like to
	 * see the "Printer Settings" dialog!

	// try to retrieve the printer DC
	if( !PrintDlg( &pd ) )
		MessageBox( NULL, "PrintDlg( &pd ) failed!", "Fatal Error", MB_OK | MB_ICONERROR );

		return -1;

	HDC hPrinter = pd.hDC;

	// initialization of the printing!
	memset( &di, 0, sizeof( di ) );
	di.cbSize = sizeof( di );
	StartDoc( hPrinter, &di );

		// start the first and only page
		StartPage( hPrinter );

		// uncomment the following line to print in colour! :)
		 SetTextColor( hPrinter, 0x0000FF );

		// write "Hello, World!" to the printer's DC
		TextOut( hPrinter, 100, 100, "Hello, World!", 13 );

		// finish the first page
		EndPage( hPrinter );

	// end this document and release the printer's DC
	EndDoc( hPrinter );
	DeleteDC( hPrinter );

	return 0;
Posted 12-Aug-12 5:34am
Richard MacCutchan 12-Aug-12 11:34am
I just tried this and it worked fine. Use your debugger to step through and check that nothing strange is happening.
wedagedara 12-Aug-12 21:03pm
Yes the problem was "TextOut( hPrinter, 1000, 1000, "Hello, World!", 13 );"
I need to change 100 to 1000
Thanks a lot

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

I just tried your code with a PDF printer and it worked correctly.

StartDoc[^] and StartPage[^] both have a return value that specifies success or failure.
You might want to check the returns values to see if they return success. Either code to check the return value or debug the program to see what is returned.

I would also skip the color printing for now by commenting out the line:
SetTextColor( hPrinter, 0x0000FF );

You might also want to increase the print coordinates in case you are printing outside the margins of the page:
TextOut( hPrinter, 1000, 1000, "Hello, World!", 13 );

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170217.1 | Last Updated 12 Aug 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100