Screenshot – Chrome – Selenium – Entire page

How to make screenshot of entire page in chrome /beyond 16384px height/ – C# code (should work in other languages) – solved by taking 16k tall screenshot, stitching them together later

RELATED LINKS – CHROME BUG FOR screenshot height > 16384px

List<Bitmap> list_imageToStitch = new List<Bitmap>();

Dictionary<string, Object> metrics = new Dictionary<string, Object>();
metrics["width"] = ((ChromeDriver)webDriver).ExecuteScript("return Math.max(window.innerWidth,document.body.scrollWidth,document.documentElement.scrollWidth)");
metrics["height"] = ((ChromeDriver)webDriver).ExecuteScript("return Math.max(window.innerHeight,document.body.scrollHeight,document.documentElement.scrollHeight)");
metrics["deviceScaleFactor"] = ((ChromeDriver)webDriver).ExecuteScript("return window.devicePixelRatio");
metrics["mobile"] = ((ChromeDriver)webDriver).ExecuteScript("return typeof window.orientation !== 'undefined'");

int maxAllowedHeight = 16000;
int pageHeight = Int32.Parse(metrics["height"].ToString());
int screenshotCount = Convert.ToInt32(Math.Ceiling(((double)pageHeight / (double)16000)));
for (int i = 0; i < screenshotCount; i++)
{
    Dictionary<string, object> parameters = new Dictionary<string, object>();
    parameters["format"] = "png";
    parameters["fromSurface"] = true;
    parameters["captureBeyondViewport"] = true;
    Dictionary<string, object> parametersClip = new Dictionary<string, object>();
    parametersClip["width"] = metrics["width"];
    parametersClip["height"] = ((i < (screenshotCount - 1)) ? (maxAllowedHeight) : (pageHeight % 16000));
    parametersClip["x"] = 0;
    parametersClip["y"] = i * maxAllowedHeight;
    parametersClip["scale"] = 1;
    parameters["clip"] = parametersClip;
    object screenshotObject = ((ChromeDriver)webDriver).ExecuteChromeCommandWithResult("Page.captureScreenshot", parameters);
    Dictionary<string, object> screenshotResult = screenshotObject as Dictionary<string, object>;
    string screenshotData = screenshotResult["data"] as string;
    Screenshot screenshot = new Screenshot(screenshotData);

    if (screenshotCount > 1)
    {
        Bitmap bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));
        list_imageToStitch.Add(bmpScreen);
    }
    else
    {
       screenshot.SaveAsFile(screenshotFileName, ScreenshotImageFormat.Png);
    }
}

if (screenshotCount > 1)
{
    int newWidth = list_imageToStitch.Max(image => image.Width);
    int newHeight = list_imageToStitch.Sum(image => image.Height);
    Bitmap bitmapStitched = new Bitmap(newWidth, newHeight);
    using (Graphics graphics = Graphics.FromImage(bitmapStitched))
    {
        int height = 0;
        foreach (Bitmap image in list_imageToStitch)
        {
            graphics.DrawImage(image, 0, height);
            height += image.Height;
        }
    }
    bitmapStitched.Save(screenshotFileName, ImageFormat.Png);
}