If you've ever used jsPDF and html2canvas with Vue to convert html to a PDF file then you probably understand the headaches that you run into when trying to achieve the proper size and resolution of the PDF. In this article I'm going to talk about the headaches that I ran into and what I did to solve those issues, so let's get started.
The first thing you will need to do is create a new jsPDF object. You can achieve this by doing the following:
const doc = new jsPDF({
orientation: 'p',
unit: 'px',
format: 'a4',
hotfixes: ['px_scaling'],
});
The default for unit is mm, if you decide to use px like I did you will need to include the hotfixes option parameter which takes an array and you will need to include px_scaling like I did in the above code.
The unit that you used to create your jsPDF object is very important. And you'll see why in a moment.
Now, once you've created your jsPDF object you'll need to use html2canvas to create an image which can then be converted to a pdf, like so:
html2canvas(this.$refs.content, {
width: doc.internal.pageSize.getWidth(),
height: doc.internal.pageSize.getHeight()
}).then((canvas) => {
const img = canvas.toDataURL("image/png");
doc.addImage(img, "PNG", 140, 10, doc.internal.pageSize.getWidth(), doc.internal.pageSize.getHeight());
doc.save("p&lstatement.pdf");
})
Originally when I was testing this out I was getting the height and width of the ref by doing the following:
this.$refs.content.clientWidth
this.$refs.content.clientHeight
The problem with this was that it was returning pixels and I had originally set the jsPDF unit to mm which was distorting the image. So make sure that you're using the same unit for both jsPDF and the actual image.
And here is the downloaded pdf:
Hopefully this helps someone else from pulling their hair out trying to get the PDF to display correctly. You may need to play around with the dimensions to get it perfect, but this is what worked best for me.
Top comments (2)
Hi Jona,
Can you please update your article with latest jsPdf version?
please update this with latest version i m facing issue with latest version when i open link in mobile browser it is missing some data some times