To convert HTML to PDF in a Node.js serverless function on Vercel, you can use a library like puppeteer. Here’s a basic example of how to create such a function:

  1. Set up a new Vercel project if you haven’t already and create an api directory as shown in the previous response.

  2. Install the necessary dependencies, including puppeteer, which is a headless Chrome browser that can be used to generate PDFs from HTML.

npm install puppeteer
  1. Inside the api directory, create a JavaScript or TypeScript file, for example, htmlToPdf.js:
// api/htmlToPdf.js
 
const puppeteer = require('puppeteer');
 
module.exports = async (req, res) => {
  const { html } = req.body; // Assuming you send HTML content in the request body
 
  if (!html) {
    return res.status(400).json({ error: 'Missing HTML content in the request body' });
  }
 
  try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
 
    await page.setContent(html); // Set the HTML content
    const pdfBuffer = await page.pdf(); // Generate the PDF
 
    await browser.close();
 
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=generated.pdf');
    res.status(200).end(pdfBuffer);
  } catch (error) {
    console.error('Error generating PDF:', error);
    res.status(500).json({ error: 'An error occurred while generating the PDF' });
  }
};
  1. This code sets up an API endpoint that expects HTML content in the request body and converts it to a PDF using Puppeteer.

  2. Deploy your project to Vercel using the CLI:

vercel
  1. Once deployed, you can send a POST request with HTML content to the following URL to generate a PDF:
https://your-vercel-project-name.vercel.app/api/htmlToPdf

Make sure to replace your-vercel-project-name with your actual project name.

Remember to handle errors and security considerations appropriately for your use case, especially if this functionality is exposed to the public.

Questions

https://vercel.com/docs/functions/serverless-functions/quickstart