MFC › 6. Graphics and Printing
GDI+ and Printing
Anti-aliased drawing and OnPrint/print preview.
Explanation
GDI+
GDI+ (header <gdiplus.h>, library gdiplus.lib) is the object-oriented successor to GDI for 2D graphics: anti-aliasing, alpha transparency, gradients, rotation/scaling transforms and many image formats. It sits in the Gdiplus namespace: Graphics, Pen, SolidBrush, LinearGradientBrush, Bitmap, Font, GraphicsPath.
Use steps:
- Start up once in
InitInstance:GdiplusStartup(&token, &input, nullptr). - In
OnDraw:Gdiplus::Graphics g(pDC->GetSafeHdc());theng.SetSmoothingMode(SmoothingModeAntiAlias)and draw. - Shut down in
ExitInstance:GdiplusShutdown(token).
GDI+ objects are small C++ objects freed by their destructors (no SelectObject); colors are ARGB (Color(128, 255, 0, 0) = half-transparent red).
Printing
MFC’s printing is built into CView. The same OnDraw renders to the screen, the print preview and the printer, because it receives a CDC for the target. For multi-page output override:
| Function | Role |
|---|---|
OnPreparePrinting(CPrintInfo*) |
set the page range (pInfo->SetMaxPage), call DoPreparePrinting(pInfo) to show the Print dialog |
OnBeginPrinting(pDC, pInfo) |
allocate printer fonts, measure the page, compute the page count |
OnPrepareDC(pDC, pInfo) |
set mapping mode for each page; set pInfo->m_bContinuePrinting = FALSE to stop |
OnPrint(pDC, pInfo) |
draw one page (pInfo->m_nCurPage, 1-based) |
OnEndPrinting |
clean up |
Hook up the commands: ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint), ID_FILE_PRINT_DIRECT, ID_FILE_PRINT_PREVIEW. Use pDC->IsPrinting() and the printer’s resolution pDC->GetDeviceCaps(LOGPIXELSX/Y), HORZRES, VERTRES to scale to the printable area.
Example
A view that draws with GDI+ and prints a long list over several pages:
#define NOMINMAX // keep windows.h from defining min/max macros (GDI+ needs this)
#include <afxwin.h>
#include <afxext.h>
#include <algorithm>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
class CReportApp : public CWinApp {
ULONG_PTR m_gdiplusToken = 0;
public:
BOOL InitInstance() override {
GdiplusStartupInput input;
GdiplusStartup(&m_gdiplusToken, &input, nullptr); // once, before any GDI+ call
return CWinApp::InitInstance();
}
int ExitInstance() override {
GdiplusShutdown(m_gdiplusToken); // after all GDI+ objects are gone
return CWinApp::ExitInstance();
}
};
CReportApp theApp;
class CReportView : public CView {
DECLARE_DYNCREATE(CReportView)
protected:
static const int kLines = 200;
int m_linesPerPage = 40;
void OnDraw(CDC* pDC) override {
if (pDC->IsPrinting()) return; // printing is handled in OnPrint
Graphics g(pDC->GetSafeHdc());
g.SetSmoothingMode(SmoothingModeAntiAlias); // smooth edges
g.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
LinearGradientBrush bg(Point(0, 0), Point(0, 120), Color(255, 220, 235, 255), Color(255, 120, 160, 220));
g.FillRectangle(&bg, 0, 0, 400, 120);
SolidBrush halfRed(Color(128, 255, 0, 0)); // alpha = 128
g.FillEllipse(&halfRed, 40, 20, 140, 80);
Pen pen(Color(255, 20, 60, 140), 3.0f);
g.DrawEllipse(&pen, 120, 20, 140, 80); // overlaps: you can see through the red
FontFamily family(L"Segoe UI");
Gdiplus::Font font(&family, 16, FontStyleBold, UnitPixel);
SolidBrush text(Color(255, 0, 0, 0));
g.DrawString(L"GDI+ anti-aliased text", -1, &font, PointF(10, 125), &text);
}
// ---------------- printing ----------------
BOOL OnPreparePrinting(CPrintInfo* pInfo) override {
pInfo->SetMaxPage(1); // real count is known in OnBeginPrinting
return DoPreparePrinting(pInfo); // shows the Print dialog
}
void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) override {
int pageHeight = pDC->GetDeviceCaps(VERTRES); // device units
int lineHeight = pDC->GetDeviceCaps(LOGPIXELSY) / 6; // about 1/6 inch per line
m_linesPerPage = std::max(1, pageHeight / lineHeight - 4);
pInfo->SetMaxPage((kLines + m_linesPerPage - 1) / m_linesPerPage);
}
void OnPrint(CDC* pDC, CPrintInfo* pInfo) override {
int lineHeight = pDC->GetDeviceCaps(LOGPIXELSY) / 6;
int first = (pInfo->m_nCurPage - 1) * m_linesPerPage;
int y = lineHeight * 2; // top margin
for (int i = first; i < std::min(first + m_linesPerPage, kLines); ++i) {
CString line;
line.Format(_T("Line %d of the report"), i + 1);
pDC->TextOut(lineHeight * 2, y, line);
y += lineHeight;
}
CString footer;
footer.Format(_T("Page %u of %u"), pInfo->m_nCurPage, pInfo->GetMaxPage());
pDC->TextOut(lineHeight * 2, pInfo->m_rectDraw.bottom - lineHeight * 2, footer);
}
void OnEndPrinting(CDC*, CPrintInfo*) override {}
DECLARE_MESSAGE_MAP()
};
IMPLEMENT_DYNCREATE(CReportView, CView)
BEGIN_MESSAGE_MAP(CReportView, CView)
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
END_MESSAGE_MAP()
Common pitfalls
- GDI+ objects (
Graphics,Bitmap) must all be destroyed beforeGdiplusShutdown. A globalBitmapthat outlives it crashes at exit. - The
min/maxmacro clash: GDI+ headers fail to compile withwindows.h’s macros. DefineNOMINMAX(project-wide in the preprocessor settings, or before the first#includeas above) and usestd::min/std::max. - Screen pixels aren’t printer pixels: never hard-code pixel sizes for printing; derive them from
GetDeviceCaps(a 600-dpi printer page is about 5000 device units wide). GetMaxPage()returns0xFFFFuntil you set it: set the real count inOnBeginPrinting.- Fonts created for the screen need to be recreated for the printer DC (point sizes scale; pixel sizes don’t).
- Mapping mode set in
OnPrepareDCapplies to each page; forgetting it for printing gives tiny output. - Print preview calls
OnPrinttoo; don’t useGetClientRectthere. UsepInfo->m_rectDraw.
Win32 vs MFC
Win32 printing is StartDoc / StartPage / EndPage / EndDoc and a PrintDlg call, and you write all the pagination code. MFC’s view calls those and runs OnPrint per page; MFC supplies the print preview window as well. For modern PDF output consider printing to the “Microsoft Print to PDF” printer.
Exercises
1. Where do you compute the number of pages for a document of unknown length?
In OnBeginPrinting, after the printer DC is known: measure the page with GetDeviceCaps, compute the number of pages, then call pInfo->SetMaxPage(count).