How to Take a Full Page Screenshot Using Chromium and C#

Capturing a full page screenshot of a website can be helpful for website archiving, reporting, and automated monitoring. This guide will show you how to build a C# console application that converts a web page into a JPG image using Chromium via CefSharp.

This step-by-step tutorial will help you set up your development environment, install CefSharp, and write the necessary code to capture a full webpage screen capture of any website.

Step 1: Setting Up Your Development Environment

Before we start coding, make sure you have:

  1. Visual Studio (any recent version)

  2. .NET Framework 4.6.2 or later installed on your system

Step 2: Create a New Console App (.NET Framework)

To create a new C# console application:

  1. Open Visual Studio.

  2. Create a new project:

    1. Click on File > New > Project.

    2. Choose Console App under .NET. Click Next.

    Choose Console App
  3. Configure the project:

    1. Name it WebScreenshot.

    2. Choose a suitable save location.

    3. Select .NET Framework 4.6.2 or later.

    4. Click Create.

    Name your project

Your project is now set up!

Step 3: Install CefSharp NuGet Package

Since we're using Chromium via CefSharp, we need to install CefSharp.OffScreen, which allows us to render web pages without a visible browser window.

Steps to Install:

  1. Open NuGet Package Manager:

    1. In Solution Explorer, right-click your project.

    2. Select Manage NuGet Packages.

  2. Search for CefSharp.OffScreen:

    1. Click the Browse tab.

    2. Type CefSharp.OffScreen in the search box.

  3. Install the package:

    1. Select CefSharp.OffScreen and click Install.

    2. Accept any license agreements.

    CefSharp.OffScreen Install

Now, CefSharp is installed and ready to use.

Step 4: Writing the Code

Below is the complete C# code that captures a full-page screenshot of a website using CefSharp. The program initializes Chromium in headless mode, loads a webpage, determines its full height, resizes the browser, and then captures a full-page screenshot.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CefSharp;
using CefSharp.OffScreen;

namespace WebScreenshot
{
    class Program
    {
        private static ChromiumWebBrowser browser;
        static void Main(string[] args)
        {
            try
            {
                // Initialize CefSharp in headless mode
                var settings = new CefSettings { WindowlessRenderingEnabled = true };
                Cef.Initialize(settings);

                // Run the screenshot process
                WebToJpgHeadless().GetAwaiter().GetResult();

                // Shut down Chromium to free resources
                Cef.Shutdown();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                Cef.Shutdown();
            }
        }

        private static async Task WebToJpgHeadless()
        {
            // Set the target URL
            string inputUrl = "https://www.google.com/";

            // Define the output path for the screenshot
            string outputPath = @"C:\Test\Screenshot.jpg";

            // Create a new browser instance and load the webpage
            browser = new ChromiumWebBrowser(inputUrl);
            await browser.WaitForInitialLoadAsync();

            using (var browser = new ChromiumWebBrowser(inputUrl))
            {
                await browser.WaitForInitialLoadAsync();

                // Run JavaScript to get the full page dimensions
                var dimensions = await browser.EvaluateScriptAsync(@"
                (function() {
                    var body = document.body,
                        html = document.documentElement;
                    var width = Math.max(body.scrollWidth, body.offsetWidth,
                        html.clientWidth, html.scrollWidth, html.offsetWidth);
                    var height = Math.max(body.scrollHeight, body.offsetHeight,
                        html.clientHeight, html.scrollHeight, html.offsetHeight);
                    return { width: width, height: height };
                })();
               ");

                if (dimensions.Success && dimensions.Result is IDictionary<string, object> result)
                {
                    // Extract width and height from the script result
                    int width = Convert.ToInt32(result["width"]);
                    int height = Convert.ToInt32(result["height"]);

                    // Resize the browser to fit the full webpage
                    browser.Size = new System.Drawing.Size(width, height);

                    // Capture the screenshot and save it
                    var screenshot = await browser.CaptureScreenshotAsync();
                    System.IO.File.WriteAllBytes(outputPath, screenshot);

                    Console.WriteLine($"Screenshot saved to {outputPath}");
                }
                else
                {
                    Console.WriteLine("Failed to get page size.");
                }
            }
        }
    }
}

How the Code Works:

  1. Initialize CefSharp in headless mode.

  2. Create a ChromiumWebBrowser instance to load a web page.

  3. Use JavaScript to determine the full height of the page.

  4. Resize the browser so the entire page is visible.

  5. Capture the screenshot using CaptureScreenshotAsync().

  6. Save the image as a JPG file.

Output:

When you run the program, it will take a full-page screenshot of https://www.google.com/ and save it as Screenshot.jpg in C:\Test\.

Conclusion

You've successfully built a full-page screenshot tool using Chromium and CefSharp in C#. This method generates thumbnails, monitors websites, and automates reports.

With just a few lines of code, you can capture full-page screen captures from any website and save them as images.

Happy coding!