parallax / jsPDF

Client-side JavaScript PDF generation for everyone.
https://parall.ax/products/jspdf
MIT License
28.71k stars 4.62k forks source link

PNG images are getting cropped #3745

Open tanishq-agarwal opened 3 weeks ago

tanishq-agarwal commented 3 weeks ago

When I click the download button to generate the PDF, everything is downloaded correctly except for PNG images, which are getting cropped. SVG images are downloaded as expected. I’m attaching a screenshot for reference.

Here is the code which I've used:

` const downloadPDF = () => { const input = document.querySelector("#downloadPDF");

html2canvas(input, {
  scale: window.devicePixelRatio,
  useCORS: true, // Allows capturing images from other domains by enabling CORS
  allowTaint: true, // Allows capturing images with CORS security.
}).then((canvas) => {
  // Capture the content inside 'input' element into 'canvas'
  const imgData = canvas.toDataURL("image/png");
  const pdf = new jsPDF("p", "mm", "a4"); //portrait view of A4 size paper in mm unit
  const pdfWidth = pdf.internal.pageSize.getWidth();
  const pdfHeight = pdf.internal.pageSize.getHeight();

  // Calculate image dimensions based on aspect ratio
  const imgWidth = pdfWidth;
  const imgHeight = (canvas.height * pdfWidth) / canvas.width;

  let heightLeft = imgHeight;
  let position = 0;

  // Uses pdf.addImage to add the captured image (imgData) to the PDF at the specified coordinates (0, position) with dimensions (imgWidth, imgHeight)
  pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
  heightLeft -= pdfHeight;

  // Loops (while loop) to add additional pages if the content exceeds the initial page height (pdfHeight)
  while (heightLeft >= 0) {
    position = heightLeft - pdfHeight;
    pdf.addPage();
    pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
    heightLeft -= pdfHeight;
  }

  pdf.save("download.pdf");
});

};`

Screenshot 2024-07-03 at 12 48 39 PM
tanishq-agarwal commented 3 weeks ago

@jamesbrobb can you help

jamesbrobb commented 3 weeks ago

I'm afraid i can't be any help here, i last worked on this about 15 years ago