0

I am using Puppeteer to generate PDFs from local HTML and subsequently send them to the client. However, the issue I'm facing is that when I initialize Puppeteer, it sends a 404 response to the client. I've tried debugging, and at some point during the process of creating a browser instance and generating a new page, Puppeteer sends a 404 response, preventing me from sending the correct response with the PDF.

Is there a way to configure Puppeteer or handle its responses to ensure that it doesn't interfere with my ExpressJS response handling?

Any insights or solutions would be greatly appreciated. Thank you!

router.get(
  "/fco1_3/pdf/:_id",
  [
    fco1_3.obtenerDatosParaPDF,
    firmaDigital.crearTemporalesParaDocumento,
    pdf.generar,
  ],
  async (req, res) => {
    const rutaPlantilla = req.rutaPlantilla;
    const pdfFilePath = req.rutaPDF;
    try {
      browserInstance = await puppeteer.launch({
        headless: "new",
      });

      page = await browserInstance.newPage();
      await page.goto(`file://${rutaPlantilla}`, {
        waitUntil: ["networkidle2"],
      });

      // Cargar el archivo HTML local o una URL
      const pdfOptions = {
        path: pdfFilePath,
        format: "letter",
        margin: { top: "20px", right: "20px", bottom: "20px", left: "20px" },
      };
      await page.pdf(pdfOptions);
      console.log("PDF generado exitosamente:");
      //Responder con descarga de pdf generado
      res.download(pdfFilePath, (err) => {
        if (err) {
          console.log("Error al enviar el PDF:", err);
        }
      });
    } catch (error) {
      // res.sendErrorResponse("Error al generar el PDF", error, 500);
      console.error("Error al generar el PDF:", error);
    }
  }
);

I have tried implementing a singleton approach, but every time I use page, the error response is sent. I have thoroughly checked all the responses, and it's clear that this error response originates from Puppeteer.

  • 1
    This looks pretty suspicious--the routes are creating global variables for `browser` and `page`. Puppeteer doesn't send responses to clients per se--Express does. Puppeteer's only job is to navigate to a page and snap a PDF. It's possible that the navigation returns a 404 inside the browser Puppeteer automates, but that seems unlikely since it's a local file, unless it's possible that that file doesn't exist. I suggest providing a [mcve] so we can debug the underlying 404 issue--that should not occur naturally. See [this post](https://stackoverflow.com/a/67910262/6243352) for setup ideas. – ggorlen Aug 16 '23 at 00:25

0 Answers0