How to convert an HTML String to PDF in Node.JS

Today we are going to use Node.JS to full render a website from HTML and then save it as a PDF file. Our solution has the flexibility to support many advanced features, such as CSS, HTML5, and Javascript. To complete our task in a timely manner, we will forgo manual coding in favor of bringing in an API-based method. Here’s how to do it.

First, install our API client.

npm install cloudmersive-convert-api-client --save

Second, call our function:

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;// Configure API key authorization: Apikeyvar Apikey = defaultClient.authentications['Apikey'];Apikey.apiKey = 'YOUR API KEY';// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.apiKeyPrefix = 'Token';var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parametersvar callback = function(error, data, response) {if (error) {console.error(error);} else {console.log('API called successfully. Returned data: ' + data);}};apiInstance.convertWebHtmlToPdf(input, callback);

Third, input your HTML string. After that, you will be returned your PDF capture of the website. It’s as easy as that!

Image for post

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store