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

如何在Laravel-dompdf中通过脚本绘制PDF对角线

在 Laravel Dompdf 中高效绘制大量对角线

针对你大量绘制对角线的需求,推荐两种比 CSS rotate 更高效的实现方式:

方案一:内联 SVG(视图层面实现,无需修改控制器)

Dompdf 支持内联 SVG,直接在单元格中嵌入 SVG 绘制线条,稳定性和性能优于 CSS 旋转,适合批量场景。

修改 test.blade.php 的表头单元格:

<tr>
    <th style="width: 60px; height: 40px; position: relative;">
        <!-- 内联SVG绘制左上角到右下角的对角线 -->
        <svg width="100%" height="100%" viewBox="0 0 60 40" style="position: absolute; top: 0; left: 0;">
            <line x1="0" y1="0" x2="60" y2="40" stroke="#000" stroke-width="1"/>
        </svg>
    </th>
    <th>Name</th>
    <th>TEL</th>
</tr>
  • 调整 width/height 匹配单元格尺寸,修改 x1,y1,x2,y2 可切换对角线方向(比如右上角到左下角设为 x1=60,y1=0,x2=0,y2=40)
  • 可通过 stroke 属性修改线条颜色,stroke-width 调整线条粗细

方案二:Dompdf 底层 PDF 回调(控制器层面实现,性能最优)

如果需要绘制极大量对角线,直接操作 Dompdf 底层 PDF 对象能避免前端渲染开销,效率最高。

修改控制器代码:

public function downloadPDF () {
    $pdf = PDF::loadView('test', [
        'users' => $users //$users is array
    ])->setPaper('a4', 'portrait');

    // 先渲染视图,获取DOM元素位置
    $pdf->render();
    $dom = $pdf->getDom();
    $canvas = $pdf->getCanvas();

    // 定位目标单元格(需给单元格加id)
    $targetCell = $dom->getElementById('diagonal-cell');
    if ($targetCell) {
        $cellBox = $targetCell->getBoundingBox();
        // 绘制对角线
        $canvas->line(
            $cellBox->getLeft(), $cellBox->getTop(),
            $cellBox->getRight(), $cellBox->getBottom(),
            ['color' => [0, 0, 0], 'width' => 1]
        );
    }

    // 若需批量绘制,可遍历带指定class的单元格
    // $cells = $dom->getElementsByClassName('need-diagonal');
    // foreach($cells as $cell) { ... }

    return $pdf->download("test.pdf");
}

同步修改视图,给目标单元格添加 id:

<tr>
    <th id="diagonal-cell"></th>
    <th>Name</th>
    <th>TEL</th>
</tr>
  • 通过 getBoundingBox() 获取单元格的精确坐标,直接调用 PDF 画布的 line 方法绘制
  • 批量绘制时,可给所有需要对角线的单元格加统一 class,遍历处理即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:25:21