[]
        
(Showing Draft Content)

Render HTML to PDF

GcPdf library along with GcHtml library, lets you easily render HTML content to PDF document. With a utility library like GcHtml, you can convert HTML files like invoices and reports to PDF documents and print them without worrying about disarranged layouts, styles or formats. You can also add HTML content to PDF documents.

GcHtml is based on the industry standard Chrome web browser engine working in headless mode, offering advantage of rendering HTML to PDF on any platform - Windows, Linux and macOS. It doesn’t matter whether your .NET application is built for x64, x86 or AnyCPU platform target. The browser is always working in a separate process.

The GrapeCity.Documents.Html package contains the following namespaces:

Install GcHtml Package

Refer the steps below to install GcHtml package in your project:

  1. Open Visual Studio and create a .Net Core Console application.

  2. 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.

    Note: During installation, you’ll receive two confirmation dialogs. Click OK in the Preview Changes dialog box and click I Agree in the License Acceptance dialog box to proceed installation.

  5. Once, the GcHtml package has been installed successfully, add the namespace in Program.cs file.

    using GrapeCity.Documents.Html;
    using GrapeCity.Documents.Pdf;
    using GrapeCity.Documents.Drawing;
  6. Apply GcPdf license to GcHtmlBrowser class of GcHtml library to convert HTML to PDF. Without proper license, the count is limited to only 5 PDF conversions. The license can be applied in one of the following ways as shown below:

    • To license the instance being created


      var html = "My First HeadingMy first paragraph.";var re = new GcHtmlBrowser(html);re.ApplyGcPdfLicenseKey("key");

    • To license all the instances


      GcHtmlBrowser.SetGcPdfLicenseKey("key");

  7. Write the sample code.

Render HTML Webpage to PDF Document

GcHtml can render HTML webpage to PDF document. GcPdf provides the PdfOptions class and RenderToPdf method of GcHtmlBrowser class to render HTML files to PDF documents.

To render the HTML webpage to a PDF document, follow the steps below:

  1. Specify the PDF file path for rendering HTML webpage.

  2. Specify the HTML source (URI).

  3. Define the PDF document settings using the PdfOptions class.

  4. Convert the HTML webpage to PDF file using SaveAsPdf method of HtmlPage class.

// Get a temporary file where the web page will be rendered:
var tmp = Path.GetTempFileName();

// The Uri of the web page to render:
var uri = new Uri("http://www.google.com");

// Create an instance of GcHtmlBrowser that is used to render HTML:
var browserPath = BrowserFetcher.GetSystemChromePath();
using var browser = new GcHtmlBrowser(browserPath);

// Create an HtmlPage instance rendering the source Uri:
using var htmlPage = browser.NewPage(uri);

// Render the source Web page to the temporary file:
htmlPage.SaveAsPdf(tmp);

// Copy the created PDF from the temp file to target stream:
using (var ts = File.OpenRead(tmp))
    ts.CopyTo(stream);

// Clean up:
File.Delete(tmp);

The snapshot of the resulting PDF document is depicted below:

HTML webpage to PDF document

Note: In order to render an HTML page to PDF document, the fonts used on that page should be already installed on your system.

Render HTML Content to PDF Document

You can add an HTML page or string to a PDF document using the DrawHtml method of GcPdfGraphicsExt class.

To add an HTML formatted string to a PDF document, follow the steps below:

  1. Create an instance of the GcPdfDocument class.

  2. Configure PDF settings using the HtmlToPdfFormat class.

  3. Add an HTML string to a PDF document using the DrawHtml method of GcPdfGraphicsExt class.

  4. Save the PDF file using the Save method of the GcPdfDocument class.

