[IE] Rendering an IHTMLElement to an Image File

Programming applications for MS Windows
Post Reply
Administrator
Site Admin
Posts: 81
Joined: 26-Feb-2014, 17:54

[IE] Rendering an IHTMLElement to an Image File

Post by Administrator » 17-Apr-2014, 19:00

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."));
      return;
   }

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

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

   long cx=0, cy=0;
   spBody->get_offsetWidth(&cx);
   spBody->get_offsetHeight(&cy);

   Bitmap myBmp(cx, cy);
   Graphics g(&myBmp);
   HDC mydc = g.GetHDC();
   if (mydc != NULL)
   {
      spElemRender->DrawToDC(mydc);
      g.ReleaseHDC(mydc);
   }

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

Post Reply