1 回答

TA貢獻1878條經驗 獲得超4個贊
var allPromises = [];
for (const element of htmlData) {
var input = document.getElementById(element);
if (input.toLowerCase().startsWith('<img')) {
allPromises.push(html2canvas(input));
} else {
allPromises.push(Promise.resolve(input));
}
}
Promise.all(allPromises).then(response => {
response.forEach(input => {
if (input instanceof String) {
doc.setFont(fontName, 'bold');
var isH3 = input.toLowerCase().startsWith('<h3>');
writeText(input, isH3 ? h3_fontSize : h5_fontSize, isH3 ? 5 : 3);
} else {
imgData = input.toDataURL('image/jpeg', 1.0);
doc.addImage(imgData, 'PNG', left_edge_distance, position_mm, 100, 100);
}
});
doc.save('download.pdf');
});
我會將第一塊代碼修改為上面的代碼,其余部分保持原樣。我將在這里解釋它的作用:
維持一系列的承諾。
循環并檢查輸入是否為圖像標簽,并將返回的 Promise 存儲到 html2Canvas() 的數組中
否則,只需存儲已解決的承諾,將輸入返回到數組以維持順序。
運行 Promise.all() 并迭代 Promise 數組中的每個響應。
如果是字符串,則寫入文本,否則添加圖像。
最后,保存它。
添加回答
舉報