Skip to main content Skip to footer

How to Render HTML to PNG, SVG, JPEG, GIF in .NET 6 C# Apps

There is always a need for HTML to be more accessible to printers, saved for future printing or archiving, and for later scanning for receipts (just a few examples). GrapeCity Documents for Imaging (GcImaging) is a high-performance imaging library that can create, load, modify and save images in .NET 6 and .NET 7 applications using C# or VB.NET, with full support on Windows, macOS, and Linux; this task becomes much less problematic. The library is a feature-rich API that loads popular image formats like BMP, JPEG, TIFF, GIF, and PNG.

It can apply advanced image processing techniques and save them; read/write images; modify images (like rotate, crop, and resize); convert images; apply dithering and thresholding effects on grayscale images; apply effects on RGB images, draw and fill graphics on images, draw advanced text with full font handling, text, paragraph formatting on images, apply advanced TIFF features, and much more.

All versions of GcImaging starting with version 3 or greater, include the capability of programmatically converting HTML content to Image formats like PNG, JPEG, TIFF, ICO, and others. There are only minor coding differences in saving to these other formats as opposed to the natively supported JPEG, PNG, and WEBP images using C#.

You may want to render HTML to images for various reasons:

  • A company may have a standard HTML fragment that renders its logo and other content. It may want to generate an image of the same to share in the official documents, as in Word, Excel, etc. This image can be used offline for a simple representation of the logo
  • One may also want to take a snapshot of pricing details online—for example, airline prices with different departure and arrival times. Using the appropriate search criteria can help your users return to the one they want

This blog will cover the following:

Ready to Try Out the Latest Version? Download GrapeCity Documents for Imaging Today!

GcHtml Packages

With GcHtml version 6, a separate utility library included with GcImaging utilizes existing Chrome, Edge, or Chromium browsers normally installed within an operating system. If no browser is available, Chromium may be programmatically downloaded so that GcHtml will work. This new and improved component is much more efficient and uses a single instance of a browser to do the work instead of opening multiple browser processes.

The browser engine is not provided as a part of the GcHtml project but may be downloaded if Chrome or Edge browsers are not already in place on the target system (this can be done programmatically as well). GcHtml currently works on AMD and Intel-based 32/64-bit processors and ARM64 architecture. The browser engine is always working in a separate process.

It consists of the following NuGet packages:

With GcHtml, you can natively render HTML content to JPEG, PNG, and WEBP images and specify PageOptions based on the settings required for each output file. However, 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. Using the new GcHtmlBrowser() method, opening a page, specifying settings, and saving as JPG, PNG, or WEBP (native to GcHtml).

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. Using 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");

HTML File to JPEG or PNG Image using C#

Let's consider an e-commerce firm that generates its invoices in HTML. These invoices are related 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 6 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 GrapeCity.Documents.Imaging under the ‘Browse’ tab and click Install.
  4. Similarly, install "GrapeCity.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’, respectively, to continue.

  1. Add namespaces in Program.cs file:
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Imaging;
using GrapeCity.Documents.Drawing;
using System.Drawing;
  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

Download the working sample here.

HTML String to JPEG or PNG Image using C#

You can use C# to programmatically render an HTML string as an image using a similar process with GcHtml (first follow steps 1-4 above to ensure the GrapeCity 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

Download the working sample here.

WebPage to JPEG or PNG Image 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 over 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 Solution’s GcHtml package and the C# programming language.

Here is some code as an example (first follow steps 1-4 above to ensure the GrapeCity 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

Download the working sample here.

HTML Conversion to TIFF, BMP, ICO, and GIF 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 GcHtml API. Here is the code to loop through and create 5 different images (the maximum allowed by our trial software without a key):

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 "png":
                    bitmap.SaveAsPng("Sample3.png");
                    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;
                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", "png", "gif", "webp", "webp"};

var myMaker = new CreateImages();

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

Download the working sample here.

Check out our video where we discuss how to programmatically convert HTML to PNG, SVG, JPEG, GIF in .NET 6 C# Apps:

Thanks for checking out our educational information. Good luck 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 | GcHtml Architecture | Demo

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

Ready to Try Out the Latest Version? Download GrapeCity Documents for Imaging Today!

comments powered by Disqus