我正在尝试用Puppeter生成pdf。我想要的是生成的pdf文件应该只有一页。这个单独的页面包含了网页的所有内容。
以下是我的代码,它是从https://github.com/puppeteer/puppeteer/issues/5590#issuecomment-747638812
但它并没有像预期的那样起作用。
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: true,
defaultViewport: {
width: 1024,
height: 800,
},
args: [
'--no-sandbox',
'--disable-gpu',
'--hide-scrollbars',
'--start-fullscreen',
]
});
const page = await browser.newPage();
await page.goto('https://www.w3schools.com/', {
waitUntil: 'networkidle0',
});
await page.emulateMediaType('screen');
const totalPage = await page.$('html');
const boundingBox = await totalPage.boundingBox();
console.log(boundingBox);
await page.pdf({
path: 'w3schools.pdf',
printBackground: true,
width: '1024px',
height: `${boundingBox.height + 20}px`,
});
await browser.close();
})();
根据我的经验,更干净的方法是使用page.eval()
来获取文档的高度,并将其作为选项传递给page.pdf()
const puppeteer = require('puppeteer');
const docHeight = () => {
const body = document.body
const html = document.documentElement;
return Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
}
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://en.wikipedia.org/wiki/JavaScript");
const height = await page.evaluate(docHeight);
await page.pdf({path: `js.pdf`, height: `${height}px`})
})();