我正在尝试打印多个 jsPDF.HTML(...) 的结果。它们中的每一个都在同一 div 内列表的不同分页中运行。该 div 的 PDF 转换会多次显示第一页,尽管我可以在执行每个 jsPDF.HTML(...) 之前在 UI 中看到其中的项目发生变化。
有解决方案吗?或者至少解释一下为什么会发生这种情况?
async printReceipt() {
console.log('getting the number of pages in the pagination');
var lenArr = new Array(Math.ceil(this.receiptItems.length / 10));
var doc = new jsPDF('p', 'pt', [496, 702]);
var arrayBuffer: ArrayBuffer[] = [];
var fileURL;
console.log('creatting main doc');
for (let index = 0; index < lenArr.length; index++) {
console.log('Changing pagination to:', index + 1);
this.page = index + 1;
console.log('Converting page:', index + 1);
await new Promise<void>(async (resolve, reject) => {
doc.html(document.getElementById('receipt'), {
callback: async (res) => {
console.log('Adding page to buffer, page:', index + 1);
arrayBuffer.push(res.output('arraybuffer'));
if (lenArr.length - 1 == index) {
console.log('Printing');
await this.mergePdfs(arrayBuffer);
}
resolve();
},
});
});
}
}
日志顺序:
我通过将 jsPDF 对象的声明移动到 Promise 中并在页面更改和 Promise 之间添加超时来解决这个问题。
async printReceipt() {
console.log('getting the number of pages in the pagination');
var lenArr = new Array(Math.ceil(this.receiptItems.length / 10));
var arrayBuffer: ArrayBuffer[] = [];
var fileURL;
console.log('creatting main doc');
for (let index = 0; index < lenArr.length; index++) {
console.log('Changing pagination to:', index + 1);
this.page = index + 1;
await this.sleep(1000);
console.log('Converting page:', index + 1);
await new Promise<void>(async (resolve, reject) => {
***var doc = new jsPDF('p', 'pt', [496, 702]);***
doc.html(document.getElementById('receipt'), {
callback: async (res) => {
console.log('Adding page to buffer, page:', index + 1);
arrayBuffer.push(res.output('arraybuffer'));
if (lenArr.length - 1 == index) {
console.log('Printing');
await this.mergePdfs(arrayBuffer);
}
resolve();
},
});
});
}
}
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
看起来,无论该方法被执行多次,jsPDF 对象都会保留 jsPDF.html(...) 的第一个结果。