如何使用 jsPDF 使图像适合页面的中心?

How to fit an image in the center of a page using jsPDF?

使用 html2canvas 和 jsPDF,我正在尝试打印我屏幕上的整个 DIV,我已经做到了这一点:

const printAsPdf = () => {
  html2canvas(pageElement.current, {
    useCORS: true,
    allowTaint: true,
    scrollY: -window.scrollY,
  }).then(canvas => {
    const image = canvas.toDataURL('image/jpeg', 1.0);
    const doc = new jsPDF('p', 'px', 'a4');
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();

    const widthRatio = pageWidth / canvas.width;
    const heightRatio = pageHeight / canvas.height;
    const ratio = widthRatio > heightRatio ? heightRatio : widthRatio;

    const canvasWidth = canvas.width * ratio;
    const canvasHeight = canvas.height * ratio;

    doc.addImage(image, 'JPEG', 0, 0, canvasWidth, canvasHeight);
    doc.output('dataurlnewwindow');
  });
};

这会用我选择的 image/canvas 填满页面。但是我无法将页面上的图像死点对齐。

这个问题需要一些老派的 CSS 技巧。我回想起我们过去如何使用 position: absolute; 计算图像宽度和 canvas 宽度,取反并将其除以一半。在此处使用相同的技术非常有效!

const marginX = (pageWidth - canvasWidth) / 2;
const marginY = (pageHeight - canvasHeight) / 2;

因此,完整的函数如下所示:

const printAsPdf = () => {
  html2canvas(pageElement.current, {
    useCORS: true,
    allowTaint: true,
    scrollY: -window.scrollY,
  }).then(canvas => {
    const image = canvas.toDataURL('image/jpeg', 1.0);
    const doc = new jsPDF('p', 'px', 'a4');
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();

    const widthRatio = pageWidth / canvas.width;
    const heightRatio = pageHeight / canvas.height;
    const ratio = widthRatio > heightRatio ? heightRatio : widthRatio;

    const canvasWidth = canvas.width * ratio;
    const canvasHeight = canvas.height * ratio;

    const marginX = (pageWidth - canvasWidth) / 2;
    const marginY = (pageHeight - canvasHeight) / 2;

    doc.addImage(image, 'JPEG', marginX, marginY, canvasWidth, canvasHeight);
    doc.output('dataurlnewwindow');
  });
};