ispt4.0_laravel/app/Services/PdfWrapper.php

90 lines
2.1 KiB
PHP

<?php
namespace App\Services;
use Spatie\Browsershot\Browsershot;
use Illuminate\Http\Response;
class PdfWrapper {
protected Browsershot $pdfGenerator;
protected string $html;
protected string $headerHtml;
protected string $footerHtml;
public function __construct() {
$this->pdfGenerator = new Browsershot();
$this->headerHtml = view('projectsClients.pdf._header')->render();
$this->footerHtml = view('projectsClients.pdf._footer')->render();
}
//Load views
public function loadView(string $bladeFile, array $data = []): self {
$this -> html = view($bladeFile, $data)->render();
return $this;
}
//Load HTML
public function loadHtml(string $html): self {
$this -> html = $html;
return $this;
}
public function loadUrl(string $url): self {
$this -> html = url($url);
return $this;
}
//Function to generate PDFs
public function generate(): Browsershot {
return $this->pdfGenerator
->html($this->html)
->format('A4')
->margins(10, 20, 10, 20)
->showBrowserHeaderAndFooter()
->headerHtml($this->headerHtml)
->footerHtml($this->footerHtml)
->waitUntilNetworkIdle();
}
//Function to save to server in public folder
public function save(string $path): void {
$this->generate()->savePdf($path);
}
//Function to save the PDF to client with specific filename
public function download(string $filename) {
$pdf = $this->generate()->pdf();
return new Response($pdf, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
'Content-Length' => strlen($pdf)
]);
}
//Function to view PDF in browser
public function stream(string $filename) {
$pdf = $this->generate()->pdf();
return new Response($pdf, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);
}
}