使用barryvdh/laravel-dompdf生成小尺寸PDF:适配单页方案咨询
解决dompdf生成小尺寸PDF内容分多页的问题
针对你遇到的45mm×30mm(对应dompdf的127×85点)条码PDF分三页的问题,可以从以下几个方面调整:
1. 重置HTML默认样式,消除冗余边距
dompdf基于HTML/CSS渲染,浏览器默认样式(比如body的margin、padding)会占用纸张空间,直接导致内容溢出分页。给HTML添加基础样式重置:
$pdf->loadHtml(' <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { width: 127px; height: 85px; font-size: 8px; line-height: 1.2; } img { max-width: 100%; height: auto; display: block; margin: 0 auto; } .code-text { text-align: center; display: block; margin: 2px 0; } .product-text { text-align: center; display: block; word-break: break-all; } </style> <img src="data:image/png;base64,' . base64_encode($barcode) . '"> <span class="code-text">' . $code . '</span> <span class="product-text">' . $product->name . '(' . $brand->name . ')</span> ');
2. 明确设置纸张边距为0
默认的页面边距会挤占小尺寸纸张的可用空间,需手动将边距设为0:
$options = new Options([ 'dpi' => 200, 'defaultPaperSize' => 'custom', ]); $pdf = new Dompdf($options); $pdf->setPaper([0, 0, 127, 85], 'portrait'); $pdf->setMargins(0, 0, 0); // 上下左右边距全设为0
3. 控制内容尺寸避免溢出
- 若条码图片过大,通过CSS限制最大高度,预留文字空间:
img { max-height: 50px; max-width: 100%; height: auto; } - 调整字体大小和行高,确保产品名称、品牌名等文本换行后总高度不超过纸张高度(85点)。
将以上调整结合后,所有内容即可适配至单页45mm×30mm的PDF中。
内容的提问来源于stack exchange,提问作者sajadsholi
相关产品推荐
相关产品推荐

