Blog
Convert HTML to PDF with client side javascript and jquery
It is rare, but there may be some situations where the only option you have to convert HTML to PDF or a URL to PDF is from the client-side javascript. Now there are some existing options such as jsPDF, but they are severely limited. An ideal situation would be to have access to wkhtmltopdf or Headless Chrome on the client side.
Api2Pdf is an HTML to PDF API that generates PDFs on AWS Lambda for extreme scalability. It offers both wkhtmltopdf and Headless Chrome as options. In most cases, you will want to call this API via server side code, but the following code will show an example below of how to interact with this API via client side javascript with jQuery.
Convert HTML to PDF with Client Side Javascript / jQuery
The first step is to acquire an API key from portal.api2pdf.com. Once you grab your API key, you are almost set. The following jQuery ajax call can be used to call the API. Your only task is to replace the apikey variable ‘YOUR-API-KEY’ with the apikey you pulled from portal.api2pdf.com.
function printHtmlToPdf(html) { | |
var endpoint = 'https://v2018.api2pdf.com/chrome/html'; | |
var apikey = 'YOUR-API-KEY'; //replace this with your own from portal.api2pdf.com | |
var payload = { | |
"html": html, | |
"inlinePdf": false | |
}; | |
$.ajax({ | |
url: endpoint, | |
method: "POST", | |
dataType: "json", | |
crossDomain: true, | |
contentType: "application/json; charset=utf-8", | |
data: JSON.stringify(payload), | |
cache: false, | |
beforeSend: function (xhr) { | |
/* Authorization header */ | |
xhr.setRequestHeader("Authorization", apikey); | |
}, | |
success: function (data) { | |
console.log(data.pdf); //this is the url to the pdf, do something with it | |
}, | |
error: function (jqXHR, textStatus, errorThrown) { | |
} | |
}); | |
} |
You can call this function with your raw HTML. Feel free to modify this function to call a URL and use the URL endpoint instead, or convert word files to PDFs with our LibreOffice endpoint. See our full documentation for the REST API here.
Demo
View a full working source code of HTML here: https://gist.github.com/apexdodge/556badd8b4fbf71d3cc566800b52b012
View a JS fiddle demo version of the above code here: https://jsfiddle.net/apexdodge/xpvt214o/723551/
Just be sure to replace the apikey with your own in both the HTML and JS Fiddle examples.
Disclaimer
The reason most people use Api2Pdf from the server side is so that they do not expose their Api2Pdf apikey. If someone has your api key, they can use the key to generate their own PDFs with your own account. Therefore we always recommend doing server-side generation, leaving this client-side approach as a last resort, and only if you really trust your user base.