Introduction
Printing a bitmap isn't very difficult to do. I saw several solutions which used creation of DIB sections and quite some code. The trick here is to use the "LoadImage
" API which can do that for you. This code uses portions of Chris Maunder's printing article:
void PrintBitmap(LPCTSTR filename) {
CPrintDialog printDlg(FALSE);
printDlg.GetDefaults();
CDC dc;
if (!dc.Attach(printDlg.GetPrinterDC())) {
AfxMessageBox(_T("No printer found!")); return;
}
dc.m_bPrinting = TRUE;
DOCINFO di;
::ZeroMemory (&di, sizeof (DOCINFO));
di.cbSize = sizeof (DOCINFO);
di.lpszDocName = filename;
BOOL bPrintingOK = dc.StartDoc(&di);
CPrintInfo Info;
Info.SetMaxPage(1);
int maxw = dc.GetDeviceCaps(HORZRES);
int maxh = dc.GetDeviceCaps(VERTRES);
Info.m_rectDraw.SetRect(0, 0, maxw, maxh);
for (UINT page = Info.GetMinPage(); page <=
Info.GetMaxPage() && bPrintingOK; page++) {
dc.StartPage();
Info.m_nCurPage = page;
CBitmap bitmap;
if(!bitmap.Attach(::LoadImage(
::GetModuleHandle(NULL), filename, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE))) {
AfxMessageBox(_T("Error loading bitmap!")); return;
}
BITMAP bm;
bitmap.GetBitmap(&bm);
int w = bm.bmWidth;
int h = bm.bmHeight;
CDC memDC;
memDC.CreateCompatibleDC(&dc);
CBitmap *pBmp = memDC.SelectObject(&bitmap);
memDC.SetMapMode(dc.GetMapMode());
dc.SetStretchBltMode(HALFTONE);
dc.StretchBlt(0, 0, maxw, maxh, &memDC, 0, 0, w, h, SRCCOPY);
memDC.SelectObject(pBmp);
bPrintingOK = (dc.EndPage() > 0);
}
if (bPrintingOK)
dc.EndDoc();
else dc.AbortDoc();
}
That's all there is to it. Have a nice day!