parallax / jsPDF

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

PNG images are getting cropped #3745

Open tanishq-agarwal opened 4 months ago

tanishq-agarwal commented 4 months 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 4 months ago

@jamesbrobb can you help

jamesbrobb commented 4 months ago

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

wlsdn1101 commented 3 months ago

same issue here 🥲

vigneshpamu commented 2 months ago

Hey Hi, @tanishq-agarwal I would really like to work on this issue, could u please assign this to me ?

ArunKushhhh commented 1 month ago

Hello @tanishq-agarwal The issue you're encountering with PNG images getting cropped during PDF generation using the html2canvas library may be due to how the images are rendered within the canvas. I would like to work on this issue, so could you please assign it to me?