1.安装chrome依赖
apt install -y libglib2.0-dev libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm-dev libpango1.0-0 libasound2 libxshmfence1 libxkbcommon0 libcairo2
2.安装node,不要使用apt-get,安装不是最新版本
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - # -s参数将不输出错误和进度信息;-L参数会让 HTTP 请求跟随服务器的重定向。curl 默认不跟随重定向。
sudo apt-get install -y nodejs
3.安装 puppeteer
npm install -g puppeteer --unsafe-perm=true # 要加--unsafe-perm=true否则会提示权限不足
4.安装chromium-browser
sudo apt-get install chromium-browser
5.安装中文字体
sudo apt-get install -y fontconfig #安装字体配置工具(fontconfig)
fc-list :lang=zh #查看目前已安装的中文字体
#直接把windows系统里已有的字体传到linux服务器
/usr/share/fonts/
#更新字体库
sudo mkfontscale
sudo mkfontdir
6.设置浏览器路径
/**
* 用node demo.js 'http://localhost:8081/#/printTemp'(需要打印的网页地址) 命令运行此文件即可生成PDF
* options里面可以取到命令调用时传过来的参数
*/
const sleep = time => new Promise(resolve => {
setTimeout(resolve, time);
})
const puppeteer = require("puppeteer");
const options = process.argv;
var address;
var filename;
var endid;
(async () => {
if (options.length >= 3) {
address = options[2];
filename = options[3];
endid = options[4]
}
endid = ""
if (options.length >= 4) {
endid = options[4]
}
console.log(options);
const browser = await puppeteer.launch({args:['--disable-gpu', '--disable-setuid-sandbox', '--no-sandbox', '--no-zygote' ], executablePath:'/usr/bin/chromium-browser'});
const page = await browser.newPage();
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at: Promise', p, 'reason:', reason);
browser.close();
});
await page.emulate(puppeteer.devices['iPhone 6']);
// await page.on('ready', () => console.log('Page loaded!'));
await page.goto(
address, //
{
waitUntil: "networkidle0",
timeout: 1000 * 60 * 20
}
);
if (endid == '') {
try{
await page.waitForSelector(endid, {
polling: 1000,
timeout: 3 * 1000,
});
}catch(e){
//TODO handle the exception
}
} else {
await page.waitForSelector(endid, {
polling: 120,
timeout: 2 * 60 * 1000,
});
}
await page.pdf({
path: filename,
format: "a4",
margin: {
top: 30,
bottom: 0,
left: 30,
right: 30
},
preferCSSPageSize: true,
printBackground: true,
"-webkit-print-color-adjust": "exact",
});
await browser.close();
})();