Skip to content

Instantly share code, notes, and snippets.

@maykbrito
Created February 20, 2021 13:44
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save maykbrito/444645526ac25a413021b0cd4d70fe24 to your computer and use it in GitHub Desktop.
Save maykbrito/444645526ac25a413021b0cd4d70fe24 to your computer and use it in GitHub Desktop.
Generate PDF with NodeJS and Puppeteer. Using ExpressJS, EJS and TailwindCSS to create fake data server

Generate PDF

Using NodeJS and Puppeteer.

Creating a fake data server with ExpressJS, EJS and TailwindCSS.

How to use it.

  1. Add this files do any directory
  2. Run npm install
  3. Run npm start to start server (port 3000)
  4. Run npm run print to create report.pdf file

#NeverStopLearning https://app.rocketseat.com.br

{
"name": "create-with-node-pdf",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"print": "node print.js"
},
"keywords": [
"NodeJS",
"Puppeteer",
"ExpressJS",
"EJS",
"TailwindCSS"
],
"author": "Mayk Brito",
"license": "MIT",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"puppeteer": "^7.1.0"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Relatório</title>
<link href="https://unpkg.com/tailwindcss/dist/tailwind.min.css" rel="stylesheet">
<style>
table {
width: 100%;
}
th {
text-align: left;
}
</style>
</head>
<body class="bg-purple-100">
<div class="m-8">
<h1 class="text-3xl mb-8">Listagem de passageiros</h1>
<table>
<thead>
<tr>
<th>Nome</th>
<th>Número do voo</th>
<th>Horário</th>
</tr>
</thead>
<tbody>
<% if (passengers.length > 0) { %>
<% passengers.forEach(passenger => { %>
<tr>
<td><%= passenger.name %></td>
<td><%= passenger.flightNumber %></td>
<td><%= passenger.time %></td>
</tr>
<% }); %>
<% } %>
</tbody>
<tfoot>
<tr><td colspan="2"><%=passengers.length%> passageiros</td></tr>
</tfoot>
</table>
</div>
</body>
</html>
const puppeteer = require('puppeteer')
const { writeFile } = require('fs');
(async() => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('http://localhost:3000/', {
waitUntil: 'networkidle0'
})
const pdf = await page.pdf({
printBackground: true,
format: 'Letter'
})
await browser.close()
writeFile("./report.pdf", pdf, {}, (err) => {
if(err){
return console.error('error')
}
console.log('success!')
})
})()
// data server
const express = require('express')
const ejs = require('ejs')
const path = require('path')
const app = express()
const passengers = [
{
name: "Joyce",
flightNumber: 7859,
time: "18h00",
},
{
name: "Brock",
flightNumber: 7859,
time: "18h00",
},
{
name: "Eve",
flightNumber: 7859,
time: "18h00",
},
];
app.get('/', (request, response) => {
const filePath = path.join(__dirname, "print.ejs")
ejs.renderFile(filePath, { passengers }, (err, html) => {
if(err) {
return response.send('Erro na leitura do arquivo')
}
// enviar para o navegador
return response.send(html)
})
})
app.listen(3000, () => console.log('The server is running on port 3000'))
@Akhil-EM
Copy link

Akhil-EM commented Dec 2, 2021

thanks. this saved my day!!!!

@RdC1965
Copy link

RdC1965 commented May 19, 2022

This is great!

@digen21
Copy link

digen21 commented Nov 2, 2022

Where you use print.js file?

@logictheprogrammer
Copy link

Thanks

@logictheprogrammer
Copy link

Where you use print.js file?

it's what you will use to access the get route created at the server.js, the print.js sends a get request to that route in order to get the html content from it, to create the pdf

@FajarAfrizal
Copy link

thanks

@mizanmahi
Copy link

Is there any way to write the external CSS for the rendered pdf ?

@chetan12125
Copy link

This code is working fine in local but not working in server,
getting this error - "error":"Failed to launch the browser process

@izakdvlpr
Copy link

Valeu mayk <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment