Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a PDF with Puppeteer in a node environment without writing it to disk

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?

like image 860
wuno Avatar asked Jun 01 '18 22:06

wuno


People also ask

How do I create a PDF from HTML?

On a Windows computer, open an HTML web page in Internet Explorer, Google Chrome, or Firefox. On a Mac, open an HTML web page in Firefox. Click the “Convert to PDF” button in the Adobe PDF toolbar to start the PDF conversion. Enter a file name and save your new PDF file in a desired location.


1 Answers

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):

  • path <string> The file path to save the PDF to. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the PDF won't be saved to the disk.
  • returns: <Promise<Buffer>> Promise which resolves with PDF buffer.
async generatePdf(url) {
   await page.goto(url, {waitUntil: 10000});
   const buffer = await page.pdf({
      format: 'A4'
   });
   return buffer;
}
like image 52
karthick Avatar answered Sep 22 '22 02:09

karthick