我目前正在尝试查看是否有一种方法可以删除我的 puppeteer PDF 中的分页符,因为我当前的 PDF 设置中的一些分页符正在以一种奇怪的方式切断文本。我所说的截图:
我的木偶代码:
app.get("/:companyId/pdf", (req, res) => {
(async () => {
try {
const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
const page = await browser.newPage();
const url =
process.env.WEBSITE_URL + `/${req.params.companyId}/report-internal`;
await page.goto(url, { waitUntil: "networkidle0" });
const buffer = await page.pdf({ format: "A4", printBackground: true });
res.type("application/pdf");
res.send(buffer);
browser.close();
} catch (error) {
console.error(error);
res.status(500).send("PDF cannot be generated.");
}
})();
});
是否可以使用 Puppeteer 生成一份长的、连续的 PDF?那将是理想的。我尝试设置自定义 CSS 打印样式以防止某些元素后分页,但到目前为止,我还没有任何运气。非常感谢任何帮助。
编辑:我找到了一个临时修复程序,它不是最漂亮的,但有效。我必须在 page.pdf 函数中手动定义文档的宽度和高度,如下所示:
const buffer = await page.pdf({ printBackground: true, width: 800, height: 3800 });
如果有更好的解决方案,那就太好了。但万一有人偶然发现这个,这对我有用。
我尝试了一种替代方法来检测滚动元素,以便您的页面在打印为 PDF 时不会被切断,我希望这能如您所愿:
const puppeteer = require('puppeteer')
const url = 'https://en.wikipedia.org/wiki/COVID-19_pandemic'
;(async () => {
const browser = await puppeteer.launch({
headless: true,
defaultViewport: {
width: 1280,
height: 800
},
userDataDir: './temp'
})
const [page] = await browser.pages()
const pageResponse = await page.goto(url)
const scrollDimension = await page.evaluate( () => {
return {
width: document.scrollingElement.scrollWidth,
height: document.scrollingElement.scrollHeight
}
})
// const viewportSize = await page.evaluate( () => {
// return {
// width: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0),
// height: Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
// }
// })
await page.setViewport({
width: scrollDimension.width,
height: scrollDimension.height
})
const bufferPDF = await page.pdf({
path: 'long.pdf',
printBackground: true,
width: scrollDimension.width,
height: scrollDimension.height
})
const exit = await browser.close()
})()