You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用Typeset.sh设置PDF图片定位及排版问题排查

问题:Typeset.sh生成PDF时首页末尾图片忽略页边距

在Laravel中通过Blade模板配合Typeset.sh生成PDF,要求所有图片固定尺寸并以网格排列。当前文档包含10张图片,8张可放入第一页、剩余2张跳转至第二页(分页逻辑正常),但第一页最后两张图片渲染时完全忽略@page规则设置的边距。已尝试break-before、break-after等分页控制属性,问题未解决。

相关代码

HTML代码

<section id="images">
    @foreach ($record->incident_images as $image)
        <div class="image">
            <img src="{{ asset('storage/' . $image) }}" />
        </div>
    @endforeach
</section>

文档配置CSS

@page {
    size: A4;
    margin: 10mm;

    @bottom-center {
        content: 'Page 'counter(page) ' of 'counter(pages);
    }
}

图片样式CSS

section#images {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 2mm;
    margin-top: 0; /* Adjust the top margin as needed */
    margin-bottom: 0; /* Adjust the bottom margin as needed */
}

.image {
    width: 100%;
    border: 1px solid black;
    break-inside: avoid; /* Ensure that each container stays together on a single page */
}

.image>img {
    width: 100%;
    height: 200vh; /* Set the image height to 50% of the viewport height */
    object-fit: cover;
}

修复方案

核心问题出在vh单位在PDF分页场景下的渲染异常,以及网格布局的精确尺寸计算缺失,以下是具体修复步骤:

  1. 替换不稳定的vh单位:
    PDF渲染中视口高度(vh)的计算在分页时会出现偏差,将图片高度改为基于A4页面可用空间的固定毫米值。A4页面上下边距10mm,可用高度为297mm - 20mm = 277mm,4行图片加3个2mm的间隙,每张图高度设为67mm((277 - 6)/4 ≈67.75,取整适配)。

  2. 添加盒模型控制避免溢出:
    给.image和section#images添加box-sizing: border-box,确保边框、内边距不会占用额外宽度,避免超出网格或页边距范围。

  3. 精确计算网格列宽:
    将grid-template-columns改为repeat(2, calc(50% - 1mm)),抵消2mm间隙带来的宽度偏移,确保两列总宽度加间隙刚好填满容器。

修改后的图片样式CSS

section#images {
    display: grid;
    grid-template-columns: repeat(2, calc(50% - 1mm));
    gap: 2mm;
    margin-top: 0;
    margin-bottom: 0;
    box-sizing: border-box;
}

.image {
    width: 100%;
    border: 1px solid black;
    break-inside: avoid;
    box-sizing: border-box;
}

.image>img {
    width: 100%;
    height: 67mm;
    object-fit: cover;
}

内容的提问来源于stack exchange,提问作者Abdulrahman Mushref

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 19:39:53