Blog

Back to blog posts

Convert HTML to PDF with javascript and VueJs

Published Jun 12, 2019

Intro

VueJs is a popular client side javascript framework. It has risen in prominence as an alternative to juggernauts like ReactJs and Angular. Part of its allure comes from its simplicity and lower barrier to entry. While building a VueJs application, you may find yourself in need of generating PDFs. This can push you down a rabbit hole. In this article we will demonstrate how you can start converting HTML to PDF files from VueJs in minutes.

Convert HTML to PDF with VueJs

Using Api2Pdf’s REST API, you can quickly send HTML to convert to a PDF. The first thing to do is grab an API key from portal.api2pdf.com. It only takes a minute.

Next, view the javascript code for the VueJs component below. Take note of the various sections – most notably replace “YOUR-API-KEY” with your api key you received from signing up and also replace the boilerplate HTML with your own HTML. You can modify the function to pull in HTML from elsewhere.

It uses Axios library to make the API call. You can view the full Api2Pdf documentation here.

 

new Vue({
el: '#app',
methods: {
printToPdf: function(event) {
var endpoint = "https://v2018.api2pdf.com/chrome/html"
var apiKey = "YOUR-API-KEY" //Replace this API key from portal.api2pdf.com
var config = {
headers: {
Authorization: apiKey
}
}
var payload = {
html: "<p>Hello from VueJs</p>", //Use your own HTML
inlinePdf: true
}
axios.post(endpoint, payload, config)
.then(function(response) {
console.log(response.data.pdf); //this is your PDF! Do something with it
})
.catch(function(error) {
console.log(error);
});
}
}
})

 

To see a fully working example, view this JS Fiddle and don’t forget to replace the API key with your own.