gpt4 book ai didi

angular - 无法在 jsPDF 的 addImage() 函数上为多个页面添加边距

转载 作者:行者123 更新时间:2023-12-05 08:08:05 24 4
gpt4 key购买 nike

enter image description here我正在尝试使用 jspdf 生成一些 html 表的 PDF。 addImage() 函数工作正常,但是当图像的大小大于 pdf 页面大小时,图像继续显示在下一页上,如上图所示

我正在尝试在每个页面上添加边距或填充,以便正确呈现。任何帮助将不胜感激。这是一个 Angular 项目。我在下面添加了我的代码。

public captureScreen() {
var data = document.getElementById('content');
html2canvas(data).then(canvas => {
// Few necessary setting options

const contentDataURL = canvas.toDataURL('image/png')
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;

var doc = new jsPDF('p', 'mm');
var position = 0;

doc.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);

heightLeft -= pageHeight;

while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save( 'file.pdf');

});

最佳答案

html2canvas 和 jsPDF。使用 doc.margin.horiz 和 doc.margin.vert。

function printPdfCalc(){
$('canvas').remove();

var container = document.querySelector("#calc-detail-container");
html2canvas(container).then(canvas => {
let doc = new jsPDF({
orientation: 'p',
unit: 'px',
format: 'a4'
});
doc.width = doc.internal.pageSize.width;
doc.height = doc.internal.pageSize.height;
doc.margin = {
horiz: 15,
vert: 20
};
doc.work = {
width: doc.width - (doc.margin.horiz * 2),
height: doc.height - (doc.margin.vert * 2)
}

let data = {
width: container.offsetWidth,
height: container.offsetHeight,
ctx: canvas.getContext('2d'),
page: {}
};
data.page.width = data.width;
data.page.height = (data.width*doc.work.height)/doc.work.width;

const getData = function(imgData, width, height){
let oCanvas = document.createElement('canvas');
oCanvas.width=width;
oCanvas.height=height;
let oCtx = oCanvas.getContext('2d');
oCtx.putImageData(imgData, 0, 0);
return oCanvas.toDataURL('image/png');
};

/**/
let oImgData = null;
let dataURL = null;
let pages = Math.ceil(data.height / data.page.height);
for(let i=0; i<pages; i++){
if( i!=0 ){
doc.addPage();
}
oImgData = data.ctx.getImageData(0, data.page.height*i, data.page.width, data.page.height);
dataURL = getData(oImgData, data.page.width, data.page.height);
doc.addImage(dataURL, 'PNG', doc.margin.horiz, doc.margin.vert, doc.work.width, doc.work.height);
}
/**/
doc.save('Test.pdf');

});
}

关于angular - 无法在 jsPDF 的 addImage() 函数上为多个页面添加边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522747/

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