matab-panel/app/Services/PdfService.php

77 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use Barryvdh\DomPDF\Facade\Pdf;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PdfService
{
public static function download(string $view, array $data, string $filename): StreamedResponse
{
if (class_exists(\Mpdf\Mpdf::class)) {
return self::downloadWithMpdf($view, $data, $filename);
}
return self::downloadWithDompdf($view, $data, $filename);
}
private static function downloadWithMpdf(string $view, array $data, string $filename): StreamedResponse
{
$defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
$defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
$fontsDir = storage_path('fonts');
$mpdf = new \Mpdf\Mpdf([
'mode' => 'utf-8',
'format' => 'A4',
'orientation' => 'P',
'margin_top' => 15,
'margin_bottom' => 15,
'margin_left' => 15,
'margin_right' => 15,
'tempDir' => sys_get_temp_dir(),
'fontDir' => array_merge($defaultConfig['fontDir'], [$fontsDir]),
'fontdata' => $defaultFontConfig['fontdata'] + [
'tahoma' => [
'R' => 'tahoma.ttf',
'B' => 'tahomabd.ttf',
'useOTL' => 0xFF,
'useKashida' => 75,
],
],
'default_font' => 'tahoma',
]);
$mpdf->autoScriptToLang = true;
$mpdf->baseScript = 1;
$mpdf->autoArabic = true;
$mpdf->autoLangToFont = true;
$html = view($view, $data)->render();
$mpdf->WriteHTML($html);
$output = $mpdf->Output('', 'S');
return response()->streamDownload(
fn () => print($output),
$filename,
['Content-Type' => 'application/pdf'],
);
}
private static function downloadWithDompdf(string $view, array $data, string $filename): StreamedResponse
{
$pdf = Pdf::loadView($view, $data)->setPaper('a4', 'portrait');
return response()->streamDownload(
fn () => print($pdf->output()),
$filename,
['Content-Type' => 'application/pdf'],
);
}
}