NodeJS 在for循环中生成多个文件到pdf

ghg1uchk  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(127)

我一直在尝试使用for循环中的**“html-pdf-node”包生成多个文件到pdf。但问题是,在生成一些文件后,它给予协议错误(Page.printToPDF):目标关闭**。我使用了promise.all(),但无法解决问题。如有任何帮助,我们将不胜感激。谢谢
下面是我的代码

for (let index = 0; index < result.length; index++) {
        const file_name = getRandomFileName();
        const html="abc";

        const margin = {
          top: "210px",
          right: "100px",
          bottom: "150px",
          left: "80px",
        };

        const options = {
          format: "A4",
          path: `some/path/{file_name}.pdf`,
          margin: margin,
        };

        const file = await html_to_pdf
          .generatePdf({ content: html }, options)
          .then(async (pdfBuffer) => {
            await fs.writeFileSync(options.path, pdfBuffer);
            filename.push(file_name);

            console.log("PDF saved successfully!");
          })
          .catch((error) => {
            console.error("Error generating PDF:", error);
          });
      }
return filename
}

字符串
我已经搜索并找到了使用Promise.all的相对解决方案。我已经使用promise.all()更新了我的代码,但它不起作用。
下面是我尝试的代码

const file = await **Promise.all**(html_to_pdf
          .generatePdf({ content: html }, options)
          .then(async (pdfBuffer) => {
            await fs.writeFileSync(options.path, pdfBuffer);
            filename.push(file_name);

            console.log("PDF saved successfully!");
          })
          .catch((error) => {
            console.error("Error generating PDF:", error);
          })
)

7rfyedvj

7rfyedvj1#

在这里,我使用**result.map()来创建promise数组,它将生成PDF。然后,我们使用Promise.all()**来等待所有这些项

async function generatePDFs(result) {
        const filename = [];
      
        const generatePdfPromiseArray = result.map(async (item) => {
          const file_name = getRandomFileName();
          const html = "abc";
      
          const margin = {
            top: "210px",
            right: "100px",
            bottom: "150px",
            left: "80px",
          };
      
          const options = {
            format: "A4",
            path: `some/path/${file_name}.pdf`,
            margin: margin,
          };
      
          try {
            const pdfBuffer = await html_to_pdf.generatePdf({ content: html }, options);
            await fs.writeFileSync(options.path, pdfBuffer);
            filename.push(file_name);
            console.log("PDF saved successfully!");
          } catch (error) {
            console.error("Error generating PDF:", error);
          }
        });
      
        // Wait for all the promises to resolve
        await Promise.all(generatePdfPromiseArray);
      
        return filename;
      }

字符串

相关问题