pdf转换puppeteer设置
# pdf属性设置
# 参数配置
await webPage.pdf({
//displayHeaderFooter: true,
printBackground: true,
path: "webpage.pdf",
format: "Letter",
margin: {
top: "20px",
bottom: "40px",
left: "20px",
right: "20px"
}
});
await browser.close();
2
3
4
5
6
7
8
9
10
11
12
13
Here are some of the options we used:
printBackground
: When this option is set totrue
, Puppeteer prints any background colors or images you have used on the web page to the PDF.path
: This specifies where to save the generated PDF file. You can also store it into a memory stream to avoid writing to disk.format
: You can set the PDF format to one of the given options:Letter
,A4
,A3
,A2
, etc.margin
: You can specify a margin for the generated PDF with this option.scale – scale of the webpage rendering. Scale amount must be between 0.1 and 2 (defaults to 1).
landscape – page orientation: false – vertical, true – horizontal (default is false)
format – paper format ( default to Letter). Possible values (all sizes are indicated in inches):
- Letter: 8.5 x 11
- Legal: 8.5 x 14
- Tabloid: 11 x 17
- Ledger: 17 x 11
- A0: 33.1 x 46.8
- A1: 23.4 x 33.1
- A2: 16.54 x 23.4
- A3: 11.7 x 16.54
- A4: 8.27 x 11.7
- A5: 5.83 x 8.27
- A6: 4.13 x 5.83
width – paper width
height – paper heigth
margin– paper margins (default to none):
- top – top margin
- bottom – bottom margin
- left – left margin
- righht – righnt margin
# 大小缩小设置
目前设置format对应为A0,设置缩小比例;而不是设置scale设置;
const pdf = await renderer.pdf(url, {
...pdfOptions,
printBackground: true,
preferCSSPageSize: true,
'-webkit-print-color-adjust': 'exact',
'format':'A0',
})
2
3
4
5
6
7
# 页眉/脚设置
这个对应页面要设置A4,再设置页脚,及背景设置也要一致;
const headerTemplate = `<div style="width:90%;margin:0 auto;font-size:8px;border-bottom:1px solid #ddd;padding:5px 0;display: flex; justify-content: space-between;"><span>我是页眉</span></div>`
const footerTemplate = `<div style="width:90%;margin:0 auto;font-size:8px;border-top:1px solid #ddd;padding:5px 0;display: flex; justify-content: space-between; ">
<span style="">我是页脚</span>
<div><span class="pageNumber"></span> / <span class="totalPages"></span></div>
</div>`;
const pdf = await renderer.pdf(url, {
...pdfOptions,
printBackground: true,
preferCSSPageSize: true,
'-webkit-print-color-adjust': 'exact',
'format':'A4',
displayHeaderFooter: true,
// headerTemplate,
footerTemplate,
margin: {bottom: 80},
// margin: {top: 80, bottom: 80},
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 参考链接
- https://pptr.dev/api/puppeteer.pdfoptions
- https://pocketadmin.tech/en/puppeteer-generate-pdf/