Last active
November 29, 2021 05:46
-
-
Save yangyang5214/0bf1884e06ec9e3443b1a16f2795c873 to your computer and use it in GitHub Desktop.
[puppeteer pdf] 浏览器实现 pdf 导出 #puppeteer #nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
'use strict'; | |
const puppeteer = require("puppeteer"); | |
(async () => { | |
let url = 'https://xxxx.com' | |
const browser = await puppeteer.launch({ | |
args: [ | |
'--start-maximized', | |
'--no-sandbox', | |
'--remote-debugging-address=0.0.0.0', | |
'--remote-debugging-port=0', | |
'--enable-automation', | |
'--disable-setuid-sandbox' | |
], | |
ignoreHTTPSErrors: true, | |
headless: true, | |
defaultViewport: { | |
width: 1920, | |
height: 1080, | |
deviceScaleFactor: 1, | |
isMobile: false, | |
hasTouch: false, | |
isLandscape: false | |
} | |
}); | |
let newPage = await browser.newPage(); | |
await newPage.goto(url, { | |
waitUntil: 'networkidle0' | |
}).catch(error => { | |
console.log(`error: ${error.message}`) | |
process.exit(-1) | |
}); | |
//for body.style.height missed. 高度是通过 Api 数据异步填充的 | |
let height = await newPage.evaluate('document.body.scrollHeight') | |
await newPage.evaluate(`document.body.style.height = "${height}px"`) | |
await newPage.pdf({ | |
format: 'A4', | |
scale: 1, | |
printBackground: true, | |
margin: { | |
top: 30, | |
bottom: 50, | |
}, | |
path: '/tmp/result.pdf' | |
}); | |
await browser.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment