Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html2Canvas image is getting cut

I use Html2Canvas and then jsPdf to export the image.

This is the function:

function exportPdf() {
    content = $("#print");

    var useWidth = content.prop('scrollWidth');
    var useHeight = content.prop('scrollHeight');

    debugger;

    html2canvas((content), { width: useWidth, height: useHeight}).then(function (canvas) {
        debugger;
        var img = canvas.toDataURL("image/png");
        var doc = new jsPDF({
            unit:'px', 
            format:'a4'
        });

        debugger;
        doc.addImage(img, 'JPEG', 0, 0);
        doc.save('test.pdf');
    });
}

I think is taking in consideration the viewport, is like doing a printscreen, of course whatever is below the scroll it doesn't take it into consideration.

Any ideas?

like image 401
user3442470 Avatar asked Oct 31 '16 19:10

user3442470


1 Answers

You can try something with the responsive way like :

if (screen.width < 1024) {
    document
      .querySelector("meta[name=viewport]")
      .setAttribute("content", "width=1200px");
  }

  let generatedPDFB64;
  //used the Printable HOC for capturing printable component with print-id attribute
  const printElement = document.querySelector(`div[print-id=${selector}]`);
  // convert the html to canvase
  const convertedCanvas = await html2canvas(printElement, {
    allowTaint: true,
    removeContainer: true,
    backgroundColor: null,
    imageTimeout: 15000,
    logging: true,
    scale: 2,
    scrollY: window.scrollTo({
      top: 0,
      behavior: 'smooth'
    }),
    useCORS: true
  });

  const contentDataURL = convertedCanvas.toDataURL("image/png");
  const imgWidth = 205;
  const pageHeight = 300;
  const imgHeight = (convertedCanvas.height * imgWidth) / convertedCanvas.width;
  let heightLeft = imgHeight;
  const shouldCompress = true

  let pdf = new jsPDF("p", "mm", "a4", shouldCompress); // A4 size page of PDF
  let position = 0;

   pdf.addImage(
    contentDataURL,
    "PNG",
    0,
    position,
    imgWidth,
    imgHeight,
    "print",
    "FAST"
  ); 
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    pdf.addPage();
    pdf.addImage(
      convertedCanvas,
      0,
      position,
      imgWidth,
      imgHeight,
      "print",
      "FAST"
    );
    heightLeft -= pageHeight;
  }

  pdf.save("resume.pdf"); // Generated PDF

  if (screen.width < 1024) {
    document
      .querySelector("meta[name=viewport]")
      .setAttribute("content", "width=device-width, initial-scale=1");
  }

like image 62
Ashif Zafar Avatar answered Oct 26 '22 23:10

Ashif Zafar