无法使用 html2canvas 和 jsPDF 捕获元素内的完整内容并将其包含在 PDF 中

问题描述 投票:0回答:1

我正在尝试使用 Vue.js 项目中的 html2canvas 和 jsPDF 库从 id 为“pagebuilder”的特定 div 元素内的内容生成 PDF。但是,我面临一个问题,PDF 仅捕获屏幕上可见的内容,而不包括需要滚动的内容。

谁知道如何解决这个问题?

相关代码如下:

import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';


const generatePDF = async function () {
  const doc = new jsPDF();

  // Select the div element with the id 'pagebuilder'
  try {
    const element = document.getElementById('pagebuilder');

    const canvas = await html2canvas(element, {
      useCORS: true,
      allowTaint: true,
      dpi: 200,
      scrollY: -window.scrollY, // Capture full content even if not visible on the screen
    });

    // Get the image data URL
    const imageData = canvas.toDataURL('image/jpeg');

    // Embed the image into the PDF
    doc.addImage(imageData, 'JPEG', 10, 10, 190, 0);
    // Save the PDF
    doc.save('downloaded_file.pdf');
  } catch (error) {
    console.error('Error generating PDF:', error);
  }
};

为了测试,我还尝试添加以下选项,但它不起作用:

 height: 30000
windowHeight: 30000

javascript jspdf html2canvas
1个回答
0
投票

htmlcanvas
工作正常并将整个元素捕获到画布中。仅其高度就占用了 PDF 中的 1 页以上。这就是它被砍的原因。

我希望每一页都有很好的边距。我所做的是将图像分割为 X 个图像,然后创建包含 X 个页面的 PDF。部分图像的正确高度是多少?

1600px
似乎有效,但我想知道为什么会这样,页面大小为
297mm
(和
10mm
边距)。

import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';

function splitImageSavePDF(imgData, constantHeight, doc) {
  const image = new Image();
  image.src = imgData;

  image.onload = function() {
    const originalHeight = image.height;
    const originalWidth = image.width;
    const numImages = Math.ceil(originalHeight / constantHeight);

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    for (let i = 0; i < numImages; i++) {
      const top = i * constantHeight;
      const bottom = Math.min((i + 1) * constantHeight, originalHeight);
      const height = bottom - top;

      canvas.width = originalWidth;
      canvas.height = height;

      ctx.clearRect(0, 0, originalWidth, height);
      ctx.drawImage(image, 0, top, originalWidth, height, 0, 0, originalWidth, height);

      const splitDataUri = canvas.toDataURL("image/png");

      doc.addImage(splitDataUri, 'JPEG', 10, 10, 190, 0);
      if (i < numImages - 1) {
        doc.addPage()
      }
    }

    doc.save('downloaded_file.pdf');
  };
}

// usage:

var div = document.querySelector("#test")

html2canvas(div, {
  useCORS: true,
  allowTaint: true
}).then(canvas => {

  const imgData = canvas.toDataURL('image/png');
  const doc = new jsPDF();

  splitImageSavePDF(imgData, 1630, doc)

});
© www.soinside.com 2019 - 2024. All rights reserved.