4

I'm trying to generate a pdf in javascript using html2pdf that I installed using npm. The problem is that it will not show my images that comes from an url in my pdf. Here is my code: My print function that generates a pdf of my data

And here is a sandbox showing the issue: https://codesandbox.io/s/html2pdf-not-loading-image-gvmx0u

As you can see when you click on "export in pdf" the image hard coded in the content variable didn't get into the file..

The result is a pdf file with blank spaces instead of images. Does anyone know how to get my images into the pdf ? Is there a better library in js to build pdf from html ?

Zarcoin
  • 133
  • 2
  • 11
  • 1
    Please may you replace the image with a text-based [mcve]? – evolutionxbox May 04 '22 at 12:22
  • @evolutionxbox I edited the question with a link to a sandbox showing the issue – Zarcoin May 04 '22 at 13:04
  • Hello @KJ Can you explain what you did there ? Is it an image in base64 hosted online ? Where is the link to it ? – Zarcoin May 05 '22 at 07:17
  • How could I avoid CORS for jsPDF ? Would it work if I use an xmlhttprequest to get the image first and then build the pdf ? – Zarcoin May 05 '22 at 07:47
  • The problem is that in my web app I retrieve the urls of my images from an API, which I then want the user to be able to get them in a pdf file. Not sure how I can manage this with jspdf.. Is there another library to use in that case ? Should I use require.context ? – Zarcoin May 05 '22 at 12:06
  • allow Cors in html2pdf options: [stackoverflow](https://stackoverflow.com/questions/51791583/pdf-does-not-show-images-html2pdf-library) – Tichel Sep 23 '22 at 06:03

2 Answers2

7

I fixed this issue by putting

useCORS: true

  exportToPDF() {
        var opt = {
            margin: 0,
            filename: 'time_sheet_report.pdf',
            image: { type: 'jpeg', quality: 0.20 },
            html2canvas: { scale: 2,useCORS: true },
            jsPDF: { unit: 'in', format: 'a4', orientation: 'p' }
        };

        html2pdf().set(opt).from(this.$refs.document).save();
}
khatib
  • 366
  • 5
  • 7
5

For those wondering I resolved the problem by converting images in Base64 and use promises to put it in the html content of the html2pdf.

The whole answer is available in the sandbox of the original question: https://codesandbox.io/s/html2pdf-not-loading-image-gvmx0u

Here are the sources that helped (as well as what @KJ told me in the comments):

How to convert images in base64: https://stackoverflow.com/a/20285053/5065874

How to await the xmlhhtprequest: In JavaScript how do I/should I use async/await with XMLHttpRequest?

Again, thank you KJ for the help !

Zarcoin
  • 133
  • 2
  • 11