为此,您需要在html2canvas方法中添加选项scrollY{scrollY:-window.scrollY},它将截取完全呈现的页面的屏幕截图。
除此之外,我们知道滚动条中包含数据。为此,您需要暂时移除滚动条并在生成PDF后添加。您可以通过将id简单地添加到<ul class="list-group list-group-flush vert-scrollable-150" id="alldata">
元素中来实现此目的。
// 用于禁用滚动
document.getElementById('alldata').style.overflow = 'inherit';
document.getElementById('alldata').style.maxHeight = 'inherit';
async downloadPdf() {
var data = document.getElementById('pdfDownload');
$('pdfOpenHide').attr('hidden', true);
document.getElementById('alldata').style.overflow = 'inherit';
document.getElementById('alldata').style.maxHeight = 'inherit';
await html2canvas(data, {scrollY: -window.scrollY,
scale: 1}).then(canvas => {
var imgWidth = 150;
var imgHeight = canvas.height * imgWidth / canvas.width;
const contentDataURL = canvas.toDataURL('image/png', 1.0)
document.getElementById('alldata').style.overflow = 'scroll';
document.getElementById('alldata').style.maxHeight = '150px';
let pdf = new jspdf('l', 'mm','a4');
var position = 0;
const divHeight = data.clientHeight
const divWidth = data.clientWidth
const ratio = divHeight / divWidth;
const width = pdf.internal.pageSize.getWidth();
let height = pdf.internal.pageSize.getHeight();
height = ratio * width;
pdf.addImage(contentDataURL, 'PNG', 0, position, width, height);
window.open(pdf.output('bloburl', { filename: 'new-file.pdf' }), '_blank');
});
}
如果数据在滚动条中更多,您也可以使用jspdf添加页面。
更多参考资料,请查看此链接
另一种解决方法:如果数据更多
async downloadPdf() {
var data = document.getElementById("pdfDownload");
$("pdfOpenHide").attr("hidden", true);
document.getElementById("alldata").style.overflow = "inherit";
document.getElementById("alldata").style.maxHeight = "inherit";
await html2canvas(data, { scrollY: -window.scrollY, scale: 1 }).then(
canvas => {
const contentDataURL = canvas.toDataURL("image/png", 1.0);
document.getElementById("alldata").style.overflow = "scroll";
document.getElementById("alldata").style.maxHeight = "150px";
let pdf = new jspdf("l", "mm", "a4");
let imgWidth = 300;
let pageHeight = pdf.internal.pageSize.height;
let imgHeight = (canvas.height * imgWidth) / canvas.width;
let heightLeft = imgHeight;
let position = 0;
pdf.addImage(contentDataURL, "PNG", 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(contentDataURL, "PNG", 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
window.open(
pdf.output("bloburl", { filename: "new-file.pdf" }),
"_blank"
);
}
);
}