一,环境:
操作系统:windows10 macOS12 centos7
node版本:v16.14.0 (最低12)
npm:6.14.10
puppeteer : ^13.0.1
puppeteer : https://github.com/puppeteer/puppeteer
puppeteer文档:http://www.puppeteerjs.com/
nvm管理切换多个node.js http://nvm.uihtm.com/
背景:
1, wkhtmltopdf 的截图对于页面中图片过多的场景 不友好,容生成失败,
2,不想使用上述的技术,推荐 微软的 edge 浏览器插件 fireshot (PRO版本是10天试用期)
3, wkhtmltopdf 参考: wkhtmltopdf + php
4, 参考: https://www.cnblogs.com/jiangwz/p/9890472.html
二,目录结构
1, index.js
try {
const puppeteer = require("puppeteer");
(async () => {
const timeout = 1000 * 60 * 10;
const browser = await puppeteer.launch({
timeout: timeout,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
const defParams = {
path: "test.pdf",
width: 1176,
height: 868,
left: 20,
right: 20,
printBackground: true,
timeout: timeout,
};
const siteParams = {
1: {
width: 1176,
height: 868,
},
2: {
width: 1176,
height: 868,
},
3: {
width: 1176,
height: 868,
},
4: {
width: 1176,
height: 868,
},
5: {
width: 1176,
height: 868,
},
}
const arguments = process.argv.splice(2);
const nodeParams = {
};
const params = {
};
const reg = /^--/;
for (let i = 0; i < arguments.length; i++) {
if (reg.test(arguments[i]) && !reg.test(arguments[i + 1])) {
nodeParams[arguments[i].substring(2)] = isNaN(arguments[i + 1]) ? arguments[i + 1] : Number(arguments[i + 1]);
}
}
Object.assign(params, defParams, siteParams[nodeParams.site] || {
}, nodeParams);
if (!params.url) {
console.log('Error:', '请传入页面链接 --url');
process.exit(1);
}
if (!params.path) {
console.log('Error:', '请传入保存位置 --path');
process.exit(1);
}
await page.setDefaultNavigationTimeout(params.timeout);
await page.setDefaultTimeout(params.timeout);
await page.goto(params.url, {
waitUntil: 'networkidle0' });
await page.pdf({
path: params.path,
width: params.width,
height: params.height,
margin: {
left: params.left,
right: params.right,
},
printBackground: params.printBackground
});
await browser.close();
})();
} catch (err) {
console.log('Error:', err);
process.exit(1);
}
2,package.json
{
"name": "puppeteer",
"version": "1.0.0",
"description": "pdf生成工具",
"main": "index.js",
"scripts": {
},
"author": ""