页面大小现在可以“几乎”精确控制,无需使用调试接口。
以下是使用Headless 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)
fixHeight = parseInt(renderBlockInfo.height) + 1 + "px"
pageCss = `@page { size: \${renderBlockInfo.width} \${fixHeight} ; margin:0;}`
document.getElementById("page_style").innerHTML = pageCss
}
</script>
这种方法消除了页眉/页脚,并解决了像素转换为pdf的数字问题。
还有一件事
Chrome目前存在一个bug,当您使用CSS时,计算div的绝对高度时会出现问题。
line-height: normal;
这会导致页面计算过短,从而生成额外的PDF页面。你可以使用以下方法解决:
line-height: unset;
在整个CSS中,没有使用它你将无法得到准确的高度!