HTML to PDF / Node.js Examples
This page contains various examples of using the HTML to PDF API in Node.js. The examples are complete and fully functional. Read more about how to convert HTML to PDF in Node.js.
Basic examples
- Webpage to PDF file
- Webpage to PDF file via callback
- HTML file to PDF file
- HTML file to PDF file via callback
- HTML string to PDF file
- HTML string to PDF file via callback
- Get info about the current conversion
Advanced examples
- Customize the page size and the orientation
- Put the source URL in the header and the page number in the footer
- Create fillable PDF form
- Zoom the HTML document
- Set PDF metadata
- Create a Powerpoint like presentation from an HTML document
- Convert an HTML document section
- Inject an HTML code
- Convert a responsive web page as it appears on a large device
- Create an in-memory archive (ZIP) and convert it
- Renderer debugging - highlight HTML elements
- Renderer debugging - borders with spacing around HTML elements
Template rendering examples
- Create PDF from JSON data
- Create PDF from XML data
- Create PDF from YAML data
- Create PDF from CSV data
Express.js examples
Basic examples
Webpage to PDF file
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Specify the mapping of HTML content width to the PDF page width. // To fine-tune the layout, you can specify an exact viewport width, such as '960px'. client.setContentViewportWidth("balanced"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "example.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Webpage to PDF file via callback
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // use predefined callback for saving to a file var callbacks = pdfcrowd.saveToFile("example.pdf"); // set custom error callback callbacks.error = function(errMessage, statusCode) { // use predefined helper class for errors const error = new pdfcrowd.Pdfcrowd.Error(errMessage, statusCode); console.error("PDFCrowd Error: " + error); }; // Run the conversion and save the result to a file. client.convertUrl("http://www.example.com", callbacks);
HTML file to PDF file
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Specify the mapping of HTML content width to the PDF page width. // To fine-tune the layout, you can specify an exact viewport width, such as '960px'. client.setContentViewportWidth("balanced"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertFileToFile( "/path/to/MyLayout.html", "MyLayout.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
HTML file to PDF file via callback
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // use predefined callback for saving to a file var callbacks = pdfcrowd.saveToFile("MyLayout.pdf"); // set custom error callback callbacks.error = function(errMessage, statusCode) { // use predefined helper class for errors const error = new pdfcrowd.Pdfcrowd.Error(errMessage, statusCode); console.error("PDFCrowd Error: " + error); }; // Run the conversion and save the result to a file. client.convertFile("/path/to/MyLayout.html", callbacks);
HTML string to PDF file
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Specify the mapping of HTML content width to the PDF page width. // To fine-tune the layout, you can specify an exact viewport width, such as '960px'. client.setContentViewportWidth("balanced"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertStringToFile( "<html><body><h1>Hello World!</h1></body></html>", "HelloWorld.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
HTML string to PDF file via callback
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // use predefined callback for saving to a file var callbacks = pdfcrowd.saveToFile("HelloWorld.pdf"); // set custom error callback callbacks.error = function(errMessage, statusCode) { // use predefined helper class for errors const error = new pdfcrowd.Pdfcrowd.Error(errMessage, statusCode); console.error("PDFCrowd Error: " + error); }; // Run the conversion and save the result to a file. client.convertString("<html><body><h1>Hello World!</h1></body></html>", callbacks);
Get info about the current conversion
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Specify the mapping of HTML content width to the PDF page width. // To fine-tune the layout, you can specify an exact viewport width, such as '960px'. client.setDebugLog(true); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertFileToFile( "/path/to/MyLayout.html", "MyLayout.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); // print URL pointing to the debug log for this request. console.log("Debug log url: " + client.getDebugLogUrl()); // print number of conversion credits remaining in your account. console.log("Remaining credit count: " + client.getRemainingCreditCount()); // print number of credits consumed for this conversion. console.log("Consumed credit count: " + client.getConsumedCreditCount()); // print unique identifier assigned to this conversion job. console.log("Job id: " + client.getJobId()); // print total number of pages in the output document. console.log("Page count: " + client.getPageCount()); // print size of the output data in bytes. console.log("Output size: " + client.getOutputSize()); });
Advanced examples
Customize the page size and the orientation
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setPageSize("Letter"); client.setOrientation("landscape"); client.setNoMargins(true); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "letter_landscape.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Put the source URL in the header and the page number in the footer
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setHeaderHeight("15mm"); client.setFooterHeight("10mm"); client.setHeaderHtml("<a class='pdfcrowd-source-url' data-pdfcrowd-placement='href-and-content'></a>"); client.setFooterHtml("<center><span class='pdfcrowd-page-number'></span></center>"); client.setMarginTop("0"); client.setMarginBottom("0"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "header_footer.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Create fillable PDF form
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setEnablePdfForms(true); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertStringToFile( "<html><body>Enter name:<input type=text></body></html>", "form.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Zoom the HTML document
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setScaleFactor(300); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "zoom_300.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Set PDF metadata
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setAuthor("Pdfcrowd"); client.setTitle("Hello World"); client.setSubject("Demo"); client.setKeywords("Pdfcrowd,demo"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "with_metadata.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Create a Powerpoint like presentation from an HTML document
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setPageLayout("single-page"); client.setPageMode("full-screen"); client.setInitialZoomType("fit-page"); client.setOrientation("landscape"); client.setNoMargins(true); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "https://pdfcrowd.com/api/", "slide_show.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Convert an HTML document section
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setElementToConvert("#main"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "https://pdfcrowd.com/api/", "html_part.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Inject an HTML code
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. 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)"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "html_inject.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Convert a responsive web page as it appears on a large device
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setContentViewportWidth("large"); client.setNoMargins(true); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "https://getbootstrap.com/", "bootstrap.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Create an in-memory archive (ZIP) and convert it
var pdfcrowd = require("pdfcrowd"); var stream = require("stream"); var archiver = require("archiver"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // create in-memory write stream var memStream = new stream.Writable({encoding: "binary"}) memStream.buffer = new Buffer(""); memStream._write = function(chunk, encoding, callback) { if(!Buffer.isBuffer(chunk)) { chunk = new Buffer(chunk, encoding); } this.buffer = Buffer.concat([this.buffer, chunk]); callback(); }; memStream.on("finish", function() { // create input stream var inStream = new stream.Readable({encoding: "binary"}) inStream.push(memStream.buffer); inStream.push(null); // use predefined callback for saving to a file var callbacks = pdfcrowd.saveToFile("HelloFromZip.pdf"); // set custom error callback callbacks.error = function(errMessage, statusCode) { // use predefined helper class for errors const error = new pdfcrowd.Pdfcrowd.Error(errMessage, statusCode); console.error("PDFCrowd Error: " + error); }; // run the conversion and write the result to the output stream. client.convertStream(inStream, callbacks); }); // Create a ZIP archive. var archive = archiver("zip"); archive.on("error", function(err) { throw err; }); archive.pipe(memStream); // Add HTML content to the archive. archive.append(`<html> <head> <style> @font-face { font-family: 'OpenSans'; src: url(fonts/OpenSans.ttf) format('truetype'); } h1 { font-family: OpenSans; } </style> </head> <body> <h1>Hello World</h1> <img src='images/logo.png'> </body> </html>`, {name: 'index.html'}); // Add required local files to the archive. archive.file("/your-path-to/fonts/OpenSans.ttf", { name: "fonts/OpenSans.ttf" }); archive.file("/your-path-to/images/logo.png", { name: "images/logo.png" }); archive.finalize();
Renderer debugging - highlight HTML elements
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setCustomJavascript("libPdfcrowd.highlightHtmlElements({backgroundColor: 'rgba(255, 191, 0, 0.1)', borderColor:null})"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "highlight_background.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Renderer debugging - borders with spacing around HTML elements
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setCustomJavascript("libPdfcrowd.highlightHtmlElements({borderColor: 'orange', backgroundColor: null, padding: '4px', margin: '4px'})"); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertUrlToFile( "http://www.example.com", "highlight_borders.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Template rendering examples
Create PDF from JSON data
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setDataString(`{ "name": "World", "product": "Pdfcrowd API" }`); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertStringToFile( "Hello {{ name }} from {{ product }}", "output.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Create PDF from XML data
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setDataString(`<?xml version="1.0" encoding="UTF-8"?> <data> <name>World</name> <product>Pdfcrowd API</product> </data>`); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertStringToFile( "Hello {{ data.name }} from {{ data.product }}", "output.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Create PDF from YAML data
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setDataString(`name: World product: Pdfcrowd API`); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertStringToFile( "Hello {{ name }} from {{ product }}", "output.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Create PDF from CSV data
var pdfcrowd = require("pdfcrowd"); // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); try { // Configure the conversion. client.setDataString(`name,product World,Pdfcrowd API`); } catch(why) { // Report the error. console.error("PDFCrowd Error: " + why); process.exit(1); } // Run the conversion and save the result to a file. client.convertStringToFile( "Hello {{ name }} from {{ product }}", "output.pdf", function(err, fileName) { if (err) return console.error("PDFCrowd Error: " + err); console.log("Success: the file was created " + fileName); });
Express.js examples
Webpage to PDF in Express.js
"use strict"; const express = require("express"); const app = express(); const pdfcrowd = require("pdfcrowd"); // The recommended method is POST. app.post("/", (req, res) => { // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // configure the callback to send a file in the HTTP response var callbacks = pdfcrowd.sendGenericHttpResponse( res, "application/pdf", "example.pdf", "attachment"); // configure the callback to send an error in the HTTP response callbacks.error = function(errMessage, statusCode) { res.set('Content-Type', 'text/plain'); res.status(statusCode || 400); res.send(errMessage); } // Run the conversion. client.convertUrl("http://www.example.com", callbacks); }); module.exports = app;
HTML file to PDF in Express.js
"use strict"; const express = require("express"); const app = express(); const pdfcrowd = require("pdfcrowd"); // The recommended method is POST. app.post("/", (req, res) => { // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // configure the callback to send a file in the HTTP response var callbacks = pdfcrowd.sendGenericHttpResponse( res, "application/pdf", "MyLayout.pdf", "attachment"); // configure the callback to send an error in the HTTP response callbacks.error = function(errMessage, statusCode) { res.set('Content-Type', 'text/plain'); res.status(statusCode || 400); res.send(errMessage); } // Run the conversion. client.convertFile("/path/to/MyLayout.html", callbacks); }); module.exports = app;
HTML string to PDF in Express.js
"use strict"; const express = require("express"); const app = express(); const pdfcrowd = require("pdfcrowd"); // The recommended method is POST. app.post("/", (req, res) => { // Create an API client instance. var client = new pdfcrowd.HtmlToPdfClient("demo", "demo"); // configure the callback to send a file in the HTTP response var callbacks = pdfcrowd.sendGenericHttpResponse( res, "application/pdf", "HelloWorld.pdf", "attachment"); // configure the callback to send an error in the HTTP response callbacks.error = function(errMessage, statusCode) { res.set('Content-Type', 'text/plain'); res.status(statusCode || 400); res.send(errMessage); } // Run the conversion. client.convertString("<html><body><h1>Hello World!</h1></body></html>", callbacks); }); module.exports = app;