CaiWuXiTong/app/Support/CourierQuotePdf.php

47 lines
1.3 KiB
PHP

<?php
namespace App\Support;
use App\Models\Business\CourierQuoteVersion;
use RuntimeException;
final class CourierQuotePdf
{
public function render(CourierQuoteVersion $version): string
{
$version->loadMissing(['change.items']);
$values = $this->decodeMatrix($version->values_json);
$formulas = $this->decodeMatrix($version->formulas_json);
$html = view('business.pdf.courier-quote', [
'version' => $version,
'change' => $version->change,
'values' => $values,
'formulas' => $formulas,
'generatedAt' => now(),
'fontPath' => str_replace('\\', '/', resource_path('fonts/DroidSansFallback.ttf')),
])->render();
$pdf = app('dompdf.wrapper');
$pdf->setPaper('a4', 'landscape');
$pdf->loadHTML($html, 'UTF-8');
$bytes = $pdf->output();
if (! is_string($bytes) || ! str_starts_with($bytes, '%PDF-')) {
throw new RuntimeException('报价 PDF 生成失败。');
}
return $bytes;
}
private function decodeMatrix(?string $json): array
{
if (blank($json)) {
return [];
}
$decoded = json_decode($json, true);
return is_array($decoded) ? $decoded : [];
}
}