Skip to content

Instantly share code, notes, and snippets.

@mathieutu
Created March 26, 2026 16:02
Show Gist options
  • Select an option

  • Save mathieutu/8104d3787f38fd0af46577bf1e70e699 to your computer and use it in GitHub Desktop.

Select an option

Save mathieutu/8104d3787f38fd0af46577bf1e70e699 to your computer and use it in GitHub Desktop.
Générateur PDF pour Laravel qui utilise pdf.mathieutu.dev
<?php
declare(strict_types=1);
namespace App\Services;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
readonly class PdfGenerator implements Responsable
{
private string $apiUrl;
private string $html;
private Collection $merge;
private string $document;
public function __construct()
{
$this->apiUrl = config('services.pdf.api_url');
}
public function view(string $name, array $data = []): self
{
$this->html = view($name, $data)->toHtml();
return $this;
}
public function html(string $html): self
{
$this->html = $html;
return $this;
}
public function merge(iterable $pdfsUrl): self
{
$this->merge = collect($pdfsUrl);
return $this;
}
public function getDocument(): string
{
if (! isset($this->document)) {
$response = Http::post($this->apiUrl, [
'html' => $this->html,
'merge' => $this->merge ?? null,
]);
if ($response->failed()) {
throw new RuntimeException("Failed to generate PDF: {$response->body()}");
}
$this->document = $response->body();
}
return $this->document;
}
public function inlineResponse(string $filename = ''): Response
{
return new Response($this->getDocument(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => "inline; filename=\"{$filename}\"",
]);
}
public function downloadResponse(string $filename = ''): Response
{
return new Response($this->getDocument(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => "attachment; filename=\"{$filename}\"",
]);
}
public function save(string $path, ?string $fileName = null): string
{
$filename ??= Str::random(40).'.pdf';
$path = mb_rtrim($path, '/').'/'.$filename;
Storage::put($path, $this->getDocument());
return $path;
}
public function toResponse($request)
{
return $this->inlineResponse();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment