基于browserless 以及puppeteer 我们可以快速的进行屏幕捕捉生成图片以及导出pdf 文件,以下是一个简单的试用
环境准备
- docker-compose
version: "3"
services:
app:
image: browserless/chrome:latest
ports:
- "3000:3000"
- node app
package.json 基于express 的web 服务,同时使用了ncc 进行打包
{
"name": "appv2",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"express": "^4.19.2",
"puppeteer-core": "^22.6.5"
},
"scripts": {
"dev":"node index.js",
"build": "ncc build index.js -o dist"
},
"devDependencies": {
"@vercel/ncc": "^0.38.1"
}
}
index.js
包含一个image 以及pdf 的get 服务,我们需要传递的是website 查询字符串
const express = require("express");
const puppeteer = require("puppeteer-core");
const app = express();
const browserWSEndpoint = process.env.ENDPOINT || "ws://localhost:3000";
const getBrowser = async () => puppeteer.connect({ browserWSEndpoint });
app.get("/image", async (req, res) => {
let browser_local = null;
const website = req.query.website;
await getBrowser()
.then(async (browser) => {
browser_local = browser
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 1024 });
await page.goto(website,{
waitUntil: ["load",'networkidle0'],
});
const screenshot = await page.screenshot({
fullPage: true,
captureBeyondViewport: true,
});
res.end(screenshot, "binary");
})
.catch((error) => {
if (!res.headersSent) {
res.status(400).send(error.message);
}
})
.finally(() => browser_local && browser_local.close());
});
app.get("/pdf", async (req, res) => {
let browser_local = null;
const website = req.query.website;
await getBrowser()
.then(async (browser) => {
browser_local = browser
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 1024 });
await page.goto(website,{
waitUntil: ["load",'networkidle0'],
});
const screenshot = await page.pdf({
displayHeaderFooter: true,
format: "A4",
printBackground: true,
});
res.end(screenshot, "binary");
})
.catch((error) => {
if (!res.headersSent) {
res.status(400).send(error.message);
}
})
.finally(() => browser_local && browser_local.close());
});
app.listen(8080, () => console.log("Listening on PORT: 8080"));
- 效果
图片的
pdf 文件
说明
使用好browserless 可以做不少有意思的东西,值得尝试下
参考资料
https://pptr.dev/api/puppeteer.page.screenshot
https://pptr.dev/api/puppeteer.page.pdf
https://www.browserless.io/
https://github.com/browserless/browserless