Record your life!
Dashboard
My Blogs
← Back to List
Create Blog
Title
Type
Diary
Blog
Category
HTML, CSS
Content
Edit
Preview
最近接到一个需求,要把html生成pdf,生成月报周报。 平时写html很顺手,把html转成pdf,原来就以为是在浏览器里`ctrl+p`,然后选择保存成pdf就能搞定的, 实际上会遇到这样几个问题(我把解决方案一并写在这里了) - Table的某一行如果跨页了,新的一页不会显示表头,这样用户容易失去上下文,解决方案是 ``` thead { display: table-header-group; /* ✅ 关键,让表头在跨页时重复 */ } tfoot { display: table-footer-group; /* 跨页表尾重复 */ } tbody { display: table-row-group; /* 默认即可 */ } /* 可选:避免行被拆开 */ tr { page-break-inside: avoid; } ``` - 页脚,页眉不展示。这个问题很复杂,因为我们用的是gotenberg这个工具,查了好久发现工具本身不支持复杂的页脚页眉,只支持简单的文字。 如果需要把某个html元素设置成页脚页眉,需要用其他付费的软件。目前他支持的如下 ``` @bottom-right { content: "Page " counter(page) " of " counter(pages); font-size: 14px; font-weight: 500; color: #18181b; margin-right: 20px; margin-bottom: 16px; position: relative; z-index: 1000; } ``` - pdf打印的时候,会有一个默认的外边距,大约10mm左右,如果css里再对页面设置了margin或者padding,会发现空间不够用,一个好的做法是 ``` @page { size: A4; margin: 0; // 左右边距不设置,使用css里的 margin-top: 15mm; //上下边距保持一点没关系 margin-bottom: 15mm; } ``` - Gotenberg使用的方法 ``` curl \ --request POST 'http://localhost:3005/forms/chromium/convert/html?marginLeft=0cm&marginRight=0cm' \ --form files=@dist/index.html \ -o dist/index.pdf ```
Update