JavaScript in HTML To PDF

IronPDF allows users to create PDF files from HTML content, but its not just pure HTML content that can be converted to PDF, it can also convert HTML with custom CSS and JavaScript. Using JavaScript within the HTML content, for example, allows assets such as images to be embedded directly within HTML string rather than loading them as external assets. All you need to achieve this is the ChromePdfRenderer class and its RenderingOptions property.

5 Steps to Rendering HTML with JavaScript to PDF in C#

  • const string htmlWithJavaScript = "...."
  • var renderer = new ChromePdfRenderer();
  • renderer.RenderingOptions.EnableJavaScript = true;
  • renderer.RenderingOptions.WaitFor.JavaScript();
  • var pdfJavaScript = renderer.RenderHtmlAsPdf(htmlWithJavaScript);

Within the string variable, we have created an HTML string that includes the JavaScript <script> tag, which will contain the JavaScript code that will be used to create our PDF. Using the script tag means we have indicated which section of the string is JavaScript, which will later be enabled using the RenderingOptions property. With this, you can embed images, maintain interactivity in the rendered PDF, and more.

With new ChromePdfRenderer();, we instantiate a new instance of the ChromePdfRenderer class, which controls the rendering of HTML content to PDF. With this class, you can be confident that your rendered PDF files will come out pixel-perfect, along with any custom JavaScript or CSS content maintained in the final outcome.

Next, make use of the RenderingOptions property within the ChromePdfRenderer class to enable the JavaScript to be executed before the new PDF is rendered. The RenderingOptions.WaitFor line ensures the program waits for the JavaScript to finish executing before continuing with the rendering process. The rendering will start once the JavaScript code executed the window.ironpdf.notifyRender() method. The RenderingOptions property is assigned to the ChromePdfRenderer instance we created, so that the options will be used for any PDF created with this renderer.

The renderer.RenderHtmlAsPdf(...) method handles the actual rendering of the PDF document. By passing the HTML string with the JavaScript to this method, we can render it as a high-quality PDF containing all of the HTML and JavaScript items. This is saved to a new PdfDocument object which will store the newly rendered PDF, which in this case is called pdfJavaScript. Finally, we can save this new PDF using the SaveAs method.

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