How do I Print from C or C++?
by Smith & Jones (July 1998)
While using Microsoft Visual C++ 5.0 Professional Edition, how do you get output from a standard C++ source file to print to a printer? It seems to only allows output to go to a DOS box which cannot be printed.
The short answer is that it takes only three or four lines of code to print, as long as you are printing to the local printer (a printer directly connected to the parallel port of your computer).
There are three basic ways to print from the C or C++ languages, depending on the type of output desired and the amount of code you want to write.
1. (From C++): Use the ostream class (cout is an ostream) This should work for both a CONSOLE and a Windows application.
Advantages: Easy printing of simple text.
Disadvantages: Can only print to local printer.
Code:
|
filebuf fb( "prn:" ); // Filebuf object attached to "prn:"
filebuf fb( "prn:" ); // Filebuf object attached to "prn:"
cout = &fb; // fb associated with cout
cout << "testing"; // Text goes to PRN: not stdout
| |
2. (From C): Use stdio file functions.
This is exactly equivalent to the stream method without using classes.
Advantages: Easy printing of simple text.
Disadvantages: Can only print to local printer.
Code:
|
FILE * fpPrint; // file handle for printing
fpPrint = fopen( "PRN:" ); // open the printer port
fprintf( fpPrint, "testing" ); // write to the printer
fclose( fpPrint ); // close the printer port
| |
3. (Using the Windows API): Although this method may look pretty to the user, it can be a lot of work to code.
Advantages: More user friendly.
Allows easy graphics printing.
Network printers can be used for printing.
Disadvantages: Requires a lot more setup.
To fully support printing from a Windows application, you'd need to give the user access to standard printer dialogs, the ability to setup up a printer device, and render your graphics into the chosen printer device context, while checking for user cancellation, etc. In other words, it's more work, but can help make your application look more like commercial software.
Code: If you need to do this style of printing, refer to the samples provided with Visual C++, such as the standard SCRIBBLE example.
Another, more complete example can be found in the Visual C++ 5.0 books under:
|
Samples
= > Windows SDK Samples
= > Win32 Samples
= > PRINTER
| |
or, just search for the words "PRINTER sample" in help
Copyright
© 1998 Smith & Jones All rights reserved.
|