Document Solutions for PDF
In This Topic
    Render HTML to PDF
    In This Topic

    DsPdf library along with DsHtml library, lets you easily render HTML content to PDF document. With a utility library like DsHtml, 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.

    DsHtml 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 DS.Documents.Html package contains the following namespaces:

    Install DsHtml Package

    Refer the steps below to install DsHtml 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 DS.Documents.Pdf under the Browse tab and click Install.

    4. Similarly, install DS.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 DsHtml package has been installed successfully, add the namespace in Program.cs file.

      Copy Code
      using GrapeCity.Documents.Html;
      using GrapeCity.Documents.Pdf;
      using GrapeCity.Documents.Drawing;
    6. Apply DsPdf license to GcHtmlBrowser class of DsHtml 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 = "<html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
        var re = new GcHtmlBrowser(html);

      • To license all the instances
    7. Write the sample code.

    Render HTML Webpage to PDF Document

    DsHtml can render HTML webpage to PDF document. DsPdf 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.
    Copy Code
    // 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("");
    // 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:
    // Copy the created PDF from the temp file to target stream:
    using (var ts = File.OpenRead(tmp))
    // Clean up:

    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.
    Copy Code
    // HTML code that represents the content to render:
    var html = "<!DOCTYPE html>" +
        "<html>" +
        "<head>" +
        "<style>" +
        "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;" +
        "}" +
        "</style>" +
        "</head>" +
        "<body>" +
        "<p class='round'>Hello, World, from <span class='bold'>DsHtml</span>!</p>" +
        "</body>" +
    // 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;
        // 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:

    Back to Top

    The resulting image is shown below:
    HTML Content to PDF Document

    For more information on rendering HTML to PDF using DsPdf, see DsPdf 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:
      Copy Code
      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.
        Copy Code
        var path = BrowserFetcher.GetSystemChromePath();                                        
      • Or, you can download and install Chrome in a location of your choice.
        Copy Code
        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.
      Copy Code
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
          return new GcHtmlBrowser(path, new LaunchOptions { RunWithNoSandbox = true });
          return new GcHtmlBrowser(path)
    5. In all calls to GcGraphics.DrawHtml() method, insert browser instance as the first parameter.
      Copy Code
      g.DrawHtml(html, ...); -> g.DrawHtml(browser, html, ...);
    6. Look for instances of GcHtmlRenderer class which are rendering Uri such as
      Copy Code
      using var re = new GcHtmlRenderer(uri);
      re.RenderToPdf(file, new PdfSettings() {…});
      and replace it with
      Copy Code
      // 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.