Search code examples
cssreactjsvitehtml2canvas

Html2Canvas: Inconsistent PDF Image Output Across Devices


Issue Summary:

I am encountering discrepancies in the PDF images generated using Html2Canvas across different devices. While the design appears satisfactory on my laptop, it exhibits variations on other devices such as phones or different laptops. I suspect this inconsistency may stem from differences in screen resolution.

Code Snippet:

const DownloadBarcodes = async () => {
try {
  const { isConfirmed } = await getBarcodeText();

  if (isConfirmed) {
    const pdf = new jsPDF({
      unit: "mm",
      format: "a4",
    });

    const imgWidth = 210;
    const imgHeight = 296;
    const qrCodeContainer = document.createElement("div");
    qrCodeContainer.style.width = `${imgWidth}mm`;
    qrCodeContainer.style.height = `${imgHeight}mm`;
    document.body.appendChild(qrCodeContainer);

    const root = createRoot(qrCodeContainer);
    for (let j = 0; j < 2; j++) {
      const headerText = j === 0 ? "Good morning !" : "Good evening ! ";
      for (let i = 0; i < qrCodes.length + 1; i++) {
        const firstName = await extractNameWithoutNumber(
          qrCodes[i]?.waiterName.split(" ")[0]
        );
        root.render(
          <BarcodePaperTemplate
            url={qrCodes[i]?.url}
            name={firstName}
            headerText={headerText}
          />
        );

        const canvas = await html2canvas(qrCodeContainer, {
          willReadFrequently: true,
        });
        const qrCodeDataUrl = canvas.toDataURL("image/png");

        if (i > 0) {
          pdf.addImage(qrCodeDataUrl, "PNG", 0, 0, imgWidth, imgHeight);
          if (i < qrCodes.length + 1) {
            pdf.addPage();
          }
        }
      }
    }
    // Remove the last page (empty page)
    pdf.deletePage(pdf.internal.getNumberOfPages());
    document.body.removeChild(qrCodeContainer);
    const fileName = `${hallChoosen.hallName}.pdf`;
    pdf.save(fileName);

    handleClose();
  }
} catch (e) {
  handleClose();
} finally {
  ShowDialogAgain();
}};

Issue Details:

Platform Differences: The PDF output from Html2Canvas varies notably across devices, indicating potential discrepancies in rendering due to screen resolution or other device-specific factors. Consistency Concerns: While the design appears satisfactory on the developer's laptop, it exhibits unexpected scale styles and variations on other devices such as phones or different laptops. Probable Cause: The root cause of this inconsistency is likely associated with differences in screen resolution or rendering mechanisms between various devices.

What I Tried: I attempted to generate PDF images using Html2Canvas within a React application. The code snippet provided utilizes Html2Canvas to convert the content of a div into a base64 string and then captures the element to a PDF file. I ensured that the PDF format was set to A4 size, and I handled the image dimensions appropriately.

Expectations: I expected the generated PDF images to exhibit consistent designs across different devices. Specifically, I anticipated that the layout and scale styles would remain uniform regardless of the device used for rendering. On my laptop, the design appeared satisfactory, leading me to believe that the code implementation was correct.

Actual Results: However, when testing the application on various devices such as phones or other laptops, I observed significant variations in the PDF output. The scale styles differed, and the layout was inconsistent compared to the results obtained on my laptop. This inconsistency suggests that the PDF images generated on different devices are not aligned, potentially due to differences in screen resolutions or other device-specific factors.

Request for Assistance: I am seeking guidance on how to ensure consistent PDF output across different devices when utilizing Html2Canvas for conversion. Any insights or recommendations to address this issue would be greatly appreciated.

Thank you in advance for your assistance.


Solution

  • I appreciate all the feedback and suggestions regarding my issue with html2canvas and jsPDF. I wanted to provide an update on how I resolved the problem.

    After some investigation, I realized that html2canvas works best with basic HTML tags like <div>, <p>, <h1>, etc. The issue I was facing was due to my use of more complex components, specifically ones that included <Qrcode>. To resolve this, I removed the styles from the complex components such as <Qrcode> and wrapped them with basic HTML tags like <div>, then applied the necessary styles to those <div> elements. This adjustment allowed me to capture the elements correctly and achieve the desired output.

    enter image description here

    Thank you again for your help and advice!

    Best regards, Tal Schreiber