0

Hi I have a few questions regarding the use of html2canvas. I am learning JavaScript and I am making a platform that helps to provide budgets that are downloaded in PDF format. I need the html2canvas to take a section (id=imagenPiezas) which is dynamicaly populated through a script (in index.js takes the ids and imgs from a data.js) and take it to pdf-lib. The result is that when I generate the PDF, the section (id=imagenPiezas) that needs to be included doesn't appear in the PDF.

To contextualize this problem, the main idea of the project is the following: Is an inside site to facilitate the budget making of the company, there are different inputs and the input id=piezas1-8 allows the user to select different pieces from a couch to make your configuration. In the section id=imagenPiezas you are going to see the couch configuration dynamically changing. The idea is that the html2canvas takes and img of that section an prints it into the PDF (pdfgenerator.js).

GITHUB LINK: https://github.com/FrancoKohler/Temasdos

I tried a wide variety of things, the main one in which i have been working around was this one (but in what I have tried that html2canvas isnt correctly printing it on the PDF):


if (typeof html2canvas === "function") {
    const canvas = await html2canvas(document.getElementById("imagenPiezas"));
    const imgData = canvas.toDataURL("image/png");
    const pdfImage = await pdfDoc.embedPng(imgData);
    page.drawImage(pdfImage, { x: 20, y: 160, width: 170, height: 100 });
  } else {
    console.error("html2canvas is not loaded correctly.");
  }

1 Answer 1

0

Looked at the github code. In github you were using html2canvas(document.getElementById("imagenPiezas")).then(...), which was failing to me because the code inside the then(...) statement was not being awaited before generating the PDF. But in the code snippet that you pasted here you already fixed that so that's good.

What worked for me to get the image to show in the PDF was:

1- I had to use absolute URLs for the images to get html2canvas to capture them. Relative paths weren't working. So, instead of /assets/CH_80_IZQ.png in your data.js I used https://francokohler.github.io/Temasdos/assets/CH_80_IZQ.png

2- I added {useCORS: true} to the html2canvas function (to make sure it is able to download the image cross domain when opening the website locally). So the html2canvas line ends up as:

const canvas = await html2canvas(document.getElementById("imagenPiezas"), {useCORS: true})

Hope that helps, cheers

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.