Node.js HTML to PDF Code Examples
Complete Node.js examples for common HTML to PDF tasks. See the Node.js SDK guide for installation and result handling.
You can run the examples below with the displayed API credentials. Update the input URLs and filenames as needed. Each Node.js example can be copied and run independently.
Basic examples
Choose file, in-memory, or output-stream handling for the result. Stream examples use a file stream as their destination.
Convert a URL
Save to a file
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.convertUrlToFile( "https://example.com/", "example.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Keep in memory
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); const chunks = []; let failed = false; client.convertUrl("https://example.com/", { data: (stream) => stream.on("data", (chunk) => chunks.push(chunk)), error: (message, statusCode) => { failed = true; console.error(new pdfcrowd.Pdfcrowd.Error( message, statusCode).toString()); }, end: () => { if (failed) { return; } const pdf = Buffer.concat(chunks); // Buffer console.log("PDF ready:", pdf.length, "bytes"); } });
Write to a stream
const pdfcrowd = require('pdfcrowd'); const fs = require('node:fs'); const { pipeline } = require('node:stream'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); let output_stream; let failed = false; function fail(error) { if (failed) return; failed = true; console.error(error.toString()); process.exitCode = 1; if (output_stream) output_stream.destroy(); } try { client.setContentViewportWidth("balanced"); client.convertUrl("https://example.com/", { data: (stream) => { if (failed) { stream.destroy(); return; } output_stream = fs.createWriteStream("example.pdf"); pipeline(stream, output_stream, (error) => { if (error) { fail(error); return; } if (failed) return; console.log("Saved:", "example.pdf"); }); }, error: (message, statusCode) => fail(new pdfcrowd.Pdfcrowd.Error( message, statusCode)), end: () => { console.log("Conversion response ended."); }, }); } catch (error) { fail(error); }
Convert an HTML file
Upload an existing document.html file. For local images and stylesheets, see Local assets.
Save to a file
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.convertFileToFile("document.html", "document.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
Keep in memory
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); const chunks = []; let failed = false; client.convertFile("document.html", { data: (stream) => stream.on("data", (chunk) => chunks.push(chunk)), error: (message, statusCode) => { failed = true; console.error(new pdfcrowd.Pdfcrowd.Error( message, statusCode).toString()); }, end: () => { if (failed) { return; } const pdf = Buffer.concat(chunks); // Buffer console.log("PDF ready:", pdf.length, "bytes"); } });
Write to a stream
const pdfcrowd = require('pdfcrowd'); const fs = require('node:fs'); const { pipeline } = require('node:stream'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); let output_stream; let failed = false; function fail(error) { if (failed) return; failed = true; console.error(error.toString()); process.exitCode = 1; if (output_stream) output_stream.destroy(); } try { client.setContentViewportWidth("balanced"); client.convertFile("document.html", { data: (stream) => { if (failed) { stream.destroy(); return; } output_stream = fs.createWriteStream("document.pdf"); pipeline(stream, output_stream, (error) => { if (error) { fail(error); return; } if (failed) return; console.log("Saved:", "document.pdf"); }); }, error: (message, statusCode) => fail(new pdfcrowd.Pdfcrowd.Error( message, statusCode)), end: () => { console.log("Conversion response ended."); }, }); } catch (error) { fail(error); }
Send HTML content
These examples read HTML text from document.html. In an application, pass the HTML produced by your template renderer instead.
Save to a file
const pdfcrowd = require('pdfcrowd'); const fs = require('node:fs'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); const html = fs.readFileSync("document.html", 'utf8'); client.setContentViewportWidth("balanced"); client.convertStringToFile(html, "html.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
Keep in memory
const pdfcrowd = require('pdfcrowd'); const fs = require('node:fs'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); const html = fs.readFileSync("document.html", 'utf8'); client.setContentViewportWidth("balanced"); const chunks = []; let failed = false; client.convertString(html, { data: (stream) => stream.on("data", (chunk) => chunks.push(chunk)), error: (message, statusCode) => { failed = true; console.error(new pdfcrowd.Pdfcrowd.Error( message, statusCode).toString()); }, end: () => { if (failed) { return; } const pdf = Buffer.concat(chunks); // Buffer console.log("PDF ready:", pdf.length, "bytes"); } });
Write to a stream
const pdfcrowd = require('pdfcrowd'); const fs = require('node:fs'); const { pipeline } = require('node:stream'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); let output_stream; let failed = false; function fail(error) { if (failed) return; failed = true; console.error(error.toString()); process.exitCode = 1; if (output_stream) output_stream.destroy(); } try { const html = fs.readFileSync("document.html", 'utf8'); client.setContentViewportWidth("balanced"); client.convertString(html, { data: (stream) => { if (failed) { stream.destroy(); return; } output_stream = fs.createWriteStream("html.pdf"); pipeline(stream, output_stream, (error) => { if (error) { fail(error); return; } if (failed) return; console.log("Saved:", "html.pdf"); }); }, error: (message, statusCode) => fail(new pdfcrowd.Pdfcrowd.Error( message, statusCode)), end: () => { console.log("Conversion response ended."); }, }); } catch (error) { fail(error); }
Convert inline HTML
Define a small HTML document directly in your code.
const pdfcrowd = require("pdfcrowd"); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); const html = "<html><body><h1>Monthly Report</h1></body></html>"; client.setContentViewportWidth("balanced"); client.convertStringToFile(html, "report.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
Read from an input stream
Open document.html as a binary input stream and save the PDF to document.pdf.
const pdfcrowd = require('pdfcrowd'); const fs = require('node:fs'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); const input_stream = fs.createReadStream("document.html"); try { client.convertStreamToFile( input_stream, "document.pdf", (error, filePath) => { input_stream.destroy(); if (error) { console.error(error.toString()); process.exitCode = 1; return; } console.log("Saved:", filePath); } ); } catch (error) { input_stream.destroy(); throw error; }
Local assets
Include HTML and its local images, stylesheets, and scripts in a ZIP archive, keeping their relative paths.
Convert a prepared archive
Upload an existing document.zip. Select the main HTML file explicitly when the archive contains multiple documents.
Detect the main HTML file
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.convertFileToFile("document.zip", "output.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
Select index.html
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setZipMainFilename("index.html"); client.convertFileToFile("document.zip", "document.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
Convert a local directory
Create document.zip from the existing document directory, then convert it to PDF.
const AdmZip = require("adm-zip"); // npm install adm-zip const pdfcrowd = require("pdfcrowd"); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); const archive = new AdmZip(); archive.addLocalFolder("document"); archive.writeZip("document.zip"); client.setContentViewportWidth("balanced"); client.convertFileToFile("document.zip", "document.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
Create an archive in memory
Package the existing document directory in memory. Its index.html file can refer to other files in the directory by relative path.
const pdfcrowd = require('pdfcrowd'); const { Readable } = require('node:stream'); const AdmZip = require('adm-zip'); // npm install adm-zip const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setZipMainFilename("index.html"); const archive = new AdmZip(); archive.addLocalFolder("document"); const archive_bytes = archive.toBuffer(); // Buffer const input_stream = Readable.from([archive_bytes]); try { client.convertStreamToFile(input_stream, "document.pdf", (error, filePath) => { input_stream.destroy(); if (error) { console.error(error.toString()); process.exitCode = 1; return; } console.log("Saved:", filePath); }); } catch (error) { input_stream.destroy(); throw error; }
Page rendering
Set page size and margins
Use landscape Letter pages with half-inch margins.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setMarginBottom("0.5in"); client.setMarginLeft("0.5in"); client.setMarginRight("0.5in"); client.setMarginTop("0.5in"); client.setOrientation("landscape"); client.setPageSize("Letter"); client.convertUrlToFile( "https://example.com/", "page-layout.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Add a header and page numbers
Show the source URL in the header and “Page N of M” in the footer.
See the headers and footers guide for more layouts and placeholders.
Scale page content
Scale the HTML content to 300%.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setScaleFactor(300); client.convertUrlToFile( "https://example.com/", "zoom_300.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Choose a responsive layout
The browser viewport controls responsive breakpoints independently of the PDF paper size.
Large viewport
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("large"); client.setNoMargins(true); client.convertUrlToFile( "https://example.com/", "bootstrap.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Small viewport
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("small"); client.convertUrlToFile( "https://example.com/", "viewport_small.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Hide or restyle page elements
Replace the selectors with elements from your page.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setCustomCss(` /* Hide navigation, ads, and sidebar */ nav, .advertisement, .sidebar, footer { display: none !important; } /* Adjust layout for print */ .content { width: 100% !important; max-width: none !important; }`); client.convertUrlToFile( "https://example.com/", "custom_css.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Modify the page with JavaScript
Adjust the selectors and class names for your page.
Remove widgets and expand sections
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setCustomJavascript(` // Remove dynamic content before conversion document.querySelectorAll('.video-player, .chat-widget').forEach(el => { el.remove(); }); // Expand collapsed sections document.querySelectorAll('.collapsed').forEach(el => { el.classList.remove('collapsed'); });`); client.convertUrlToFile( "https://example.com/", "custom_js.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Add content to the page
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setCustomJavascript(` el = document.createElement('h2'); el.textContent = 'Hello from PDFCrowd API'; el.style.color = 'red'; el_before = document.getElementsByTagName('h1')[0]; el_before.parentNode.insertBefore(el, el_before.nextSibling);`); client.convertUrlToFile( "https://example.com/", "html_inject.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Convert a specific element
Convert only #main in an existing document.html file. Adjust the filename and selector for your document.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setElementToConvert("#main"); client.convertFileToFile( "document.html", "html_part.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Wait for a page element
Wait for #content-loaded to appear in an existing document.html file. Choose an element that appears when your content is ready.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setWaitForElement("#content-loaded"); client.convertFileToFile( "document.html", "wait_element.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Allow extra time for JavaScript
Add a delay of 2000 milliseconds. When the page has a reliable readiness marker, use Wait for a page element.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setJavascriptDelay(2000); client.convertUrlToFile( "https://example.com/", "with_delay.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Apply print stylesheets
Apply the page’s @media print rules. The page must provide print styles for this to change its appearance.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setUsePrintMedia(true); client.convertUrlToFile( "https://example.com/", "print_media.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Inspect element boundaries
Highlight element boxes to investigate spacing and layout.
Highlight backgrounds
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setCustomJavascript(` libPdfcrowd.highlightHtmlElements({ backgroundColor: 'rgba(255, 191, 0, 0.1)', borderColor: null });`); client.convertUrlToFile( "https://example.com/", "highlight_background.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Add borders and spacing
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setCustomJavascript(` libPdfcrowd.highlightHtmlElements({ borderColor: 'orange', backgroundColor: null, padding: '4px', margin: '4px' });`); client.convertUrlToFile( "https://example.com/", "highlight_borders.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
HTML and CSS
Add these fragments to HTML you control.
Remove or hide elements
<nav class="pdfcrowd-remove">This won't appear in the PDF</nav> <div class="pdfcrowd-hide">This is invisible but takes up space</div>
pdfcrowd-remove removes the element from the layout. pdfcrowd-hide preserves its space.
Control page breaks
<!-- Force a page break before the following section --> <div style="page-break-before: always"></div> <!-- Avoid breaking tables across pages --> <style> table, tr, td { page-break-inside: avoid; } </style>
Content taller than a page still needs to break.
Apply styles only during conversion
<style> /* These styles only apply during PDF conversion */ .pdfcrowd-body h1 { font-size: 48px; } .pdfcrowd-body footer { display: none; } .pdfcrowd-body .main-content { width: 100%; } </style>
The .pdfcrowd-body prefix limits these rules to conversion; it does not change the page in a visitor’s browser.
Templates
Render a template with JSON data
Upload existing template.html and data.json files. See the template rendering guide for template syntax, data mapping, and other supported data formats.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setDataFormat("json"); client.setDataFile("data.json"); client.convertFileToFile("template.html", "output.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
PDF features
Create a fillable PDF
Use an existing form.html file containing HTML form controls.
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setEnablePdfForms(true); client.convertFileToFile("form.html", "form.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); });
See fillable PDF forms for supported controls and attributes.
Set PDF metadata
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setAuthor("PDFCrowd"); client.setKeywords("PDFCrowd,demo"); client.setSubject("Demo"); client.setTitle("Hello World"); client.convertUrlToFile( "https://example.com/", "with_metadata.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
Set a presentation view
const pdfcrowd = require('pdfcrowd'); const client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setInitialZoomType("fit-page"); client.setNoMargins(true); client.setOrientation("landscape"); client.setPageLayout("single-page"); client.setPageMode("full-screen"); client.convertUrlToFile( "https://example.com/", "slide_show.pdf", (error, filePath) => { if (error) { console.error(error.toString()); return; } console.log("Saved:", filePath); } );
These settings request a full-screen initial view with landscape pages. The PDF viewer controls whether it honors those preferences.