1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| <?php
namespace App\Services;
use Barryvdh\DomPDF\Facade\Pdf; use Illuminate\Support\Facades\Storage;
class PdfService { protected string $defaultPaper = 'a4'; protected string $defaultOrientation = 'portrait';
public function generate(string $view, array $data = [], array $options = []): \Barryvdh\DomPDF\PDF { $pdf = Pdf::loadView($view, $data);
if (isset($options['paper'])) { $pdf->setPaper($options['paper'], $options['orientation'] ?? $this->defaultOrientation); }
if (isset($options['header']) || isset($options['footer'])) { $this->addHeaderFooter($pdf, $options); }
return $pdf; }
public function download(string $view, array $data, string $filename, array $options = []): \Illuminate\Http\Response { return $this->generate($view, $data, $options)->download($filename); }
public function stream(string $view, array $data, string $filename, array $options = []): \Illuminate\Http\Response { return $this->generate($view, $data, $options)->stream($filename); }
public function save(string $view, array $data, string $path, array $options = []): bool { $pdf = $this->generate($view, $data, $options); $directory = dirname($path); if (!Storage::exists($directory)) { Storage::makeDirectory($directory); }
Storage::put($path, $pdf->output());
return true; }
public function generateInvoice($invoice): string { $pdf = $this->generate('pdf.invoice', [ 'invoice' => $invoice, 'company' => config('company'), ], [ 'paper' => 'a4', 'orientation' => 'portrait', ]);
$path = "invoices/{$invoice->id}/invoice.pdf"; Storage::put($path, $pdf->output());
return $path; }
public function generateReport($data): string { $pdf = $this->generate('pdf.report', [ 'data' => $data, 'generatedAt' => now(), ], [ 'paper' => 'a4', 'orientation' => 'landscape', ]);
$filename = 'report_' . now()->format('Y-m-d_His') . '.pdf'; $path = "reports/{$filename}"; Storage::put($path, $pdf->output());
return $path; }
protected function addHeaderFooter($pdf, array $options): void { $canvas = $pdf->getCanvas(); $canvas->setCallbacks([ 'event' => 'end_page', 'f' => function ($info) use ($canvas, $options) { if (isset($options['footer'])) { $canvas->page_text( $info['canvas_width'] / 2, $info['canvas_height'] - 30, $options['footer'], null, 10 ); }
$canvas->page_text( $info['canvas_width'] - 50, $info['canvas_height'] - 30, "第 {PAGE_NUM} 页", null, 10 ); }, ]); } }
|