Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate PDF with puppeteer without save it

I have an API written with node.js hosted on heroku and my frontend app is written in Vue.js, it is on hostinger. I would like to know if is it possible to generate a PDF file with puppeteer and send it immediately to frontend client without saving it to the disk first? If yes, could you give me some example on how to do it?

Currently my function is like that:

exports.gerarPDFAvaliacao = async (dadosAvaliacao) => {
    try {
        const compile = async (fileName, data) => {

            const filePath = path.join(process.cwd(), 'src/templates/client/operation/', `${fileName}.hbs`);
            const html = await fs.readFile(filePath, 'utf-8');
            return await hbs.compile(html)(data);
        }

        const browser = await puppeteer.launch();
        const page = await browser.newPage();

        let content = await compile('avaliations', dadosAvaliacao);

        await page.goto(`data:text/html,${content}`, { waitUntil: 'networkidle0' });
        await page.emulateMedia('screen');
        await page.pdf({
            path: 'src/dist/pdf/' + dadosAvaliacao.arquivo + '.pdf',
            format: 'A4',
            printBackground: true
        })
        await browser.close();

        return dadosAvaliacao.arquivo + '.pdf';
    } catch (error) {
        console.log('Errors => ', error);
    }
};
like image 306
Felipe Paz Avatar asked Nov 06 '18 11:11

Felipe Paz


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

According to official documentation, if you do not provide a path the file will not be saved to disk.

page.pdf(options) : Options object which might have the following properties: path 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.

This mean that it should return something like a buffer or a binary representation of the generated file. You just need to return that or pipe that to the response,depending on the framework you are using.

This just outputs the pdf to console:

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');

console.log(await page.content());
const pdf = await page.pdf();

await browser.close();
console.log(pdf) // maybe do response(pdf).type('x-pdf')

EDIT: Here is a complete example using express and puppeteer that returns the pdf content directly in-memory. It runs on runkit, so I think the same limitations apply (maybe even more). If you navigate to the public endpoint that the example has you can see how the browser detects that it is a pdf file and renders it properly.

  • Public url: https://puppeteer-express-pdf-export-w3o8ip7k207y.runkit.sh/
  • Runkit notebook: https://runkit.com/danielo515/puppeteer-express-pdf-export

code

const puppeteer = require ('puppeteer');
const express = require('express');
var app = express(exports);
const browser = await puppeteer.launch();

const main = async () => {

    const page = await browser.newPage();
    await page.goto('https://example.com');

    const pdf = await page.pdf();
    return pdf;
 }


app.get('/', async function (req, res) {
        const pdf = await main();
        res.contentType("application/pdf");
        res.send(pdf);
});

app.listen(3000, function(){ console.log('Listening on 3000') });
like image 196
Danielo515 Avatar answered Oct 17 '22 19:10

Danielo515