Blog

Back to blog posts

Convert HTML to PDF with javascript and AngularJS

Published Jun 13, 2019

Intro

In some cases you may need to convert HTML to PDF from your client side application. Rendering a high quality PDF is not obvious and doing it purely from javascript isn’t feasible either. You need to be able to use a browser-based PDF engine like wkhtmltopdf or Headless Chrome. If you’re looking to generate PDF files with either of those engines straight from your AngularJs code, you’ve come to the right place.

Convert HTML to PDF with AngularJs

The first step is to grab an API key from https://portal.api2pdf.com. It only takes a minute. Once you have your API key, analyze the code below. This is a very simple AngularJs controller that has a function printToPdf(). This function sets your API key (which you should replace with the one you just acquired) and makes a POST call to the Api2Pdf REST API with the HTML specified. The response includes the payload and a URL to the generated PDF. It’s literally that simple.

 

function HtmlToPdfController($scope, $http) {
$scope.printToPdf = function () {
$http.defaults.headers.common.Authorization = 'YOUR-API-KEY'; //replace with our API key from portal.api2pdf.com
var endpoint = "https://v2018.api2pdf.com/chrome/html"
var payload = {
html: "<p>Hello from AngularJS</p>", //set your HTML here!
inlinePdf: true
}
$http.post(endpoint, payload).then(
function(response) {
console.log(response) //your PDF is in this response. Do something with it!
},
function(error) {
});
};
}

 

Below is a link to a JS Fiddle that you can modify to include your own API key and play with.

Hope that helps!