ispt4.0_laravel/app/Services/PdfWrapper.php
2024-12-09 08:21:37 +00:00

107 lines
2.9 KiB
PHP

<?php
namespace App\Services;
use Spatie\Browsershot\Browsershot;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\File;
class PdfWrapper
{
protected Browsershot $pdfGenerator;
protected string $html;
protected $orientation = 'portrait';
public function __construct()
{
$this->pdfGenerator = new Browsershot();
}
// Método para configurar a orientação (paisagem ou retrato)
public function setOrientation($orientation): self
{
$this->orientation = $orientation;
return $this;
}
// Load view and render HTML
public function loadView(string $bladeFile, array $data = []): self
{
// Convert image paths to base64
if (isset($data['imagePaths']) && is_array($data['imagePaths'])) {
$data['imagesBase64'] = array_map(function($path) {
return $this->getImageBase64($path);
}, $data['imagePaths']);
}
$this->html = view($bladeFile, $data)->render();
return $this;
}
// Load raw HTML
public function loadHtml(string $html): self
{
$this->html = $html;
return $this;
}
// Load HTML from a URL
public function loadUrl(string $url): self
{
$this->html = file_get_contents(url($url));
return $this;
}
// Generate the PDF using Browsershot
public function generate(): Browsershot
{
return $this->pdfGenerator
->html($this->html)
->format('A4')
->landscape($this->orientation === 'landscape') // Verifica se deve ser paisagem
->scale(0.7)
->fullPage()
->setOption('printBackground', true)
->showBackground()
->waitUntilNetworkIdle();
}
// Save the PDF to the server in the public folder
public function save(string $path): void
{
$this->generate()->savePdf($path);
}
// Download the PDF with a specified 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)
]);
}
// Stream the PDF in the browser
public function stream(string $filename)
{
$pdf = $this->generate()->pdf();
return new Response($pdf, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);
}
// Function to convert image to base64
protected function getImageBase64($imagePath)
{
$path = public_path($imagePath);
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = File::get($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
}