Execute Custom JavaScript
With IronPDF, you can execute custom JavaScript to better customize your PDFs rendered from HTML content. With the ChromePdfRenderOptions.Javascript
property, you can make sure the JavaScript executes after the HTML content has loaded but before your PDF is rendered, allowing for dynamic content rendering and interactivity. IronPDF's ChromePdfRenderer class ensures you create high-quality PDF documents tailored to your needs without losing any of the original quality or interactivity.
Steps to Execute Custom JavaScript for your PDF Documents
- var renderOptions = new ChromePdfRenderOptions();
- renderOptions.Javascript = "document.querySelectorAll('h1').forEach(function(el){el.style.color='red';})";
- var renderer = new ChromePdfRenderer { RenderingOptions = renderOptions };
- var pdf = renderer.RenderHtmlAsPdf("<h1>Happy New Year!</h1>");
- pdf.SaveAs("executed_js.pdf");
Before we can begin rendering our custom HTML and JavaScript into PDFs, we must first create a new ChromePdfRenderer
instance. The ChromePdfRenderer class handles the rendering of HTML, CSS, and JavaScript content into PDF format, while maintaining a pixel-perfect quality. Then, using the Javascript
property of the ChromePdfRenderer class, we can create a custom JavaScript code that will execute as soon as the HTML content has loaded, this will ensure that the changes dictated by our JavaScript string are reflected in the final PDF document. In this case, we are selecting any h1
tags within the HTML content and changing their text color to red.
We then handle assigning our renderOptions
object to the ChromePdfRenderer RenderingOptions
property, which controls the rendering options for that specific instance of the ChromePdfRenderer. This means that when we use our instance of the ChromePdfRenderer class, we will be running our JavaScript before the PDF is rendered, ensuring the changes are made in the resulting PDF. Then, we render our HTML content using RenderHtmlAsPdf
and use the PdfDocument class to create a new PDF document from the rendered content which is stored in the variable pdf
.
Finally, we save the rendered PDF using the final line, SaveAs
, which will export the PDF to the specified filepath.
Click here to view the How-to-Guide, including examples, sample code and files >