Page 1 of 1

[IE] Rendering an IHTMLElement to an Image File

Posted: 17-Apr-2014, 19:00
by Administrator
Rendering an IHTMLElement to an Image File

What This Article Is About
This code can take a snapshot of a webpage and store it as an image for viewing later.

I would like to extract a bitmap from an html page. I expected to find a IStream, IPersistStream or IPersistStreamInit from the IHTMLImgElement I got in the web page. However I can't found any of those.
Is there some interface I could use to get the bitmap ?

Answer: Use IHTMLElementRender.
Using QueryInterface on your IHTMLImgElement will get a pointer to the IHTMLElementRender interface, then call DrawToDC in a memory DC.
There are several ways to save a bitmap when it's in a memory DC.

The Source Code of the First Implementation

Code: Select all

   CHtmlView* pView = (CHtmlView*)this->GetActiveView();

   CComPtr<IDispatch> spDisp(pView->GetHtmlDocument());

   CComPtr<IHTMLDocument2> spDoc;
   if (FAILED(spDisp->QueryInterface(IID_IHTMLDocument2, (void**)&spDoc)))
      AfxMessageBox(_T("Unable to get the HTML Document off the browser."));

   CComPtr<IHTMLElement> spBody;
   if ( FAILED(spDoc->get_body(&spBody)) )
      AfxMessageBox(_T("Unable to get the body of the HTML Document."));

   CComPtr<IHTMLElementRender> spElemRender;
   if ( FAILED(spBody->QueryInterface(IID_IHTMLElementRender, (void**)&spElemRender)) )
      AfxMessageBox(_T("Unable to create render of the body element."));

   long cx=0, cy=0;

   Bitmap myBmp(cx, cy);
   Graphics g(&myBmp);
   HDC mydc = g.GetHDC();
   if (mydc != NULL)

   CLSID jpegClsid;
   GetEncoderClsid(_T("image/jpeg"), &jpegClsid);
   myBmp.Save((LPCTSTR)sFileName, &jpegClsid, NULL);