Document Solutions for Imaging
In This Topic
    Render HTML to Image
    In This Topic

    DsImaging library along with DsHtml library lets you easily render HTML content to Images. When you browse through the content on a website, you may want to capture images to incorporate them into a professional presentation. Sometimes, one may also want to take the snapshot of online pricing details. With a utility library like DsHtml,the user can conveniently render HTML content to high resolution images. With DsHtml, you can convert webpages, HTML strings or even URIs to different image formats (JPEG, PNG, BMP, TIFF, GIF and WebP).

    DsHtml is based on the industry standard Chrome web browser engine working in headless mode, offering advantage of rendering HTML to image 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

    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.Imaging under the Browse tab and click Install.
    4. Similarly, install DS.Documents.Html package.
      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.
      C#
      Copy Code
      using GrapeCity.Documents.Html;
      using GrapeCity.Documents.Pdf;
      using GrapeCity.Documents.Drawing;
      
    6. Apply DsImaging license to GcHtmlBrowser class of DsHtml library to convert HTML to image. Without proper license, the count is limited to only 5 image 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);
        re.ApplyGcImagingLicenseKey("key");

      • To license all the instances
        GcHtmlBrowser.SetGcImagingLicenseKey("key");
    7. Write the sample code.

    Render HTML Webpage as Image

    1. Get the URI of the HTML webpage you wish to render.
    2. Configure image settings using the PageOptions class.
    3. Convert the HTML page to JPEG, PNG, or WebP image using the SaveAsPng, SaveAsJpeg or SaveAsWebP methods of the HtmlPage class.
      C#
      Copy Code
      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");             
      

    The resulting image is shown below:

    Webpage being rendered as image in GcImaging

    Note:

    • In order to render an HTML page to image, the fonts used on that page should be already installed on your system.
    • It is important to dispose every instance of the GcHtmlBrowser class after use.

    Render HTML Markup as a Bitmap and Save as Image

    1. Get the HTML string or mark up that you wish to render.
    2. Store the HTML markup on a new page of the browser instance.
    3. Configure image settings using the PageOptions class.
    4. Create a new instance of GcBitmap and apply any transformations you need.
    5. Use the SaveAsTiff method to save the image in TIFF format.
      Similarly, you can use other SaveAs methods of GcBitmap class to save HTML markup in other image formats.  
      C#
      Copy Code
      using GrapeCity.Documents.Imaging;
      using GrapeCity.Documents.Html;
      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");
      

    The resulting image is shown below:

     

    Draw HTML String or Page on GcGraphics at Specified Position

    The user can also render HTML content to image using the DrawHtml method of GcBitmapGraphicsExt class. The DrawHtml method allows to convert an HTML text or page into an image. It also allows to insert HTML fragments in images along with other content. Moreover, the DrawHtml method has two overloads. The GcBitmapGraphics.DrawHtml (string html, float x, float y, HtmlToImageFormat format, out SizeF size) can be used to draw an HTML text on GcBitmapGraphics at a specified position, while the GcBitmapGraphics.DrawHtml (Uri htmlUri, float x, float y, HtmlToImageFormat format, out SizeF size) can be used to draw an HTML page specified by an URI on GcBitmapGraphics at a specified position.

    To render HTML string or page on GcBitmapGraphics at specified position, follow the steps below:

    1. Create an instance of GcBitmap class.
    2. Configure the image settings using the HtmlToImageFormat class.
    3. Save the HTML page or string on GcBitmapGraphics using the DrawHtmlextension method of GcBitmapGraphicsExt class.
    4. Call the SaveAsJpeg, SaveAsPng, SaveAsGif, SaveAsBmp and SaveAsTiff methods of GcBitmap class.
      C#
      Copy Code
      //Create an instance of GcBitmap class
      var bmp = new GcBitmap(1000, 1000, true, 96, 96);
      
      //Configure image settings
      HtmlToImageFormat htmlToImage = new HtmlToImageFormat(true)
      { WindowSize = new Size(500, 500) };
      
      htmlToImage.DefaultBackgroundColor = Color.White;
      
      //Draw HTML Page on GcBitmapGraphics
      using (var g = bmp.CreateGraphics(Color.LightBlue))
      {
          SizeF addSize = new SizeF();
      
          // Create an instance of GcHtmlBrowser that is used to render HTML:
          var browserPath = BrowserFetcher.GetSystemChromePath();
          var browser = new GcHtmlBrowser(browserPath);
      
          g.DrawHtml(browser, new Uri("https://www.apple.com/in/"), 10, 10, htmlToImage, out addSize);
          bmp.SaveAsJpeg("DrawHtml.jpeg");
      }
      

    The resulting image is shown below:

    Convert HTML page of Apple website to an image using GcImaging

    For more information about rendering HTML to Image using DsImaging, see DsImaging demo.

    Tips to Migrate from Obsolete GcHtmlRenderer Class

    If your application uses obsolete GcHtmlRenderer class to convert the HTML pages or content to an image 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:
      C#
      Copy Code
      GcHtmlRenderer.SetGcImagingLicenseKey(key); -> GcHtmlBrowser.SetGcImagingLicenseKey(key);
      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.
        C#
        Copy Code
        var path = BrowserFetcher.GetSystemChromePath();                                        
        
      • Or, you can download and install Chrome in a location of your choice.
        C#
        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.
      C#
      Copy Code
      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.
      C#
      Copy Code
      g.DrawHtml(html, ...); -> g.DrawHtml(browser, html, ...);
      
    6. Look for instances of GcHtmlRenderer class which are rendering Uri such as
      C#
      Copy Code
      using var re = new GcHtmlRenderer(uri);
      ...
      re.RenderToJpeg(file, new JpegSettings() {...});
      re.RenderToPng(file, new PngSettings() {...});
      
      and replace them with
      C#
      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.SaveAsJpeg(file, new JpegOptions() {...});
      htmlPage.SaveAsPng(file, new PngOptions() {...});
      
      Note: Few methods and properties of JpegSettings and PngSettings classes have been moved to LaunchOptions and PageOptions classes.