adrema/app/Pdf/PdfGenerator.php

67 lines
1.8 KiB
PHP
Raw Normal View History

2021-07-15 21:17:48 +02:00
<?php
namespace App\Pdf;
use Illuminate\Contracts\Support\Responsable;
2021-07-16 00:12:19 +02:00
use Illuminate\Support\Str;
2021-07-15 21:17:48 +02:00
use Storage;
class PdfGenerator implements Responsable
{
private ?string $filename = null;
2021-07-16 00:12:19 +02:00
private PdfRepository $repo;
private string $dir;
2021-07-15 21:17:48 +02:00
2021-07-16 00:12:19 +02:00
public function setRepository(PdfRepository $repo): self
2021-07-15 21:17:48 +02:00
{
2021-07-16 00:12:19 +02:00
$this->repo = $repo;
return $this;
}
public function render(): self
{
$this->filename = $this->repo->getFilename();
$this->dir = Str::random(32);
2021-07-15 21:17:48 +02:00
2021-07-16 00:12:19 +02:00
Storage::disk('temp')->put($this->dir.'/'.$this->repo->getFilename().'.tex', $this->compileView());
Storage::disk('temp')->makeDirectory($this->dir);
2021-07-15 21:17:48 +02:00
2021-07-16 00:12:19 +02:00
$this->copyTemplateTo(Storage::disk('temp')->path($this->dir));
$command = 'cd '.Storage::disk('temp')->path($this->dir);
$command .= ' && '.env('XELATEX').' --halt-on-error '.$this->repo->getFilename().'.tex';
exec($command, $output, $returnVar);
return $this;
}
public function compileView(): string
{
2022-01-02 11:42:32 +01:00
return view()->make($this->repo->getView(), [
2021-07-16 00:12:19 +02:00
'data' => $this->repo,
2022-01-02 11:42:32 +01:00
])->render();
2021-07-15 21:17:48 +02:00
}
public function toResponse($request)
{
2021-07-16 00:12:19 +02:00
return response()->file($this->getCompiledFilename(), [
'Content-Type' => 'application/pdf',
'Content-Disposition' => "inline; filename=\"{$this->filename}.pdf\"",
]);
2021-07-15 21:17:48 +02:00
}
2021-07-16 00:12:19 +02:00
public function getCompiledFilename(): string
{
return Storage::disk('temp')->path($this->dir.'/'.$this->filename.'.pdf');
}
2021-07-15 21:17:48 +02:00
2021-07-16 00:12:19 +02:00
private function copyTemplateTo(string $destination): void
{
$templatePath = resource_path("views/tex/templates/{$this->repo->getTemplate()}");
exec('cp '.$templatePath.'/* '.$destination);
}
}