我想把整页的PDF分成两个半页,而且不留任何多余的空白
public function commerceProcess(Request $request)
{
$request->validate([
'files.*' => 'required|mimes:pdf|max:20480',
]);
$files = $request->file('files');
if ($request->has('merge')) {
return $this->mergePdf($files);
}
if ($request->has('keepInvoice')) {
return $this->keepInvoice($request, $files);
}
}
// === keep invoice ===
private function keepInvoice($request, $files)
{
$pdf = new Fpdi();
$file = $files[0];
$path = $file->getRealPath();
$pageCount = $pdf->setSourceFile($path);
for ($page = 1; $page <= $pageCount; $page++) {
$tplId = $pdf->importPage($page);
$size = $pdf->getTemplateSize($tplId);
$splitY = 123;
// Top page
$pdf->AddPage($size['orientation'], [$size['width'], ($size['height'])]);
$pdf->useTemplate($tplId, 0, 0, $size['width']);
$pdf->SetFillColor(255, 255, 255); // white
$pdf->Rect(0, $splitY, $size['width'], $size['height'], 'F');
// Bottom page
$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
$pdf->useTemplate($tplId, 0, -$splitY, $size['width'], $size['height']);
$pdf->Rect(0, $splitY, $size['width'], $size['height'], 'F');
}
return response($pdf->Output('keepInvoice.pdf', 'S'))
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'inline; filename="keepInvoice.pdf"');
}
我正在使用“Keep Invoice”把一个PDF页面分成两页。目前,生成的两页都是全尺寸的,只能看到原始内容的一半,另一半是空白的。
我希望每一页输出只包含原始页面的一半内容(上半部和下半部),这样就不会有空白区域,并且每一页的大小正好是半页的内容。
这个工具用于PDF排序。如何在不出现空白区域的情况下实现正确的半页分割?
我有一整页PDF,包含客户信息和税务发票。我想把它拆成两张单独的页面——上半部分用于客户信息,下半部分用于税务发票。
所以基本上,我想把整页PDF分成两张半尺寸的页面。
现在,页面已经分离,但每个输出页仍然是全尺寸,而不是半尺寸。因此,每页的一半区域仍然是空白。
我希望每一页的尺寸能够恰当地只显示原始内容的一半,没有任何空白区域。
解决方案
你需要将新页面的尺寸定义为高度的一半(更准确地说,是你 $splitY的高度),以实现干净的分割。然后,在放置模板时,必须改变坐标系,使下半部“滑入”视野。
你应创建一个只与要保留的内容同高的页面,而不是添加一个全尺寸页面然后在底部绘制一个白色框。
private function keepInvoice($request, $files)
{
$pdf = new Fpdi();
$file = $files[0];
$path = $file->getRealPath();
$pageCount = $pdf->setSourceFile($path);
for ($page = 1; $page <= $pageCount; $page++) {
$tplId = $pdf->importPage($page);
$size = $pdf->getTemplateSize($tplId);
// Define your split point
$splitY = 123;
$remainingHeight = $size['height'] - $splitY;
// --- TOP HALF (Customer Info) ---
// Create a page with the width of the original and height of $splitY
$pdf->AddPage($size['orientation'], [$size['width'], $splitY]);
// Place the template at (0,0). Fpdi will clip anything outside the page boundary.
$pdf->useTemplate($tplId, 0, 0, $size['width']);
// --- BOTTOM HALF (Tax Invoice) ---
// Create a page with the remaining height
$pdf->AddPage($size['orientation'], [$size['width'], $remainingHeight]);
// Shift the template UP by $splitY so the bottom half starts at the top of this page
$pdf->useTemplate($tplId, 0, -$splitY, $size['width']);
}
return response($pdf->Output('keepInvoice.pdf', 'S'))
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'inline; filename="keepInvoice.pdf"');
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。