尝试隐藏由Puppeteer生成的PDF上的第一个页脚/页眉 [英] Trying to hide first footer/header on PDF generated with Puppeteer
问题描述
我是使用nodejs函数和puppeteer的新手.以前我使用wkhtmltopdf,但目前它的选项非常差.
Im new using nodejs functions and also puppeteer. Previously I was using wkhtmltopdf but currently its options are very poor.
所以,我的想法是从带有第一封面的html生成pdf(具有全A4宽度/高度的图像),因为页脚是从index.js生成的,所以无法在FIRST上将其隐藏PDF页面.
So, my idea was generating a pdf from a html with a first cover page (an image with full A4 width/height ), since the footer is generated from the index.js, theres no way to hide it on the FIRST page of the PDF.
//Imports
const puppeteer = require('puppeteer');
//Open browser
async function startBrowser() {
const browser = await puppeteer.launch({headless: true, args:['--no-sandbox']});
const page = await browser.newPage();
return {browser, page};
}
//Close browser
async function closeBrowser(browser) {
return browser.close();
}
//Html to pdf
async function html2pdf(url) {
const {browser, page} = await startBrowser();
await page.goto(url, {waitUntil: 'networkidle2'});
await page.emulateMedia('screen');
//Options
await page.pdf({
printBackground: true,
path: 'result.pdf',
displayHeaderFooter: true,
footerTemplate: '<div style="width:100%;text-align:right;position:relative;top:10px;right:10px;"><img width="60px" src="data:data:image/..."'
margin : {top: '0px',right: '0px',bottom: '40px',left: '0px' },
scale: 1,
landscape: false,
format: 'A4',
pageRanges: ""
});
}
//Exec
(async () => {
await html2pdf('file:///loc/node_pdfs/givenhtml.html');
process.exit(1);
})();
我的问题是,有什么方法可以找到第一个页脚并将其隐藏在索引功能之外?
My question is, is there any way to locate the first footer and hide it from the index fuction?
谢谢!
推荐答案
当前存在多个错误(请参见此问题/答案或这),导致无法正常工作.
There are currently multiple bugs (see this question/answer or this one) that make it impossible to get this working.
当前仅适用于使用此技巧的标头(取自此 github评论):
This is currently only possible for headers using this trick (taken from this github comment):
await page.addStyleTag({
content: `
body { margin-top: 1cm; }
@page:first { margin-top: 0; }
`,
});
这基本上将在第一页上隐藏页边距,但在使用底部页边距时将不起作用(也请注意
This will basically hide the margin on the first page, but will not work when using a bottom margin (as also noted here).
我建议的解决方案是创建两个PDF,一个PDF仅具有第一页且没有空白,而另一个则具有剩余的页面并具有空白:
The solution I recommend is to create two PDFs, one with only the first page and no margins, and another one with the remaining pages and a margin:
await page.pdf({
displayHeaderFooter: false,
pageRanges: '1',
path: 'page1.pdf',
});
await page.pdf({
displayHeaderFooter: true,
footerTemplate: '<div style="font-size:5mm;">Your footer text</div>',
margin: {
bottom: '10mm'
},
pageRanges: '2-', // start this PDF at page 2
path: 'remaining-pages.pdf',
});
Depending on how often you need to perform the task you could either manually merge the PDFs or automate it using a tool like easy-pdf-merge (I have not used this one myself).
这篇关于尝试隐藏由Puppeteer生成的PDF上的第一个页脚/页眉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!