如何在单张纸上打印多张演唱会门票?
解决方案
要在单张纸上打印多张门票,核心是移除循环内的AddPage()调用,改为跟踪当前绘制的Y坐标,当剩余空间不足以放下下一张门票时再新增页面,同时调整所有元素的Y坐标为相对偏移值。
修改后的代码
// 初始化参数 $ticketHeight = 107; // 单张门票的高度(和原代码中Cell高度一致) $gap = 5; // 门票之间的间隙 $startY = 10; // 页面顶部起始Y坐标 $currentY = $startY; $pageHeight = $pdf->GetPageHeight(); // 获取当前PDF页面高度 $bottomMargin = 10; // 页面底部预留边距 // 先添加第一页 $pdf->AddPage(); for($i = 0; $i < 5; $i++){ // 检查当前剩余空间是否能放下下一张门票,不够则新增页面 if($currentY + $ticketHeight > $pageHeight - $bottomMargin){ $pdf->AddPage(); $currentY = $startY; // 重置Y坐标到页面顶部 } // background - 调整Y坐标为currentY $pdf->SetAlpha($alpha); $pdf->Image('../img/banners/'.$row['banner'], 10, $currentY, 0, $ticketHeight); // draw border around image $pdf->SetAlpha(1); $pdf->SetXY(10, $currentY); $pdf->Cell(0, $ticketHeight,'',1,1, 'C'); // logo - Y坐标:currentY + 10(原位置是20,相对于起始10的偏移是10) $pdf->Image('../img/logo/logo-trans-bg.png', 20, $currentY + 10, 20, 20); // name - Y坐标:currentY + 22(原位置32-10=22) $pdf->SetFont('Courier','I',12); $pdf->Text(105 - ($pdf->GetStringWidth($row['name']) / 2), $currentY + 22, $row['name']); // price - Y坐标:currentY + 22 $pdf->SetFont('Courier','',12); $price1 = "£".$row['t1_price']; $pdf->Text(175 - ($pdf->GetStringWidth($price1) / 2), $currentY + 22, $price1); // date - Y坐标:currentY + 95(原位置105-10=95) $pdf->SetFont('Courier','B',12); $pdf->Text(155 - ($pdf->GetStringWidth($date) / 2), $currentY + 95, $date); // web address - Y坐标:currentY + 95 $pdf->SetFont('Courier','BI',12); $pdf->Text(40 - ($pdf->GetStringWidth('dwhsociety.co.uk') / 2), $currentY + 95, 'dwhsociety.co.uk'); // concert title - Y坐标:currentY + 50(原位置60-10=50) $pdf->SetFont('Courier','B',16); $pdf->Text(105 - ($pdf->GetStringWidth($row['title']) / 2), $currentY + 50, $row['title']); // Adult - Y坐标:currentY + 57(原位置67-10=57) if($row['type_1'] != '0'){ $adult = "1 ticket ".$row['t1_label']; $pdf->SetFont('Courier','',12); $pdf->Text(105 - ($pdf->GetStringWidth($adult) / 2), $currentY + 57, $adult); } // venue - Y坐标:currentY + 67(原位置77-10=67) $pdf->SetFont('Courier','',12); $pdf->Text(105 - ($pdf->GetStringWidth($row['venue']) / 2), $currentY + 67, $row['venue']); // 更新当前Y坐标,加上门票高度和间隙 $currentY += $ticketHeight + $gap; }
关键修改点
- 移除循环内的
AddPage():只在页面空间不足时才新增页面,避免每张票占一页 - 动态跟踪Y坐标:用
$currentY记录当前绘制的起始位置,每次绘制完门票后加上高度和间隙 - 相对偏移替换固定Y值:所有元素的Y坐标都改为
$currentY + 偏移量,偏移量是原固定Y值减去初始的10(原代码中第一张票的起始Y) - 空间检查逻辑:每次循环开始前判断剩余空间,确保门票不会超出页面底部
内容的提问来源于stack exchange,提问作者George Feichter
相关产品推荐
相关产品推荐

