我想上傳多張圖片(不同大小),壓縮每張圖片并按上傳順序將其添加到 PDF 檔案中。處理完所有上傳的影像后,我想保存 PDF 檔案
在附圖中,FileList 的順序正確,但是當我嘗試處理它們時,順序完全錯誤。它從檔案[13](最小的檔案)開始,然后生成 pdf,然后處理其余的影像。
正確的方法是如何實作這一點并確保只有在所有影像都以正確的順序處理后才保存 PDF 非常感謝!
我有一個輸入檔案:
<input id="file" type="file" accept="image/*" multiple .....>
我有一個處理影像的功能:
Array.from(files).forEach(async (file: any, i: number) => {
console.log("Index inside forEach: " i);
imageCompression(file, compressOptions).then(function (compressedFile) {
let fileUrl = URL.createObjectURL(compressedFile)
let fileType = compressedFile.type === "image/png" ? "PNG" : "JPEG";
const pdfWidth = PDF.internal.pageSize.getWidth();
const pdfHeight = PDF.internal.pageSize.getHeight();
PDF.addImage(fileUrl, fileType, 0, 0, pdfWidth, pdfHeight, "alias" i, 'SLOW');
console.log("Index inside imageCompression: " i " -> " compressedFile.name);
if ( i < files.length - 1) {
PDF.addPage('a4');
}
if ( i === files.length - 1) {
console.log('!!!! GENERATE PDF');
PDF.save('fisa_' new Date().getTime() '.pdf');
}
})
.catch(function (error) {
console.log(error.message);
});
});

uj5u.com熱心網友回復:
更改Array#forEach為Array#map:
const compressions = Array.from(files).map((file) => {
return imageCompression(file, compressOptions);
});
Promise.all(compressions).then((compressedImages) => {
// the ordering of images in `compressedImages` is the same as in `files`
// you can do the PDF.addImage(...) and PDF.addPage(...) bits here
});
使用現代async/await語法,這看起來稍微好一些:
const compressions = Array.from(files).map((file) => {
return imageCompression(file, compressOptions);
});
const compressedImages = await Promise.all(compressions);
// the ordering of images in `compressedImages` is the same as in `files`
// you can do the PDF.addImage(...) and PDF.addPage(...) bits here
查看此答案以獲取有關回圈中 Promise 的更多見解。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408389.html
標籤:
上一篇:Angular-重繪內容的問題
