Skip to main content Skip to footer

How to Convert HTML to Image (PNG, SVG, JPEG, GIF) in C# .NET Apps

  • 0 Comments
Quick Start Guide
Tutorial Concept

Learn how to render or convert HTML to images, including PNG, SVG, JPEG, and GIF, in your C# .NET desktop apps with Document Solutions for Imaging.

What You Will Need
Controls Referenced DsHtml

Rendering HTML to image formats is essential in various scenarios, such as printing, archiving, or generating snapshots for easy sharing. Document Solutions for Imaging (DsImaging) provides a powerful, high-performance imaging library that allows .NET 8 applications to seamlessly create, load, modify, and save images in various formats like BMP, JPEG, TIFF, GIF, and PNG, with full support across Windows, macOS, and Linux. By leveraging this library, developers can easily integrate advanced image processing capabilities, including resizing, rotating, applying effects, and drawing graphics or text on images.

The DsHtml library features included with DsImaging enhance this capability by allowing developers to programmatically convert HTML content into image formats like PNG, JPEG, TIFF, and ICO, with minimal code changes from standard image formats. This makes it ideal for scenarios like generating images of logos or snapshots of dynamic online content, such as pricing details. By using DsImaging and DsHtml, developers can effortlessly integrate HTML-to-image rendering into their applications, providing greater flexibility for creating visual representations of HTML content, saving time, and enhancing document workflows.

This blog will cover the following:

Ready to Try Out the Latest Version? Download Document Solutions for Imaging Today!

Set Up DsHtml and DsImaging

DsHtml is a utility library included with DsImaging that leverages the Chrome, Edge, or Chromium browsers typically installed on an operating system. If no browser is available, Chromium may be programmatically downloaded so that DsHtml will work. This updated component is more efficient, utilizing a single browser instance to handle rendering, rather than launching multiple browser processes.

The browser engine is not provided as part of the DsHtml library. Still, it may be downloaded if Chrome or Edge browsers are not installed on the target system (which can also be accomplished programmatically). DsHtml supports AMD and Intel-based 32/64-bit processors, as well as ARM64 architecture, with the browser engine always running in a separate process.

DsHtml is self-contained, consisting of the following NuGet packages:

With DsHtml, you can natively render HTML content to JPEG, PNG, and WEBP images and specify PageOptions based on the settings required for each output file. The following formats are supported by creating a GcBitmap stream and rendering with a SaveAsXXX method: BMP, GIF, TIFF, and ICO.

Broadly, there are two ways to render HTML to an image:

1. Use the new GcHtmlBrowser() method, open a page, specify settings, and save as JPG, PNG, or WEBP (native to DsHtml).

using GrapeCity.Documents.Html;
using System.Drawing;

var browserPath = BrowserFetcher.GetSystemChromePath();
using var browser = new GcHtmlBrowser(browserPath);

var uri = new Uri("Sample2.html", UriKind.Relative);
using var pg = browser.NewPage(uri, new PageOptions
{
    WindowSize = new Size(700, 300),
    DefaultBackgroundColor = Color.AliceBlue
});
pg.SaveAsPng("Sample2.png");

2. Use the GcBitmap() method with PageOptions() to render to all other supported image types using a bitmap.SaveAsXXX, where XXX is the image type (i.e., SaveAsTiff, SaveAsGif, etc.)

using GrapeCity.Documents.Html;
using GrapeCity.Documents.Imaging;
using System.Drawing;

var browserPath = BrowserFetcher.GetSystemEdgePath();
using var browser = new GcHtmlBrowser(browserPath);

string html = "<p style=\"color: green; text-shadow: 3px 3px 3px gray;\">JavaScript can change HTML content.</p>";
using var pg = browser.NewPage(html, new PageOptions { DefaultBackgroundColor = Color.LemonChiffon });

