next js generate pdf

To generate a PDF in Next.js, follow these steps:

  1. Install Dependencies: Start by installing required packages. Use html-pdf or pdf-lib for generating PDFs. Run: bash npm install html-pdf # or npm install @pdf-lib/core

  2. Create a Function: Implement a function that generates the PDF. Use the chosen library (html-pdf or pdf-lib) to create the PDF content. For example, with html-pdf: ```javascript import fs from 'fs'; import pdf from 'html-pdf';

export default async function generatePDF(req, res) { const htmlContent = '

Hello, PDF!

'; // Your HTML content here

 pdf.create(htmlContent).toStream((err, stream) => {
   if (err) {
     res.status(500).end('Something went wrong');
     return;
   }
   res.setHeader('Content-Type', 'application/pdf');
   stream.pipe(res);
 });

} ```

  1. Create API Route: In Next.js, set up an API route that uses this function to generate the PDF. For example: ```javascript // pages/api/pdf.js import generatePDF from '../../path/to/generatePDF';

export default function handler(req, res) { if (req.method === 'GET') { generatePDF(req, res); } else { res.status(405).end(); // Method Not Allowed } } ```

  1. Access the Route: Access the API route from your frontend to trigger PDF generation. For instance, using fetch or axios: javascript // Call the API route to generate PDF fetch('/api/pdf') .then(response => response.blob()) .then(blob => { const url = window.URL.createObjectURL(new Blob([blob])); const a = document.createElement('a'); a.href = url; a.download = 'example.pdf'; a.click(); });

  2. Customize PDF Content: Modify the HTML content in the function to include the data or content you want in the PDF. You can use HTML/CSS to structure the content as needed.

Remember to handle errors and edge cases according to your specific application requirements.