Rat*_*teM 5 javascript node.js puppeteer
我正在尝试使用 puppeteer 生成 pdf,但生成的 pdf 宽度很大。我想要一个 pdf 文件,它在一页中显示所有内容,并且宽度必须为 4.8 厘米,其中页面高度可以是其内容的任何长度。
我在pdf中添加了配置
{
path : filePath,
printBackground : true,
width : '4.8cm'
}
Run Code Online (Sandbox Code Playgroud)
到页面我将配置添加到视口
{
width : 136,
height : 842,
deviceScaleFactor : 1
}
Run Code Online (Sandbox Code Playgroud)
但最终的结果并没有改变
尝试此代码,如果效果完美,请选择正确的答案。
我在方法中设置了缩放选项,page.pdf将原始打印的 PDF 缩放为缩放后的版本。所以这使得整个页面只适合一页。
const puppeteer = require('puppeteer')
const pageURL = '/sf/ask/4162497531/'
const optionsPDF = {
path: 'print.pdf',
printBackground: true,
width: '4.8cm',
scale: 1,
preferCSSPageSize: false
}
;(async () => {
const browser = await puppeteer.launch({
headless: true,
devtools: false,
defaultViewport: {
width : 136,
height : 842,
deviceScaleFactor : 1
}
})
const [page] = await browser.pages()
await page.emulateMedia('screen')
await page.goto( pageURL, { waitUntil: 'networkidle0', timeout: 0 })
const height_weight_ratio = await page.evaluate( () => window.innerHeight / window.innerWidth)
const height = parseInt(optionsPDF.width) * height_weight_ratio
optionsPDF.scale = 1/height_weight_ratio
console.log('Printing PDF...')
await page.pdf(optionsPDF)
await browser.close()
})()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14344 次 |
| 最近记录: |