using var bitmap = new GcBitmap();
pg.RenderAndCrop(bitmap, new PngOptions { Scale = 3 }, Color.LemonChiffon, 100, 50, 20, 100);
bitmap.SaveAsTiff("Sample3.tiff");

Render HTML to JPEG or PNG Using C#

Let's consider an e-commerce firm that generates its invoices in HTML. These invoices relate to the customers' transactions and can be rendered programmatically using C# in separate JPEG or PNG images to generate a single report. All stakeholders can view the potential customers and then analyze the data for quarterly sales targets.

To meet this requirement, generate images corresponding to the invoices.

The steps are as follows:

  1. Open Visual Studio 2022 and create a .NET 8 Console application.
  2. In your application, right-click 'Dependencies' and select 'Manage NuGet Packages.'
  3. With the "Package source" set to the NuGet website, search for "DS.Documents.Imaging" under the 'Browse' tab and click 'Install.'
  4. Similarly, install "DS.Documents.Html" (mandatory for HTML rendering).

Note: While installing, you'll receive two confirmation dialogs: 'Preview Changes' (if the "Show preview window" option setting for the package is checked) and 'License Acceptance.' Click 'Ok' and 'I Agree' to continue.

  1. Add namespaces in Program.cs file:
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Imaging;
using GrapeCity.Documents.Drawing;
using System.Drawing;

Note: Previously, the packages used the "GrapeCity" prefix instead of the "DS" prefix. We maintained the internal namespace to avoid breaking changes for users who utilized the previous namespace, resulting in the using statements above.

  1. Write the sample code:
var browserPath = BrowserFetcher.GetSystemEdgePath();
using var browser = new GcHtmlBrowser(browserPath);

var uri = new Uri("Invoice.html", UriKind.Relative);
using var pg = browser.NewPage(uri, new PageOptions
{
    WindowSize = new Size(1024, 1024)
});
pg.SaveAsPng("invoice.png");

HTML File to PNG

Render an HTML String to JPEG or PNG Using C#

You can use C# to programmatically render an HTML string as an image using a similar process with DsHtml (first, follow steps 1-4 above to ensure the Document Solutions NuGet packages are installed):

using GrapeCity.Documents.Imaging;
using GrapeCity.Documents.Html;
using System.Drawing;

//set up the internal browser to utilize chromium or installed browser
var browserPath = BrowserFetcher.GetSystemEdgePath();
using var browser = new GcHtmlBrowser(browserPath);

//now set up the variable containing the "thank you for shopping" message

string html = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<style>" +
"p.round {" +
"font: 36px verdana;" +
"color: Red;" +
"border: 4px solid SlateBlue;" +
"border-radius: 16px;" +
"padding: 3px 5px 3px 5px;" +
"}" +
"</style>" +
"</head>" +
"<body>" +
"<p class='round'>Thank You for shopping with us!</p>" +
"<p class='round'>Hope to see you again soon.</p>" +
"</body>" +
"</html>";

//now create a browser instance and load the HTML string
using var pg = browser.NewPage(html, new PageOptions 
    { 
        DefaultBackgroundColor = Color.White, 
        WindowSize = new Size(1024,1024)
    });

//now create the png file
pg.SaveAsPng("thankYou.png");

HTML String to PNG

Render an Entire WebPage to JPEG or PNG Using C#

To share the "Help and Customer Services" a firm offers related to a product, it may decide to generate images from the web page and provide them to the customers by email. This can draw attention to the product and its related services.

This conversion to JPEG or PNG can be carried out easily using Document Solutions' DsHtml package and the C# programming language.

Below is some example code (first, follow steps 1-4 above to ensure the Document Solutions NuGet packages are installed):

using GrapeCity.Documents.Html;
using GrapeCity.Documents.Imaging;
using System.Drawing;

//first get the path to the browser on the system
var browserpath = BrowserFetcher.GetSystemEdgePath();
using var browser = new GcHtmlBrowser(browserpath);

