// Printer port name or network printer name (e.g.: "\\SERVER\LASER")
String printerPort = "LPT1:"; HANDLE printerHandle = 0;
// Neccesary for network printers; Windows 9x ignores last member,
// but it's neccesary for NT
PRINTER_DEFAULTS printerOptions;
printerOptions.pDatatype = "RAW";
printerOptions.pDevMode = NULL;
printerOptions.DesiredAccess = PRINTER_ACCESS_USE;
if (!OpenPrinter(printerHandle.c_str(), &printerHandle, &printerOptions))
{
throw "Error when opening printer port";
}
DOC_INFO_1 docInfo;
docInfo.pDocName = "Document name";
docInfo.pOutputFile = NULL;
docInfo.pDatatype = "RAW";
if (!StartDocPrinter(printerHandle, 1, (LPBYTE)&docInfo)) {
throw "Error when starting printing";
}
if (!StartPagePrinter(printerHandle)) {
throw "Error when starting a new page";
}
// Main printing loop (assumed finishedPrinting is a boolean flag
// which becomes true when all the text is printed)
while (!finishedPrinting) {
// Print a sample line
char* lineToPrint = "This is a sample line printed used Windows API
calls\n";
DWORD numBytesWritten;
BOOL correct = WritePrinter(printerHandle, (LPVOID*)lineToPrint,
strlen(lineToPrint), &numBytesWritten);
// Check if line printed OK
if (!correct | | numBytesWritten < DWORD(strlen(lineToPrint)))
throw "Error when printing a line";
// When a page is completed (EndPagePrinter sends a form feed):
if (endOfPageReached) {
if (!EndPagePrinter(printerHandle)) {
throw "Error when finishing a page";
}
}
}
if (!EndDocPrinter(printerHandle)) {
throw "Error when finishing printing";
}
ClosePrinter(printerHandle);