HTML strings or files are commonly used in scenarios where text formatting is applied to data. Meanwhile, it is also necessary to have these HTML files rendered as a PDF, allowing them to be available in a readable and easily accessible form. Considering this requirement, the v3 release of GrapeCity Documents introduces GcHTML, a package available with GcPdf and GcImaging products, that allows the conversion of HTML content to PDF and Images. Read more about GcHtml here (link to What's New blog).

GcHtml Packages

GcHtml is based on the Chromium web browser, working in headless mode. The browser engine is provided as a part of GcHtml project but in separate NuGet packages, one for each of the following platforms: Windows, Linux, macOS. GcHtml currently works on Intel-based 64-bit processor architecture only. It doesn’t matter whether your .NET application is built for x86, x64, or AnyCPU platform target, the browser engine is always working in a separate process.

It consists of the following NuGet packages:

  1. GrapeCity.Documents.Html
  2. GrapeCity.Documents.Html.Linux.X64
  3. GrapeCity.Documents.Html.Mac.X64
  4. GrapeCity.Documents.Html.Windows.X64

GrapeCity.Documents.Html is always required. You need to add at least one of the platform-specific packages depending on your runtime platform. To support multiple platforms, two or all three packages can be added, and the correct platform-specific package will be automatically selected by GcHtml at runtime.

GcHtml allows adding HTML content to PDF documents using GrapeCity Documents for PDF, such that the CSS styles of the web pages are retained, along with their layout and flow. It also helps in specific scenarios, such as archiving or batch processing.

Broadly, there are two ways to render HTML to PDF:

  1. DrawHtml method: It extends GcGraphics and allows it to render an HTML text or page in a PDF. This allows inserting HTML fragments into a PDF file along with other (non-HTML) content.

DrawHtml method has two overloads:

  • Draws an HTML text on GcPdfGraphics, at a specified position:
bool GcPdfGraphics.DrawHtml(string html, float x, float y, HtmlToPdfFormat format, out SizeF size);
  • Draws an HTML page specified by an URI on GcPdfGraphics, at a specified position:
bool GcPdfGraphics.DrawHtml(Uri htmlUri, float x, float y, HtmlToPdfFormat format, out SizeF size);

Here, HtmlToPdfFormat class contains attributes for rendering HTML on a GcPdfGraphics instance using DrawHtml extension methods.

  1. GcHtmlRenderer class: It's used with one of its' two constructors: the one that accepts Uri to the source HTML page and the other that accepts HTML as a plain string. RenderToPdf method of GcHtmlRenderer helps to convert the source HTML to PDF. It accepts the output file path as the first parameter. The second parameter (optional) is the PdfSettings instance that defines parameters for the Chromium PDF exporter.

HTML Files to PDF

Consider a scenario where an e-commerce firm’s transactions are carried out online. The invoices related to these transactions are generated over the same platform, in HTML format. The style and layout of these invoices may not remain intact when they are viewed offline or on other devices. Since these invoices need to be distributed to the customers and they may use different devices or browsers to view the invoices, converting HTML to PDF would be ideal so the content, layout, and formatting are all retained.

To provide these invoices to the customers via email, the company converts the HTML files to PDF.

Invoice.HTML

To serve this purpose, GcPdf and the new GcHtml package can be used.

Steps:

  1. Open Visual Studio and create a .Net Core Console application, by selecting the same from the templates.
  2. In your application, right-click ‘Dependencies’ and select ‘Manage NuGet Packages.’
  3. With the "Package source" set to Nuget website, search for GrapeCity.Documents.Pdf under the ‘Browse’ tab and click Install.
  4. Similarly, install "GrapeCity.Documents.Html" (mandatory for HTML rendering) and "GrapeCity.Documents.Html.Windows.X64" (considering that you work on Windows platform only).
  5. Note: While installation, 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.

Note: To use GcHtml on Linux, Chromium dependencies must be installed.

The following command installs the necessary packages on Ubuntu:

sudo apt-get update

sudo apt-get install libxss1 libappindicator1 libindicator7 libnss3-dev
  1. Add namespaces in Program.cs file:
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Drawing;
  1. Write the sample code:
namespace GcPdf_DrawHtml
{
  class Program
  {
    static void Main(string[] args)
     {
     //Create a GcPdfDocument instance
     var doc = new GcPdfDocument();
     //Add a new page to the document
     var page = doc.Pages.Add();
     //Take the Graphics instance of the page
     var g = page.Graphics;
     //Add the HTML file to it, using the DrawHtml method which reads the html content from the invoice file
     g.DrawHtml(File.ReadAllText("Invoice.html"), 72, 72, new HtmlToPdfFormat(), out SizeF size);
     //Save the PDF Document
     doc.Save("Invoice.pdf");
     }
  }
}

With these quick steps, you are ready with a PDF file generated from an HTML file.

Invoice.PDF

HTML String to PDF

Simple HTML strings can also be directly rendered to PDF, using DrawHtml method. This can be done as using HTML files, just that you can directly specify the HTML content now.

Follow steps (1) to (5) as mentioned above. Then add the following code to the Main method in Program.cs:

//Create a variable containing the HTML code as string
var 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>";

//Render the HTML string on the PDF, using the DrawHtml method
var ok = g.DrawHtml(html, 72, 72, new HtmlToPdfFormat() { MaxWidth = 6.5f },out SizeF size);
//Additionally, draw a rounded rectangle around this HTML string
if (ok)
{
var rc = new RectangleF(72 - 4, 72 - 4, size.Width + 8, size.Height + 8);
g.DrawRoundRect(rc, 8, Color.PaleVioletRed);
}

//Save the PDF Document
doc.Save("HTMLStringToPDF.pdf");   

HTML string to PDF

The GcHtmlRenderer class can also be directly used to render web pages to a PDF. In case the above-discussed firm wants to update its' customers or the stakeholders with the new products every month, it sends a PDF generated from the New Releases page on its' website. The process should be automated to make the stakeholders aware of the new launches regularly and create a consolidated report at the end of every year.

WebPage preview

The GcHtmlRenderer class can be used to serve this purpose. The Uri of the webpage is used and the required settings of the PDF are applied using PdfSettings class.

Follow steps (1) to (5) as mentioned above. Thereafter, add the following code to the Main method in Program.cs:

//Specify a PDF file name
var fn = @"webpage.pdf";

//Specify the url to be used for PDF conversion
var uri = new Uri(@"https://www.amazon.com/gp/new-releases/electronics/ref=zg_bs_tab_t_bsnr");
//Create a GcHtmlRenderer instance.
using (var re = new GcHtmlRenderer(uri))
{
//The PdfSettings instance is created to specify the pdf related settings that will show up in the generated PDF.
var pdfSettings = new PdfSettings(){
PageRanges = "1-100",
Margins = new Margins(0.2f), // narrow margins all around
IgnoreCSSPageSize = true, // try to ensure that we print the pages as we want
Landscape = false };

//Use the RenderToPdf method of RenderingExtension to generate the pdf file
re.RenderToPdf(fn, pdfSettings);
}

PDF obtained from the WebPage

Visit our demo and documentation for additional details:

Help | GcHtml Architecture | Demo

How do you use GcHtml in your applications? Let us know in the comments.

Try GrapeCity Documents for PDF free for 30 days

Download the latest version of GrapeCity Documents for PDF

Download Now!