Rendering Charts in PDFs

Along with powerful HTML-to-PDF conversion capabilities, IronPDF provides full support for JavaScript rendering - which includes support for canvas and chart rendering. This full support for JavaScript enables developers to create high-quality PDFs with fully rendered charts, including 3D charts and polygons.

Some supported charts include:

  • C3.js
  • D3.js
  • Highcharts

Steps for Rendering Charts in PDFs

  • var renderer = new ChromePdfRenderer();
  • renderer.RenderingOptions.EnableJavaScript = true;
  • renderer.RenderingOptions.WaitFor.JavaScript();
  • renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
  • var pdf = renderer.RenderHtmlAsPdf(htmlWithJs);

To start with, we first need to create the HTML content that will be used to create our PDF document. This HTML includes inline JavaScript to generate a bar chart using the C3 library. The setTimeout function ensures that after 1 second, window.ironpdf.notifyRender() is called, signaling IronPDF to proceed with rendering the page once the JavaScript has completed execution.

Now, we can look at how this is rendered into an easy-to-read PDF document. First, we create a new ChromePdfRenderer instance, which is used to access the powerful the powerful rendering engine IronPDF uses, and allows for advanced JavaScript to be rendered in the HTML page.

Next, we have three different options that are set using the RenderingOptions class. The first, EnableJavaScript = true, ensures that the JavaScript within our example HTML document is executed when rendering the HTML page. WaitFor.JavaScript() is used to pause the rendering process until all JavaScript has run, ensuring the chart is properly rendered. The third option, CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print, sets the CSS media type to print, optimizing styles for PDF rendering.

The next step is to finally render the HTML document we created earlier into a PDF file. This is done through the RenderHtmlAsPdf method, which takes the htmlWithJs variable, and turns the HTML and JavaScript into a new PDF document.

Finally, the PDF document can be saved using the SaveAs method. Now, you will have a new PDF document with a fully rendered chart created using HTML and JavaScript.

Click here to view the How-to Guide, including examples, sample code, and files >