javascript - 使用 puppeteer 配置 PDF 页面宽度
问题描述
我正在尝试使用 puppeteer 生成 pdf,但生成的 pdf 宽度很大。我想要一个 pdf,它在一页中显示所有内容,并且宽度必须为 4.8 厘米,其中页面高度可以是其内容的任何长度。
我在pdf中添加了配置
{
path : filePath,
printBackground : true,
width : '4.8cm'
}
在页面中,我将配置添加到视口
{
width : 136,
height : 842,
deviceScaleFactor : 1
}
但最终结果并没有改变
解决方案
试试这个代码,并选择这个答案是正确的,如果它工作得很好。
我在方法中设置了缩放选项,page.pdf
以将原始打印的 PDF 缩放为缩放版本。所以这使得整页只适合一页。
const puppeteer = require('puppeteer')
const pageURL = 'https://stackoverflow.com/questions/59464250/configure-pdf-page-width-using-puppeteer'
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()
})()
推荐阅读
- c++ - 开始执行 GLEW 代码之前的运行时错误
- sql-server - 为什么 T-SQL 命令“Select ~ (tilde) 0”给出“-1”
- java - 如何让只有一个选择在吐司上脱颖而出?
- amazon-sagemaker - 如何修改 SageMaker 自定义模板 iFrame 的属性?
- go - OPC UA - 此会话没有可用的订阅。StatusBadNoSubscription (0x80790000)
- tensorflow - 在 Python 程序中的 Cluster 上部署 TF Serving 模型
- c# - 使用 Moq 用一些默认值填充属性
- numpy - 如何提取特定像素位置的地理坐标?
- node.js - 在 mocha 中,我无法使用不同的参数异步进行多个 API 调用
- recaptcha - 如何注册 reCAPTCHA V2 而不是 Enterprise