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
Advanced examples
Template rendering examples
Express.js examples

Basic examples

Webpage to PDF file

var pdfcrowd = require("pdfcrowd");

// create the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// use predefined callback for saving to a file
var callbacks = pdfcrowd.saveToFile("example.pdf");

// set custom error callback
callbacks.error = function(errMessage, statusCode) {
    if(statusCode) {
        console.error("Pdfcrowd Error: " + statusCode + " - " + errMessage);
    } else {
        console.error("Pdfcrowd Error: " + errMessage);
    }
};

// run the conversion and write the result to a file
client.convertUrl("http://www.example.com", callbacks);

HTML file to PDF file

var pdfcrowd = require("pdfcrowd");

// create the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// use predefined callback for saving to a file
var callbacks = pdfcrowd.saveToFile("MyLayout.pdf");

// set custom error callback
callbacks.error = function(errMessage, statusCode) {
    if(statusCode) {
        console.error("Pdfcrowd Error: " + statusCode + " - " + errMessage);
    } else {
        console.error("Pdfcrowd Error: " + errMessage);
    }
};

// run the conversion and write the result to a file
client.convertFile("/path/to/MyLayout.html", callbacks);

HTML string to PDF file

var pdfcrowd = require("pdfcrowd");

// create the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// use predefined callback for saving to a file
var callbacks = pdfcrowd.saveToFile("HelloWorld.pdf");

// set custom error callback
callbacks.error = function(errMessage, statusCode) {
    if(statusCode) {
        console.error("Pdfcrowd Error: " + statusCode + " - " + errMessage);
    } else {
        console.error("Pdfcrowd Error: " + errMessage);
    }
};

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setDebugLog(true);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 of the debug log
        console.log("Debug log url: " + client.getDebugLogUrl());
        
        // print the number of conversion credits remaining in your account
        console.log("Remaining credit count: " + client.getRemainingCreditCount());
        
        // print the number of credits used for the conversion
        console.log("Consumed credit count: " + client.getConsumedCreditCount());
        
        // print the unique identifier for the conversion
        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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setEnablePdfForms(true);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setScaleFactor(300);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setElementToConvert("#main");
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setViewportWidth(992);
    client.setRenderingMode("viewport");
    client.setSmartScalingMode("viewport-fit");
    client.setNoMargins(true);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// 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) {
        if(statusCode) {
            console.error("Pdfcrowd Error: " + statusCode + " - " + errMessage);
        } else {
            console.error("Pdfcrowd Error: " + errMessage);
        }
    };

    // run the conversion and write the result into the output stream
    client.convertStream(inStream, callbacks);

});

// create 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setDataString(`{
            "name": "World",
            "product": "Pdfcrowd API"
        }`);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    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 write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setDataString(`name: World
product: Pdfcrowd API`);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// configure the conversion
try {
    client.setDataString(`name,product
World,Pdfcrowd API`);
} catch(why) {
    // report the error
    console.error("Pdfcrowd Error: " + why);
    process.exit(1);
}

// run the conversion and write 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 the API client instance
    var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

    // 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 the API client instance
    var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

    // 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 the API client instance
    var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

    // 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;