来源:www.cncfan.com | 2006-4-15 | (有5094人读过)
Creating an image of the current HTML Turning the contents of the WebBrowser into an image is not as straight forward as you may expect. Looking at the IHTMLXxx interfaces does turn up an IHTMLElementRenderer interface. IHTMLElementRenderer contains:
IHTMLElementRenderer::Draw(HDC hDC);You can try to use this method, but I have found that it is not very reliable and reacts inconsistently depending on the type of HDC you give it. A more reliable method uses an older OLE method. IViewObject supports the ability to render to an HDC. The IWebBrowser2::Document property can be QueryInterfaced for IViewObject. Two things to note while using this method, (1) you will probably want to turn off the scrollbars and 3D border since they will show up in the image and (2) you will want to resize the WebBrowser to the size of the contained HTML if you want to capture the entire content in the image. You may want to only make these changes temporarily and change them back after the image is captured:
IHTMLDocument2* pDoc = ...; IHTMLElement* pBodyElem = 0; HRESULT hr = pDoc->get_body(&pBodyElem); if (SUCCEEDED(hr)) { IHTMLBodyElement* pBody = 0; hr = pBodyElem->QueryInterface(IID_IHTMLBodyElement, (void**)&pBody); if (SUCCEEDED(hr)) { // hide 3D border IHTMLStyle* pStyle; hr = pBodyElem->get_style(&pStyle); if (SUCCEEDED(hr)) { pStyle->put_borderStyle(CComBSTR("none")); pStyle->Release(); }
// hide scrollbars pBodyElement->put_scroll(CComBSTR("no"));
// resize the browser component to the size of the HTML content IHTMLElement2* pBodyElement2; hr = Body->QueryInterface(IID_IHTMLElement2, (void**)&BodyElement2) if (SUCCEEDED(hr)) { long iScrollWidth = 0; pBodyElement2->get_scrollWidth(&iScrollWidth);
long iScrollHeight = 0; pBodyElement2->get_scrollHeight(&iScrollHeight);
// these lines depend on your WebBrowser wrapper pWebBrowser->SetWidth(iScrollWidth); pWebBrowser->SetHeight(iScrollHeight);
pBodyElement2->Release();
IViewObject* pViewObject; pDoc->QueryInterface(IID_IViewObject, (void**)&pViewObject); if (pViewObject) { /* however you want to make your image HDC. You can size it using iScrollHeight & iScrollWidth */ HDC hImageDC = ... // could be bitmap or enhanced metafile HDC hScreenDC = ::GetDC(0); RECT rcSource = {0, 0, iScrollWidth, iScrollHeight}; hr = pViewObject->Draw(DVASPECT_CONTENT, 1, NULL, NULL, hScreenDC, hImageDC, rcSource, NULL, NULL, 0); ::ReleaseDC(0, hScreenDC); pViewObject->Release(); } } pBody->Release(); } pBodyElem->Release(); }
pDoc->Release(); As you can see, there is a lot of things you can do using the MSHTML object model. Some of it can be tricky. Other things just aren't supported as well as they should be for an application developer. I guess you could say that application developers have their own list of issues for IE.
|