页面大小显然现在可以“几乎”准确控制,而无需使用调试界面。
以下是使用无头 chrome 创建其内容的几乎精确尺寸的 PDF 的方法。
<head>
<style>
html, body {
width: fit-content;
height: fit-content;
margin: 0px;
padding: 0px;
}
</style>
<style id=page_style>
@page { size: 100px 100px ; margin : 0px }
</style>
</head>
这准备使 pdf 适合页面,但不正确,因为页面大小已设置为 100x100 的任意值。
呈现文档后,以下内容用于在页面底部正确设置页面大小:
<script>
window.onload(fixpage);
function fixpage() {
renderBlock = document.getElementsByTagName("html")[0];
renderBlockInfo = window.getComputedStyle(renderBlock)
// fix chrome page bug
fixHeight = parseInt(renderBlockInfo.height) + 1 + "px"
pageCss = `@page { size: \${renderBlockInfo.width} \${fixHeight} ; margin:0;}`
document.getElementById("page_style").innerHTML = pageCss
}
</script>
这种方法消除了页眉/页脚,并处理了将像素转换为 pdf 的数字问题。
还有一件事
Chrome 目前在使用 CSS 时计算 div 的绝对高度存在错误
line-height: normal;
这会使页面计算太短,并导致生成额外的 pdf 页面。您可以使用以下方法解决此问题:
line-height: unset;
贯穿你的 CSS。没有它,您将无法获得准确的高度!