I have a NextJs application with an api route, which calls an internal page to generate a pdf file.
This method generate the pdf file 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;
}
This method (sendEmail) is being called from the frontend, with the data (req.body) provided to generate the pdf page properly. I am passing that data as a parameter to the generatePdf method.
async function sendEmail(req, res) {
const pdf = await generatePdf(req.body);
...
I am wondering if it is possible to generate that page using the provider data from the req.body in nextjs. So that I can generate the pdf files dynamically since the content of the Pdf page changes depending on what data I sent.