Open vdias38 opened 2 years ago
$ cd [PROJECT_PATH]
$ npm install -g firebase-tools
$ firebase init functions
const puppeteer = require("puppeteer");
const fs = require("fs-extra");
const hbs = require("handlebars");
const path = require("path");
async function compileTpl(data){
try{
const filePath = path.join(__dirname,"../templates/index.hbs");
const tpl = await fs.readFile(filePath,'utf-8');
return hbs.compile(tpl)(data);
}catch(error){
console.log(error);
}
}
(async () => {
// launch a new chrome instance
const browser = await puppeteer.launch({
headless: true
})
// create a new page
const page = await browser.newPage()
// set your html as the pages content
const html = await compileTpl({title: "Hello world"});
await page.setContent(html, {
waitUntil: 'domcontentloaded'
})
await page.setViewport({
width: 960,
height: 760,
deviceScaleFactor: 1,
});
// const imageBuffer = await page.screenshot({});
await page.screenshot({ path: 'result.png', fullPage: true })
await browser.close();
})()
https://medium.com/@fmoessle/use-html-and-puppeteer-to-create-pdfs-in-node-js-566dbaf9d9ca https://stackoverflow.com/a/55079122 https://stackoverflow.com/a/60480450 https://stackoverflow.com/q/60871125/4982169
I've commited a scaffold of cloud functions and scripts folder. I recommend to use a script to develop locally and migrate to cloud functions when ready.
I use Handlebars as templating language, it allows to manage vars replacement within html template.
You can see /generate-instagram-picture.js
in action running following cmd:
$ node ./scripts/generate-instagram-picture.js NSQJRipCSvxbhpPEc6lM
For devs purpose, if you need to update functions, you should compile them before using
$ npm i -g typescript
$ tsc -p functions
To avoid several deploys on dev stage, I recommend using firebase emulator
To display images from local path on puppeteer screenshots:
static images should be deployed on website
endpoint /events/[id]/insta
createInstaPicture(:id) w/ puppeteer
Resources
https://firebase.google.com/docs/functions/callable