使用 Windows GDI+ 在打印机上绘图类似于使用 GDI+ 在计算机屏幕上绘图。 若要在打印机上绘图,请获取打印机的设备上下文句柄,然后将该句柄传递给 图形 构造函数。
以下控制台应用程序在名为 MyPrinter 的打印机上绘制线条、矩形和椭圆:
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;
INT main()
{
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// Get a device context for the printer.
HDC hdcPrint = CreateDC(NULL, TEXT("\\\\printserver\\print1"), NULL, NULL);
DOCINFO docInfo;
ZeroMemory(&docInfo, sizeof(docInfo));
docInfo.cbSize = sizeof(docInfo);
docInfo.lpszDocName = "GdiplusPrint";
StartDoc(hdcPrint, &docInfo);
StartPage(hdcPrint);
Graphics* graphics = new Graphics(hdcPrint);
Pen* pen = new Pen(Color(255, 0, 0, 0));
graphics->DrawLine(pen, 50, 50, 350, 550);
graphics->DrawRectangle(pen, 50, 50, 300, 500);
graphics->DrawEllipse(pen, 50, 50, 300, 500);
delete pen;
delete graphics;
EndPage(hdcPrint);
EndDoc(hdcPrint);
DeleteDC(hdcPrint);
GdiplusShutdown(gdiplusToken);
return 0;
}
在前面的代码中,三个 GDI+ 绘图命令位于对 StartDoc 和 EndDoc 函数的调用之间,每个函数都接收打印机设备上下文句柄。 StartDoc 和 EndDoc 之间的所有图形命令都路由到临时图元文件。 调用 EndDoc 后,打印机驱动程序会将图元文件中的数据转换为使用的特定打印机所需的格式。
注意
如果未为正在使用的打印机启用后台打印,则图形输出不会路由到图元文件。 相反,单个图形命令由打印机驱动程序处理,然后发送到打印机。
通常,你不希望像在前面的控制台应用程序中那样对打印机名称进行硬编码。 对名称进行硬编码的一种替代方法是调用 GetDefaultPrinter 以获取默认打印机的名称。 在调用 GetDefaultPrinter 之前,必须分配一个足够大的缓冲区来保存打印机名称。 可以通过调用 GetDefaultPrinter 来确定所需缓冲区的大小,并将 NULL 作为第一个参数传递。
注意
GetDefaultPrinter 函数仅在 Windows 2000 及更高版本上受支持。
以下控制台应用程序获取默认打印机的名称,然后在该打印机上绘制一个矩形和一个椭圆。 Graphics::D rawRectangle 调用位于对 StartPage 和 EndPage 的调用之间,因此矩形本身位于页面上。 同样,椭圆本身位于页面上。
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;
INT main()
{
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
DWORD size;
HDC hdcPrint;
DOCINFO docInfo;
ZeroMemory(&docInfo, sizeof(docInfo));
docInfo.cbSize = sizeof(docInfo);
docInfo.lpszDocName = "GdiplusPrint";
// Get the size of the default printer name.
GetDefaultPrinter(NULL, &size);
// Allocate a buffer large enough to hold the printer name.
TCHAR* buffer = new TCHAR[size];
// Get the printer name.
if(!GetDefaultPrinter(buffer, &size))
{
printf("Failure");
}
else
{
// Get a device context for the printer.
hdcPrint = CreateDC(NULL, buffer, NULL, NULL);
StartDoc(hdcPrint, &docInfo);
Graphics* graphics;
Pen* pen = new Pen(Color(255, 0, 0, 0));
StartPage(hdcPrint);
graphics = new Graphics(hdcPrint);
graphics->DrawRectangle(pen, 50, 50, 200, 300);
delete graphics;
EndPage(hdcPrint);
StartPage(hdcPrint);
graphics = new Graphics(hdcPrint);
graphics->DrawEllipse(pen, 50, 50, 200, 300);
delete graphics;
EndPage(hdcPrint);
delete pen;
EndDoc(hdcPrint);
DeleteDC(hdcPrint);
}
delete buffer;
GdiplusShutdown(gdiplusToken);
return 0;
}