//now browse to the URL that needs converting, in this case
var uri = new Uri("https://www.amazon.com/gp/help/customer/display.html?ref_=hp_gcs_csd_d2_649_1_202138870_oQZCy5KxYC&nodeId=202138870&qid=1669741042700&sr=1");

using var pg = browser.NewPage(uri, new PageOptions
{
    WindowSize = new Size(1024, 1024)
});
//Now save as the three native image types.  Same instance can be used to save all three.
pg.SaveAsPng("AmazonShow_Help.png");
pg.SaveAsJpeg(“AmazonShow_Help.jpeg”);
pg.SaveAsWebp(“AmazonShow_Help.webp”);

Web page to PNG

Advanced Formats: Converting HTML to GIF, TIFF, BMP, ICO, and WebP Using C#

Reference the demonstration code for the complete application, but the code snippet below shows how to handle all other types of HTML to Image conversions using C# and the DsHtml API. The code to loop through and create five different images (the maximum allowed by our trial software without a key) is as follows:

First, follow steps 1-4 above to set up a project named 'SaveOtherImages_HTML.' Then, add a class to the project called 'CreateImages. cs' and modify the Program.cs file as below:

CreateImages.cs:

using GrapeCity.Documents.Html;
using GrapeCity.Documents.Imaging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace SaveOtherImages_HTML
{
    internal class CreateImages
    {

        public bool makeImages(string HTML, string picType, GcHtmlBrowser myBrowser)
        {
            
            using var bitmap = new GcBitmap();

            //set up the page with background color and the HTML provided from the calling application
            using var pg = myBrowser.NewPage(HTML, new PageOptions { DefaultBackgroundColor = Color.LemonChiffon });
            pg.RenderAndCrop(bitmap, new PngOptions { Scale = 3 }, Color.LemonChiffon, 100, 50, 20, 100);

            //figure out which type to save based on information passed into the Method.
            switch(picType)
            {
                case "tiff":
                    bitmap.SaveAsTiff("Sample3.tiff");
                    return true;
                case "webp":
                    bitmap.SaveAsWebp("Sample3.webp");
                    return true;
                case "ico":
                    bitmap.SaveAsIco("Sample3.ico");
                    return true;
                case "bmp":
                    bitmap.SaveAsBmp("Sample3.bmp");
                    return true;
                case "gif"
                    bitmap.SaveAsGif("Sample3.gif");
                    return true;
                // case "png": // can be uncommented out if you want to save as png
                    // bitmap.SaveAsPng("Sample3.png");
                    // return true;
                default:
                    return false;
            }
        }
    }
}

Now, for the Program.cs file:

using GrapeCity.Documents.Html;
using GrapeCity.Documents.Imaging;
using SaveOtherImages_HTML;
using System.Drawing;
using GrapeCity.Documents.Common;
using System.Security.AccessControl;

//set up the HTML and Browsers to pass to the makeImages() method of CreateImages class.
string html = "<p style=\"color: green; text-shadow: 3px 3px 3px gray;\">JavaScript can change HTML content.</p>";

var browserPath = BrowserFetcher.GetSystemEdgePath();
using var browser = new GcHtmlBrowser(browserPath);

//set up the array to pass file types to the loop
string[] myTypes = { "tiff", "ico", "gif", "webp", "bmp"};

var myMaker = new CreateImages();

foreach (string i in myTypes)
{
    myMaker.makeImages(html, i, browser);
    Console.WriteLine("Success! - Writing - " + i);
}

Download a completed demo to check it out for yourself!

Learn how to programmatically convert HTML to PNG, SVG, JPEG, GIF in .NET 6 C# Apps in our video below:

Thanks for checking out this tutorial. Enjoy building your application to programmatically convert HTML into various forms of images, such as PNG, JPEG, or TIFF, using C# or VB!

Happy coding!

Help | DsHtml Architecture | Demo

What do you think about the new features? Leave a comment below.

Ready to Try Out the Latest Version? Download Document Solutions for Imaging Today!