I've spent half of a day googling the problem.
Found some solutions
- Using "VisualBrush" - does not work for WPF, creates black image.
- Using "FromImage" - does not work either with WPF.
Finally found this one.
Much better! But there are still "BUTS"
1. "This API was accessed with arguments from the wrong context." Did not have time to figure out, why this exception is being thrown. Something with the access permission from window to window or whatever. With other words if you get exception like that, use "Dispatcher.Invoke" part of the source-code posted below.
2. Full-Page. Some pages are longer than just one screen, so you need to make more than one screenshot to map whole page into image. There are also some DOM problems related to this task - some of the properties, like body.scrollTop just ain't being updated after you call window.scrollTo, killed some time for debugging.
Here is the source code of my final solution
browser.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate(){
HTMLDocument htmlDoc = browser.Document as HTMLDocument;
HTMLBodyClass body = (HTMLBodyClass)htmlDoc.body;
var topLeftCorner = browser.PointToScreen(new System.Windows.Point(0, 0));
var topLeftGdiPoint = new System.Drawing.Point((int)topLeftCorner.X, (int)topLeftCorner.Y);
var size = new System.Drawing.Size(body.clientWidth, body.clientHeight);
var screenShot = new Bitmap(body.scrollWidth, body.scrollHeight);
var graphics = Graphics.FromImage(screenShot);
var cP = new System.Drawing.Point();
var i = 0;
var scrollTop = 0;
var cW = (int)browser.ActualWidth;
var cH = (int)browser.ActualHeight;
do
{
scrollTop = Math.Min(cH * i, body.scrollHeight - cH);
htmlDoc.parentWindow.scrollTo(0, scrollTop);
newWindow.UpdateLayout();
Thread.Sleep(1500);
cP.X = 0;
cP.Y = scrollTop;
graphics.CopyFromScreen(topLeftGdiPoint, cP, size, CopyPixelOperation.SourceCopy);
i++;
} while (scrollTop + cH < body.scrollHeight);
screenShot.Save(@"C:\temp\screens\page.png", ImageFormat.Png);
})
);
NB: This algo only scrolls vertically (downwards). But you can easily figure out the way of screening it horizontally too.
Gl & HF
No comments:
Post a Comment