# Generate and save a pdf with VueJS

# Generate a PDF with Puppeteer

Puppeteer is Node library to control Chrome thanks to an API. With that, you can generate PDFs file.

Here's the code that is used to do this. You then have to use this method into a route of your backend API.

app.createPDF = async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://example.com', {
    waitUntil: ['domcontentloaded', 'networkidle0', 'load']
  })

  const pdf = await page.pdf({
    path: 'quick-test.pdf'
  })
  await browser.close()
  return pdf
}

In this code, we instantiate a browser then we navigate to the example.com page.

The code for you route:

app.post('/documents', async (req, res) => {
  const pdf = await app.printDocument(dataBinding)
  res.contentType('application/pdf')
  res.send(pdf)
})

With that, a POST request let you access to your generated PDF document.

# Save in the front end with VueJS

Let's see how to download a PDF file with a vueJS app.

You can do it yourself this way

axios({
  url: 'http://localhost:5000/static/example.pdf',
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.pdf');
  document.body.appendChild(link);
  link.click();
});

Basically, creating a link and triggering the click.

Or you can choose a cleaner way. You can use file-saver in your project and import the saveAs method into a component.

import { saveAs } from 'file-saver'
...
async printDocument () {
  const { data } = await api.printDocument()
  const blob = new Blob([data], { type: 'application/pdf' })
  saveAs(blob, 'invoice.pdf')
}

Let's focus on the printDocument method. It will call your backend API to retrieve the PDF file (Here axios is used to call the backend) The most important thing is to define the responseType arraybuffer otherwise your PDF will be corrupted.

printDocument () {
  return axios.post(`api/documents`, {}, {
    responseType: 'arraybuffer'
  })
}

And that all you need to do to have a well formatted PDF file.

Until next time!