// HTML code that represents the content to render:
var html = "" +
    "" +
    "" +
    "" +
    "span.bold {" +
        "font-weight: bold;" +
    "}" +
    "p.round {" +
        "font: 36px arial, sans-serif;" +
        "color: DarkSlateBlue;" +
        "border: 4px solid SlateBlue;" +
        "border-radius: 16px;" +
        "padding: 3px 5px 3px 5px;" +
        "text-shadow: 3px 2px LightSkyBlue;" +
    "}" +
    "" +
    "" +
    "" +
    "Hello, World, from GcHtml!" +
    "" +
    "";

// Create a new PDF document, add a page, get graphics to draw on:
var doc = new GcPdfDocument();
var page = doc.NewPage();
var g = page.Graphics;

try
{
    // Create an instance of GcHtmlBrowser that is used to render HTML:
    var browserPath = BrowserFetcher.GetSystemChromePath();
    using var browser = new GcHtmlBrowser(browserPath);

    // Render HTML.
    var ok = g.DrawHtml(browser, html, 72, 72,
        new HtmlToPdfFormat(false) { MaxPageWidth = 6.5f, MaxPageHeight = 9f },
        out SizeF size);
}
catch (Exception ex)
{
    throw new Exception($"Error:\n{ex.Message}");
}
// Done:
doc.Save(stream);

The resulting image is shown below:

HTML Content to PDF Document

For more information on rendering HTML to PDF using GcPdf, see GcPdf sample browser.

Tips to Migrate from Obsolete GcHtmlRenderer Class

If your application uses obsolete GcHtmlRenderer class to convert the HTML pages or content to a pdf format, you can use following steps to quickly update to the new GcHtmlBrowser class which does not depend on a custom build of Chromium and does not require GPL or LGPL licenses.

  1. In Solution Explorer, go to Project > Dependencies > Packages and remove any references to

    • GrapeCity.Documents.Html.Windows.X64

    • GrapeCity.Documents.Html.Linux.X64

    • GrapeCity.Documents.Html.Mac.X64

  2. Check for licensing calls and if they exist, change them as follows:

    GcHtmlRenderer.SetGcPdfLicenseKey(key); -> GcHtmlBrowser.SetGcPdfLicenseKey(key); 
  3. In order to create and use an instance of GcHtmlBrowser, you require the path to a Chromium based browser on the current system. For instance, in case of Chrome browser:

    • You can get the path to an existing instance of Chrome installed on the current system.

      var path = BrowserFetcher.GetSystemChromePath();                                        
    • Or, you can download and install Chrome in a location of your choice.

      var tp = Path.GetTempPath();
      var bf = new BrowserFetcher() { DestinationFolder = Path.Combine(tp, ".gc-chromium") };
      var path = bf.GetDownloadedPath();                                        

    Note: We recommend using Chrome browser with GcHTMLBrowser class as Edge has some differences in the implementation of some DevTools features.

  4. Create an instance of GcHtmlBrowser. Note that RunWithNoSandbox option may be needed on some Linux systems.

    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        return new GcHtmlBrowser(path, new LaunchOptions { RunWithNoSandbox = true });
    else
        return new GcHtmlBrowser(path)
  5. In all calls to GcGraphics.DrawHtml() method, insert browser instance as the first parameter.

    g.DrawHtml(html, ...); -> g.DrawHtml(browser, html, ...);
  6. Look for instances of GcHtmlRenderer class which are rendering Uri such as

    using var re = new GcHtmlRenderer(uri);
    ...
    re.RenderToPdf(file, new PdfSettings() {…});

    and replace it with

    // Create an HtmlPage from the URI
    // (DefaultBackgroundColor and WindowSize options from Pdf/Jpeg/PngSettings
    // have moved to PageOptions, while some other options are now in LaunchOptions):
    using var htmlPage = browser.NewPage(uri, new PageOptions() { WindowSize = pixelSize;… });
    ...
    htmlPage.SaveAsPdf(file, new PdfOptions() {...});

    Note: Few methods and properties of JpegSettings and PngSettings classes have been moved to LaunchOptions and PageOptions classes.