2

I am using jspdf's html() method to convert an HTML string of an invitation to pdf.

The problem is that I don't know how to set the content height to fit in one pdf page, cause the generated pdf get split if the height is bigger than the pdf height and it's not looking good for an invitation.

Here is my code:

const doc = new jspdf('p', 'pt', 'a4');
let docWidth = doc.internal.pageSize.getWidth();

const htmlString = row.content;
await doc.html(htmlString, {
  callback: function(doc) {
    doc.save('file.pdf');
  },

  autoPaging: 'text',
  margin: [0, 0, 0, 0],
  width: docWidth,
  windowWidth: 1000,

})
double-beep
  • 5,031
  • 17
  • 33
  • 41
Yafaa ats
  • 31
  • 4
  • I have encountered similar issue before but with mpdf (for php) not jspdf. I solved it by converting my HTML into image and then I rendered the image in my PDF and made it fit the page. To convert HTML to image I used HTML2CANVAS https://html2canvas.hertzen.com/ – DVN-Anakin Sep 16 '21 at 12:25
  • @DVN-Anakin i did what you said, and even so the height is not fitting exactly the pdf page, here what i tried : const pdf = new jspdf('p', 'pt', 'a4'); html2canvas(content, {scale: 2 }).then(canvas => { let imgWidth = pdf.internal.pageSize.getWidth(); let imgHeight = canvas.height * imgWidth / canvas.width; const contentDataURL = canvas.toDataURL('image/png'); pdf.addImage(contentDataURL, 'PNG', 0, 0, imgWidth, imgHeight); pdf.save(invitation.title + '.pdf'); And, i don't know why that methode not working in firefox browser – Yafaa ats Sep 16 '21 at 21:13
  • 1
    @Yafaaats well, firstly I set a fixed height and a fixed width to my HTML wrapper, you can find `A4` dimensions in pixels on Google. So, if your HTML is wrapped inside a `div`, you should try setting `
    ` before converting that `div` into an image and inserting it into your PDF.
    – DVN-Anakin Sep 17 '21 at 00:01
  • The idea is to have an image of the same size or at least the same proportions as an `A4` canvas, so it either fits or you will have to resize a bit and try again. Easy peasy. – DVN-Anakin Sep 17 '21 at 00:07
  • @Yafaaats if you have a problem with Firefox not rendering an image correctly, try `.jpg` instead of `.png` – DVN-Anakin Sep 17 '21 at 00:10
  • @Yafaaats this answer might help u as well >>> https://stackoverflow.com/questions/36472094/how-to-set-image-to-fit-width-of-the-page-using-jspdf – DVN-Anakin Sep 17 '21 at 00:17
  • @DVN-Anakin thank you for your answers, i think it doesn't work in firefox because i m using an iframe to hold the html string – Yafaa ats Sep 17 '21 at 11:29

0 Answers0