First of all, I need to capture a lot of demo pictures, when I use HTML2Canvas to turn, there is always a part of the screenshot, I found several ways on the Internet, but none of them solved, I was very speechless, There seems to be no reply from Gitlab. Finally, I used the dom-to-image plug-in to solve the collocation of JSPDF

By the way, is there a function to convert the page to PDF without converting the image to Canvas, which means that the direct DOM elements and styles are generated into PDF for editing

No paging


export const downloadPDF = async (ele) => {
  var element = window.document.querySelector(ele); // The DOM element is the div container to export the PDF
  console.log(element);
  if(! element)return;

  const resp = await domtoimage.toPng(element);
  let contentWidth = element.clientWidth;
  let contentHeight = element.clientHeight;

  // Set the size of the PDF to 1pt/1px = 0.75pt = (px/scale)* 0.75
  // 2 scales the scale above by 2 times
  var pdfX = ((contentWidth + 10) / 2) * 0.75;
  var pdfY = ((contentHeight + 500) / 2) * 0.75; // 500 is left blank at the bottom

  // Set the size of the content image. Img is in pt units
  var imgX = pdfX;
  var imgY = (contentHeight / 2) * 0.75; // No blank space is required for the content image

  var pdf = new jsPDF("p"."pt", [pdfX, pdfY]);
  // add the content image to the PDF, because the content width and height are the same as the PDF width and height, it only needs one page, and the position is 0,0
  pdf.addImage(resp, "jpeg".0.0, imgX, imgY);

  pdf.save(`1111f`);
};

    
Copy the code

paging

export const downloadPDF = async (ele) => {
  var element = window.document.querySelector(ele); // The DOM element is the div container to export the PDF
  console.log(element);
  if(! element)return;

  const resp = await domtoimage.toPng(element);
  let contentWidth = element.clientWidth;
  let contentHeight = element.clientHeight;

  let pageHeight = (contentWidth / 592.28) * 841.89;
  // The height of an HTML page that did not generate a PDF
  let leftHeight = contentHeight;
  // Page offset
  let position = 0;
  // A4 paper size [595.28,841.89], HTML page generated canvas in PDF image width and height
  let imgWidth = 595.28;
  let imgHeight = (592.28 / contentWidth) * contentHeight;
  let pdf = new jsPDF(""."pt"."a4");

  // There are two heights to distinguish, one is the actual height of the HTML page, and the height of the generated PDF page (841.89)
  // When the content does not exceed the PDF page display range, no paging
  if (leftHeight < pageHeight) {
    pdf.addImage(resp, "JPEG".0.0, imgWidth, imgHeight);
  } else {
    while (leftHeight > 0) {
      pdf.addImage(resp, "JPEG".0, position, imgWidth, imgHeight);
      leftHeight -= pageHeight;
      position -= 841.89;
      // Avoid adding blank pages
      if (leftHeight > 0) {
        pdf.addPage();
      }
    }
  }
  pdf.save('content.pdf');
};

Copy the code