Printing a bitmap

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:

Collapse

void PrintBitmap(LPCTSTR filename) {
 CPrintDialog printDlg(FALSE);
 printDlg.GetDefaults();
 // Or get from user:

 // if (printDlg.DoModal() == IDCANCEL)   

 //        return;

 CDC dc;
 if (!dc.Attach(printDlg.GetPrinterDC())) {
  AfxMessageBox(_T("No printer found!")); return;
 }
 
 dc.m_bPrinting = TRUE;
 DOCINFO di;    
 // Initialise print document details

 ::ZeroMemory (&di, sizeof (DOCINFO));
 di.cbSize = sizeof (DOCINFO);
 di.lpszDocName = filename;
 BOOL bPrintingOK = dc.StartDoc(&di); // Begin a new print job

 // Get the printing extents

 // and store in the m_rectDraw field of a

 // CPrintInfo object

 CPrintInfo Info;
 Info.SetMaxPage(1); // just one page

 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();    // begin new page

  Info.m_nCurPage = page;
  CBitmap bitmap;
  // LoadImage does the trick here, it creates a DIB section

  // You can also use a resource here

  // by using MAKEINTRESOURCE() ... etc.

  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;
   // create memory device context

   CDC memDC;
   memDC.CreateCompatibleDC(&dc);
   CBitmap *pBmp = memDC.SelectObject(&bitmap);
   memDC.SetMapMode(dc.GetMapMode());
   dc.SetStretchBltMode(HALFTONE);
   // now stretchblt to maximum width on page

   dc.StretchBlt(0, 0, maxw, maxh, &memDC, 0, 0, w, h, SRCCOPY);
   // clean up

   memDC.SelectObject(pBmp);
   bPrintingOK = (dc.EndPage() > 0);   // end page

 }
 if (bPrintingOK)
   dc.EndDoc(); // end a print job

 else dc.AbortDoc();           // abort job.

}

That's all there is to it. Have a nice day!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值