Reputation: 9865
Background
I am working in a node.js express application where we have a need to generate PDFs. Currently we are using Puppeteer from Google which makes this simple. In the documentation the way it shows to do this is by passing a path to the object which tells Puppeteer where to write the PDF.
Problem
I would prefer to not write this PDF file to disk. The goal here is to have a client hit an end point where a PDF will be generated and returned to the client. Creating a file for 2 seconds adds a tiny bit of state which causes me to have to deal with a lot more headaches in order to deploy to production.
Example
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(
'https://example.com/',
);
await page.pdf({
path: filePath,
format: 'A4',
margin: {
top: '20px',
left: '20px',
right: '20px',
bottom: '20px',
},
});
await browser.close();
Question
In this example of code I am creating a PDF and storing it to disk. How can I create this PDF but instead of writing it to disk, return it to the client in the response immediately?
Upvotes: 6
Views: 2977
Reputation: 12176
Strange I am also having the same requirement.
The problem by itself is relatively simple. All you need to do is remove the path attribute and wait for the page.pdf to complete its task, it will return a bytearray just send that as a response.
You can find the documentation for page.pdf(options)
:
async generatePdf(url) {
await page.goto(url, {waitUntil: 10000});
const buffer = await page.pdf({
format: 'A4'
});
return buffer;
}
Upvotes: 11