How to use JavaScript with HTML to PDF in C#
IronPDF enables JavaScript execution during HTML to PDF conversion using its Chromium rendering engine. Convert dynamic web content including JavaScript and jQuery to PDF documents in .NET C# applications with support for interactive elements and dynamic rendering.
JavaScript is a high-level, versatile programming language used in web development. It enables interactive and dynamic features on websites. jQuery is a JavaScript library that simplifies common tasks such as DOM manipulation, event handling, and AJAX requests.
IronPDF supports JavaScript through the Chromium rendering engine. This article demonstrates how to use JavaScript and jQuery in HTML to PDF conversion in .NET C# projects. IronPDF provides a free trial of IronPDF for testing. For debugging HTML before conversion, see our guide on debugging HTML with Chrome.
Quickstart: Convert HTML with JavaScript to PDF in .NET
Convert HTML pages that include JavaScript to PDF using IronPDF in .NET projects. With Chromium rendering engine support, all JavaScript elements are processed accurately. This example shows how to render a web page to PDF with dynamic content. A single method call renders and saves your PDF document.
Get started making PDFs with NuGet now:
Install IronPDF with NuGet Package Manager
Copy and run this code snippet.
new IronPdf.ChromePdfRenderer { RenderingOptions = { EnableJavaScript = true, WaitFor = IronPdf.Rendering.WaitFor.JavaScript() } } .RenderHtmlAsPdf("<h1>Start</h1><script>document.write('<h1>Generated by JS</h1>');window.ironpdf.notifyRender();</script>") .SaveAs("js‑rendered.pdf");Deploy to test on your live environment
How Do I Set Up the Basic Workflow?
- Download the C# library: Convert HTML to PDF
- Enable JavaScript execution: Use the
EnableJavaScriptproperty - Render from HTML to PDF: Ensure JavaScript code is supported
- Execute custom JavaScript: Within your .NET C# code
- Capture console messages: Using a JavaScript message listener
How Do I Render JavaScript When Converting HTML to PDF?
JavaScript in HTML is supported when converting to PDF. Since rendering happens immediately, JavaScript might not execute properly. Configure the WaitFor class in rendering options to allow JavaScript execution time. The following code uses WaitFor.JavaScript with a 500 ms maximum wait time. For details on wait times and rendering delays, see our guide on using WaitFor to delay PDF rendering.
:path=/static-assets/pdf/content-code-examples/how-to/javascript-to-pdf-render-javascript.csusing IronPdf;
string htmlWithJavaScript = @"<h1>This is HTML</h1>
<script>
document.write('<h1>This is JavaScript</h1>');
window.ironpdf.notifyRender();
</script>";
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Enable JavaScript
renderer.RenderingOptions.EnableJavaScript = true;
// Set waitFor for JavaScript
renderer.RenderingOptions.WaitFor.JavaScript(500);
// Render HTML contains JavaScript
var pdfJavaScript = renderer.RenderHtmlAsPdf(htmlWithJavaScript);
// Export PDF
pdfJavaScript.SaveAs("javascriptHtml.pdf");Imports IronPdf
Private htmlWithJavaScript As String = "<h1>This is HTML</h1>
<script>
document.write('<h1>This is JavaScript</h1>');
window.ironpdf.notifyRender();
</script>"
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Enable JavaScript
renderer.RenderingOptions.EnableJavaScript = True
' Set waitFor for JavaScript
renderer.RenderingOptions.WaitFor.JavaScript(500)
' Render HTML contains JavaScript
Dim pdfJavaScript = renderer.RenderHtmlAsPdf(htmlWithJavaScript)
' Export PDF
pdfJavaScript.SaveAs("javascriptHtml.pdf")Why Does WaitFor Matter for JavaScript Execution?
Complex JavaScript frameworks may require memory allocation adjustments due to limited JavaScript execution memory in .NET. WaitFor provides options to ensure complete JavaScript execution before PDF generation. Wait for JavaScript execution, network idle states, HTML elements, or custom render delays. Learn about available rendering options to optimize PDF generation.
When Should I Use the notifyRender Method?
The window.ironpdf.notifyRender() method signals that JavaScript execution is complete, ensuring proper rendering timing for dynamic content. Use it for asynchronous operations or animations that must complete before PDF generation. The method works with WaitFor.JavaScript settings for precise rendering control.
What Are Common JavaScript Rendering Issues?
Complex frameworks may need additional wait time or memory allocation. Common issues include:
- Asynchronous data not loading before render
- CSS animations captured mid-transition
- JavaScript errors preventing rendering
- Memory constraints with heavy frameworks
For troubleshooting, enable custom logging to capture rendering process details.
How Can I Execute Custom JavaScript Before PDF Rendering?
Use the JavaScript property in rendering options to execute custom JavaScript before rendering. This helps when rendering URLs where JavaScript injection isn't possible. Assign JavaScript code to the rendering options' JavaScript property. Combine with async PDF generation for processing multiple documents.
:path=/static-assets/pdf/content-code-examples/how-to/javascript-to-pdf-execute-javascript.csusing IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// JavaScript code
renderer.RenderingOptions.Javascript = @"
document.querySelectorAll('h1').forEach(function(el){
el.style.color='red';
})";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Happy New Year!</h1>");
pdf.SaveAs("executed_js.pdf");Imports IronPdf
Private renderer As New ChromePdfRenderer()
' JavaScript code
renderer.RenderingOptions.Javascript = "
document.querySelectorAll('h1').forEach(function(el){
el.style.color='red';
})"
' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Happy New Year!</h1>")
pdf.SaveAs("executed_js.pdf")When Should I Use Custom JavaScript Injection?
Custom JavaScript injection works when rendering URLs where source HTML modification isn't possible. Common uses:
- Modifying third-party pages before conversion
- Adding dynamic watermarks or headers
- Hiding or showing elements conditionally
- Adjusting styles for print layouts
- Extracting and reorganizing content
What Types of DOM Manipulation Can I Perform?
Modify styles, add elements, change content, or perform standard DOM operations before rendering. Examples:
- Change CSS properties for print formatting
- Remove navigation elements or ads
- Add page numbers or custom headers
- Restructure content layout
- Inject additional data or metadata
How Do I Capture JavaScript Console Messages During PDF Generation?
IronPDF captures JavaScript console messages including error logs and custom messages. Use the JavascriptMessageListener property to capture messages. This example shows logging custom text and errors.
:path=/static-assets/pdf/content-code-examples/how-to/javascript-to-pdf-message-listener.csusing IronPdf;
using System;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Method callback to be invoked whenever a browser console message becomes available:
renderer.RenderingOptions.JavascriptMessageListener = message => Console.WriteLine($"JS: {message}");
// Log 'foo' to the console
renderer.RenderingOptions.Javascript = "console.log('foo');";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1> Hello World </h1>");
//--------------------------------------------------//
// Error will be logged
// message => Uncaught TypeError: Cannot read properties of null (reading 'style')
renderer.RenderingOptions.Javascript = "document.querySelector('non-existent').style.color='foo';";
// Render HTML to PDF
PdfDocument pdf2 = renderer.RenderHtmlAsPdf("<h1> Hello World </h1>");Imports IronPdf
Imports System
Private renderer As New ChromePdfRenderer()
' Method callback to be invoked whenever a browser console message becomes available:
renderer.RenderingOptions.JavascriptMessageListener = Sub(message) Console.WriteLine($"JS: {message}")
' Log 'foo' to the console
renderer.RenderingOptions.Javascript = "console.log('foo');"
' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1> Hello World </h1>")
'--------------------------------------------------//
' Error will be logged
' message => Uncaught TypeError: Cannot read properties of null (reading 'style')
renderer.RenderingOptions.Javascript = "document.querySelector('non-existent').style.color='foo';"
' Render HTML to PDF
Dim pdf2 As PdfDocument = renderer.RenderHtmlAsPdf("<h1> Hello World </h1>")
Why Should I Monitor JavaScript Console Messages?
Console monitoring helps debug JavaScript errors and track execution during PDF generation. Essential for:
- Identifying JavaScript errors preventing rendering
- Tracking complex JavaScript operation progress
- Debugging asynchronous code timing issues
- Validating custom JavaScript execution
- Collecting JavaScript performance metrics
What Types of Messages Can Be Captured?
The listener captures custom console.log messages and JavaScript errors including:
- Console outputs: log(), info(), warn(), error()
- Uncaught exceptions and runtime errors
- Network errors from failed resources
- Browser engine deprecation warnings
- Custom debugging information
How Do I Create Charts with JavaScript Libraries Like D3.js?
D3.js works well with IronPDF for creating charts or images. D3.js (Data-Driven Documents) is a JavaScript library for dynamic, interactive data visualizations using SVG in HTML5 and CSS3. See our guide on rendering charts in PDFs for more charting library examples.
To create a D3.js chart and convert it to PDF:
- Create a renderer object
- Set JavaScript and CSS properties
- Use
RenderHTMLFileAsPdfto read HTML - Save as PDF
:path=/static-assets/pdf/content-code-examples/how-to/javascript-to-pdf-render-chart.csusing IronPdf;
string html = @"
<!DOCTYPE html>
<html>
<head>
<meta charset=""utf-8"" />
<title>C3 Bar Chart</title>
</head>
<body>
<div id=""chart"" style=""width: 950px;""></div>
<script src=""https://d3js.org/d3.v4.js""></script>
<!-- Load c3.css -->
<link href=""https://cdnjs.cloudflare.com/ajax/libs/c3/0.5.4/c3.css"" rel=""stylesheet"">
<!-- Load d3.js and c3.js -->
<script src=""https://cdnjs.cloudflare.com/ajax/libs/c3/0.5.4/c3.js""></script>
<script>
Function.prototype.bind = Function.prototype.bind || function (thisp) {
var fn = this;
return function () {
return fn.apply(thisp, arguments);
};
};
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]]
}
});
</script>
</body>
</html>
";
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Enable JavaScript
renderer.RenderingOptions.EnableJavaScript = true;
// Set waitFor for JavaScript
renderer.RenderingOptions.WaitFor.JavaScript(500);
// Render HTML contains JavaScript
var pdfJavaScript = renderer.RenderHtmlAsPdf(html);
// Export PDF
pdfJavaScript.SaveAs("renderChart.pdf");Imports IronPdf
Private html As String = "
<!DOCTYPE html>
<html>
<head>
<meta charset=""utf-8"" />
<title>C3 Bar Chart</title>
</head>
<body>
<div id=""chart"" style=""width: 950px;""></div>
<script src=""https://d3js.org/d3.v4.js""></script>
<!-- Load c3.css -->
<link href=""https://cdnjs.cloudflare.com/ajax/libs/c3/0.5.4/c3.css"" rel=""stylesheet"">
<!-- Load d3.js and c3.js -->
<script src=""https://cdnjs.cloudflare.com/ajax/libs/c3/0.5.4/c3.js""></script>
<script>
Function.prototype.bind = Function.prototype.bind || function (thisp) {
var fn = this;
return function () {
return fn.apply(thisp, arguments);
};
};
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]]
}
});
</script>
</body>
</html>
"
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Enable JavaScript
renderer.RenderingOptions.EnableJavaScript = True
' Set waitFor for JavaScript
renderer.RenderingOptions.WaitFor.JavaScript(500)
' Render HTML contains JavaScript
Dim pdfJavaScript = renderer.RenderHtmlAsPdf(html)
' Export PDF
pdfJavaScript.SaveAs("renderChart.pdf")What Chart Libraries Work Best with IronPDF?
JavaScript charting libraries compatible with IronPDF:
- Chart.js: Lightweight for basic charts
- Highcharts: Professional charts with customization
- D3.js: Maximum flexibility for visualizations
- C3.js: D3-based reusable charts
- ApexCharts: Modern charts with performance
Success requires chart rendering completion before PDF generation using appropriate wait strategies.
When Should I Adjust Wait Times for Chart Rendering?
Complex charts with animations or large datasets need longer wait times. Consider:
- Data volume affects processing time
- Animation duration must complete
- Network requests for async data
- Chart complexity increases processing
How Can I Troubleshoot Chart Rendering Issues?
See 'How to Use the WaitFor Class to Delay C# PDF Rendering' for more WaitFor options. Troubleshooting steps:
- Increase JavaScript wait time
- Use
WaitFor.NetworkIdle()for async loading - Disable animations for PDF output
- Check console for JavaScript errors
- Test HTML in browser first
How Do I Convert AngularJS Applications to PDF?
AngularJS is a JavaScript-based open-source front-end framework. It simplifies single-page application development using client-side MVC and MVVM architectures. See our Angular to PDF code example for details.
For compatibility, use server-side rendering (SSR) with Angular Universal. Single-page applications (SPAs) need special handling due to dynamic content generation after initial load.
Why Is Server-Side Rendering Important for Angular PDFs?
Client-side Angular may not render properly without SSR due to browser JavaScript dependency. Challenges:
- Minimal initial HTML with dynamic content
- Client-side routing not in static HTML
- Data binding after page load
- API calls incomplete before PDF generation
What Are the Limitations with Client-Side Angular?
Dynamic content after initial load may not capture without proper wait configuration. Limitations:
- Asynchronously loaded components
- Lazy-loaded modules and routes
- Animations and transitions
- Dynamic forms and interactions
- Real-time data updates
Use longer wait times or implement window.ironpdf.notifyRender() in your Angular application.
How Does Server-Side Rendering Work with Angular Universal?
What's the Difference Between Angular and Angular Universal?
Angular runs client-side in the browser, rendering pages in the DOM based on user actions. Angular Universal runs server-side, generating static pages bootstrapped on the client. This improves loading and allows layout viewing before full interactivity.
PDF generation differences:
- Angular: Requires JavaScript execution
- Angular Universal: Provides pre-rendered HTML
- Performance: Universal renders faster
- Reliability: Universal ensures content availability
When Should I Choose Angular Universal for PDF Generation?
Use Angular Universal for guaranteed dynamic content rendering without client-side JavaScript dependency. Ideal for:
- Reports with API data
- Documents needing consistent formatting
- High-volume PDF generation
- Complex Angular applications
- JavaScript execution timeout concerns
Angular Universal ensures server-side rendering before IronPDF conversion, eliminating timing issues and improving reliability.
Frequently Asked Questions
How do I enable JavaScript when converting HTML to PDF in C#?
To enable JavaScript in IronPDF, set the EnableJavaScript property to true in the rendering options: new ChromePdfRenderer { RenderingOptions = { EnableJavaScript = true } }. This allows IronPDF's Chromium engine to execute JavaScript during the conversion process.
What JavaScript libraries are supported for PDF conversion?
IronPDF supports all JavaScript libraries including jQuery, React, Vue.js, and Angular through its Chromium rendering engine. The library can process DOM manipulation, AJAX requests, and dynamic content generation just like a modern web browser would.
How do I handle JavaScript execution timing in PDF generation?
Use the WaitFor class in IronPDF's rendering options to control JavaScript execution timing. You can use WaitFor.JavaScript() with a maximum wait time (e.g., 500ms) to ensure JavaScript completes before PDF generation: WaitFor = IronPdf.Rendering.WaitFor.JavaScript(500).
Can I execute custom JavaScript code during HTML to PDF conversion?
Yes, IronPDF allows you to execute custom JavaScript code within your .NET C# application during the conversion process. You can inject JavaScript directly into the HTML string or use the rendering options to run custom scripts.
How do I capture JavaScript console messages during PDF rendering?
IronPDF provides a JavaScript message listener feature that allows you to capture console.log messages and other JavaScript output during the PDF rendering process. This is useful for debugging JavaScript execution.
What rendering engine does the library use for JavaScript support?
IronPDF uses the Chromium rendering engine, the same engine that powers Google Chrome. This ensures full JavaScript compatibility and accurate rendering of modern web technologies in your PDF documents.
Is there a free trial available for testing JavaScript to PDF conversion?
Yes, IronPDF offers a free trial that includes full JavaScript support. You can test all features including JavaScript execution, jQuery rendering, and dynamic content generation before purchasing a license.






