I’m trying to make a simple HTML to PDF API using Puppeteer but I keep getting this error message when sending a decent-sized HTML file. Nothing too crazy maybe a page or two. Here is the error and then here is my code.
Error:
Error generating PDF: Error: Navigation failed because browser has disconnected!
My Code
import { VercelRequest, VercelResponse } from '@vercel/node';
const puppeteer = require('autocode-puppeteer');
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
res.status(405).send({ error: 'Only POST requests are allowed' });
return;
}
console.log("Request body:", req.body); // Log the entire request body
const { html } = req.body;
if (!html) {
res.status(400).send({ error: 'No HTML content provided' });
return;
}
console.log("HTML content:", html); // Log the HTML content
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: [, 'load', 'domcontentloaded', 'networkidle2'], timeout: 3000});
const pdf = await page.pdf({ format: 'A4' });
await browser.close();
res.setHeader('Content-Type', 'application/pdf');
res.status(200).send(pdf);
} catch (error) {
console.error('Error generating PDF:', error);
res.status(500).send('Failed to generate PDF');
}
}
I have tried to let all the content load but still nothing. When i send in somthing like {"html": "<h1>This is a test</h1>"}
i get the PDF back no problem but when i send more html that has CSS, i get this error.