Printing text using WIN 32 API/GDI

well...I'm trying to link my Visual Studio 2008 to printer and print text by using the printer...but I'm failed to do so...can anyone please help me to rectify my error?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <windows.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow ){
	PRINTDLG pd;
	string name;
	ofstream print;
	memset( &pd, 0, sizeof( pd ) );
	pd.lStructSize = sizeof( pd );
	pd.Flags = PD_RETURNDEFAULT | PD_RETURNDC;
	cout << "Enter Your Name:";
	getline(cin,name);
	cout << "Please enter you choice <1 = Print , 2 = Exit> :";
	int choice;
	cin >> choice;
	if (choice == 1){

	if( !PrintDlg( &pd ) ){
		MessageBox( NULL, L"PrintDlg( &pd ) failed!", L"Fatal Error", MB_OK | MB_ICONERROR );

		return -1;
	}

	DOCINFO di;
	HDC hPrinter = pd.hDC;

	memset( &di, 0, sizeof( di ) );
	di.cbSize = sizeof( di );
	StartDoc( hPrinter, &di );

		StartPage( hPrinter );
		//print text to printer
		print << name;

		EndPage( hPrinter );

	EndDoc( hPrinter );
	DeleteDC( hPrinter );
	}
	if (choice == 2){
		return 0;
	}
	return 0;
}


when i compiled...it didn't occur any errors..but after i try to run it...the runtime error occur...
Last edited on
What runtime error? What line of code? Why do you think the ofstream object named 'print' is linked to the printer? ofstream stands for "output file stream", meaning is good for writing files, not to print on printers.

In order to print something on a page, you draw with GDI/GDI+ using the printer's device context. Try TextOut() for instance.

http://msdn.microsoft.com/en-us/library/dd145133(VS.85).aspx
but I'm going to merge this printing code with my another code....and it consist lots of input from user....if i use TextOut() then where should i place my output at? in order to print it out? like the name on line 36....I prompt the user to enter their name and choice to print...and the output should be their name....
example...if i replaced TextOut( hPrinter, 100, 100, "Hello, World!", 13 ); with line 36...and it will print out
Hello, World!
through printer....but if i want to print the data that user inputted...then what should i do?
Since we are talking printers here, and since the term print is also applicable to the screen, please use "print to screen" or "print to printer" to make things 100% clear. Just to make sure we are talking the same.

If you do TextOut(hPrinter, 100, 100, name.c_str(), -1);, then you'll get the name the user input in a printed page. Does this make it better?
yeah...thank you so much !!
Topic archived. No new replies allowed.