gpt4 book ai didi

javascript - 如何使用 jsPDF 将图像放在页面的中心?

转载 作者:行者123 更新时间:2023-12-01 16:04:27 26 4
gpt4 key购买 nike

使用 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');
});
};

这会用我选择的图像/ 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');
});
};

关于javascript - 如何使用 jsPDF 将图像放在页面的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com