我正在尝试使用 puppeteer 创建 PDF。创建 PDF 时设置视口(viewport)根本没有效果。但是,视口(viewport)设置确实适用于屏幕截图。过去在 github 上似乎发现了一些问题,但它们显然已被关闭。传入 defaultViewport: null 应该是解决方案。
这是我的代码:
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: null,
executablePath: await chromium.executablePath,
ignoreHTTPSErrors: true,
headless: true,
});
let page = await browser.newPage();
// Set viewport
await page.setViewport({width: 1440, height: 900, deviceScaleFactor: 2});
// Generate pdf
const doc = await page.pdf(options);
我还尝试在启动时传递视口(viewport)设置。
谢谢!
最佳答案
page.pdf
模拟“打印为 PDF”操作。这意味着两件事:首先是 media print其次是您需要将特定格式或大小传递给 pdf
函数。
来自documentation :
The
width
,height
, andmargin
options accept values labeled with units. Unlabeled values are treated as pixels.A few examples:
*page.pdf({width: 100})
- prints with width set to 100 pixels.
*page.pdf({width: '100px'})
- prints with width set to 100 pixels.
*page.pdf({width: '10cm'})
- prints with width set to 10 centimeters.All possible units are:
*px
- pixel
*in
- inch
*cm
- centimeter
*mm
- millimeterThe
format
options are:
*Letter
: 8.5in x 11in
*Legal
: 8.5in x 14in
*Tabloid
: 11in x 17in
*Ledger
: 17in x 11in
*A0
: 33.1in x 46.8in
*A1
: 23.4in x 33.1in
*A2
: 16.54in x 23.4in
*A3
: 11.7in x 16.54in
*A4
: 8.27in x 11.7in
*A5
: 5.83in x 8.27in
*A6
: 4.13in x 5.83in
关于javascript - Puppeteer 视口(viewport)设置在创建 PDF 时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59951399/