在MFC使用打印机相对简单,此处不多说,现看看在控制台下如何使用打印功能。
获取所有的打印机:
struct print
{
CString mDriverName;
CString mDeviceName;
CString mDevicePort;
};
vector<print> mPrints;
void GetPrinters()
{
DWORD dwFlags = PRINTER_ENUM_FAVORITE | PRINTER_ENUM_LOCAL;
LPPRINTER_INFO_2 pPrinters;
DWORD cbPrinters;
DWORD cReturned;
int i;
//
// get byte count needed for buffer, alloc buffer, the enum the printers
//
//先获取打印机数量
EnumPrinters (dwFlags, NULL, 2, NULL, 0, &cbPrinters,
&cReturned);
if (!(pPrinters = (LPPRINTER_INFO_2) LocalAlloc (LPTR, cbPrinters + 4)))
{
goto done_refreshing;
}
//获取打印机,填充到数组
if (!EnumPrinters (dwFlags, NULL, 2, (LPBYTE) pPrinters,
cbPrinters, &cbPrinters, &cReturned))
{
goto done_refreshing;
}
//提取打印机信息,包括驱动名、打印机名、端口名
if (cReturned > 0)
{
for (i= 0; i < cReturned; i++)
{
//
// for each printer in the PRINTER_INFO_2 array: build a string that
// looks like "DEVICE_NAME;PORT;DRIVER_NAME"
//
print p;
p.mDriverName.Append((pPrinters + i)->pDriverName);
p.mDeviceName.Append((pPrinters + i)->pPrinterName);
p.mDevicePort.Append((pPrinters + i)->pPortName);
mPrints.push_back(p);
}
}
done_refreshing:
LocalFree (LocalHandle (pPrinters));
}
使用打印机:
打开打印机,并创建打印机DC:
wchar_t szPrinter[MAX_PATH];
DWORD cchPrinter(ARRAYSIZE(szPrinter));
//GetDefaultPrinter(szPrinter, &cchPrinter);
wcscpy(szPrinter, gSystemConfig.mDeviceName.GetBuffer());
OpenPrinter(szPrinter, &hdl, NULL);
DWORD size = DocumentProperties(NULL, hdl, szPrinter, NULL, NULL, 0);
devmode = (DEVMODE*)malloc(size);
DocumentProperties(NULL, hdl, szPrinter, devmode, NULL, DM_OUT_BUFFER);
HDC printerDC = CreateDC(L"WINSPOOL", szPrinter, NULL, devmode);
获取打印机的尺寸:
width = GetDeviceCaps(printerDC, HORZRES);
height = GetDeviceCaps(printerDC, VERTRES);
这里获取的尺寸是以像素为单位的,所有,如果打印参数是按照实际尺寸的,那么需要根据打印分辨率将实际尺寸换算成像素,因为程序中是以像素为单位进行文本、图像等绘制。
获取打印机分辨率:
mDpi = GetDeviceCaps(printerDC, LOGPIXELSX);
打印设置:
devmode->dmOrientation = DMORIENT_PORTRAIT; //打印方向设置成纵向打印
devmode->dmPaperSize = DMPAPER_A4;
打印参数设置之后需要调用:
ResetDC(printerDC, devmode);
生效。
开始文档,开始一页
StartDoc(printerDC, &info);
StartPage(printerDC);
结束一页:
EndPage(printDC);
打印结束之后:
EndDoc(printerDC);
DeleteDC(printerDC);
ClosePrinter(hdl);
free(devmode);
关闭文档、打印机。
这里使用打印机只获取打印机的名称就可以了。