Execute Custom JavaScript
IronPDF for Python can inject and execute custom JavaScript against a page before it is rendered to PDF, giving you programmatic control over the HTML content at render time.
Getting Started
Assign a JavaScript string to RenderingOptions.Javascript on a ChromePdfRenderer instance. IronPDF will execute that script after the page has loaded and before the PDF is captured.
Understanding the Code
RenderingOptions.Javascript: A string containing JavaScript code that IronPDF injects and runs after the page finishes loading. In the example, this script selects all<h1>elements and sets their color to red usingquerySelectorAlland aforEachloop.RenderHtmlAsPdf(html): Renders the HTML with the injected JavaScript applied. The resulting PDF reflects the DOM state after the script has run.
Use Cases
Injecting custom JavaScript at render time is useful for:
- Hiding UI elements not relevant to a print view (navigation bars, sidebars, modals).
- Applying dynamic styles based on conditions evaluated at render time.
- Populating data into a page template before capturing it as a PDF.
- Triggering print-specific layout changes without modifying the original HTML source.






