I've developed a NextJs application with an API route that calls an internal page to create a PDF file.
Here is the code snippet responsible for generating the PDF in my API route:
function serialize(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
};
async function generatePdf(body) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Allows you to intercept a request; must appear before
// your first page.goto()
await page.setRequestInterception(true);
// Request intercept handler... will be triggered with
// each page.goto() statement
page.on("request", (interceptedRequest) => {
// Here, is where you change the request method and
// add your post data
var data = {
method: "POST",
postData: serialize(body),
headers: {
...interceptedRequest.headers(),
"Content-Type": "application/x-www-form-urlencoded",
},
};
// Request modified... finish sending!
interceptedRequest.continue(data);
// Immediately disable setRequestInterception, or all other requests will hang
page.setRequestInterception(false);
});
const response = await page.goto(process.env.GEN_PDF_URL, {
waitUntil: "networkidle2",
});
const pdf = await page.pdf({
path: "test.pdf",
printBackground: true,
format: "a4",
});
const responseBody = await response.text();
console.log(responseBody);
await browser.close();
return pdf;
}
The sendEmail method is called from the frontend and passes req.body as data to generate the PDF correctly.
async function sendEmail(req, res) {
const pdf = await generatePdf(req.body);
...
I am contemplating whether it's feasible to dynamically generate the PDF based on the provider data sent through req.body in Next.js. This would enable me to create PDF files adaptively since the content of the PDF page varies depending on the data provided.