89 lines
2.3 KiB
PHP
89 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Repositories\Core;
|
|
|
|
use Barryvdh\DomPDF\Facade\Pdf as DomPDF;
|
|
use GravityMedia\Ghostscript\Ghostscript;
|
|
use Mpdf\Mpdf;
|
|
use Barryvdh\Snappy\Facades\SnappyPdf;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
class PDF
|
|
{
|
|
public static function view($view, $data, $filename = 'file.pdf')
|
|
{
|
|
\Debugbar::disable();
|
|
$pdf = DomPDF::loadView($view, $data);
|
|
return $pdf->download($filename);
|
|
}
|
|
|
|
public static function convertHTML($html)
|
|
{
|
|
$mpdf = new Mpdf();
|
|
$mpdf->WriteHTML($html);
|
|
return $mpdf->Output();
|
|
}
|
|
|
|
public static function convertURL($url)
|
|
{
|
|
$pdf = SnappyPdf::loadFile($url);
|
|
return $pdf->download('invoice.pdf');
|
|
}
|
|
|
|
public static function convertIfNeeded($filename)
|
|
{
|
|
if (self::getVersion($filename) > 1.4) {
|
|
self::downgrade2($filename);
|
|
}
|
|
}
|
|
|
|
public static function getVersion($filename)
|
|
{
|
|
$pdf = fopen($filename, 'r');
|
|
if ($pdf) {
|
|
$line_first = fgets($pdf);
|
|
fclose($pdf);
|
|
} else {
|
|
echo 'error opening the file.';
|
|
}
|
|
preg_match_all('!\d+!', $line_first, $matches);
|
|
$version = implode('.', $matches[0]);
|
|
|
|
return (float) $version;
|
|
}
|
|
|
|
public static function downgrade($filename)
|
|
{
|
|
$new_filename = $filename.'-temp';
|
|
$ghostscript = new Ghostscript([
|
|
'quiet' => false,
|
|
]);
|
|
|
|
$device = $ghostscript->createPdfDevice($new_filename);
|
|
$device->setCompatibilityLevel(1.4);
|
|
|
|
// dump($device);
|
|
$process = $device->createProcess($filename);
|
|
// dump($process);
|
|
// echo '$ ' . $process->getCommandLine() . PHP_EOL;
|
|
// exit;
|
|
$process->run(function ($type, $buffer) {
|
|
if ($type === Process::ERR) {
|
|
throw new \RuntimeException($buffer);
|
|
}
|
|
// print $buffer;
|
|
});
|
|
|
|
unlink($filename);
|
|
rename($new_filename, $filename);
|
|
}
|
|
|
|
public static function downgrade2($filename)
|
|
{
|
|
$new_filename = $filename.'-temp';
|
|
shell_exec('gs -dBATCH -dCompatibilityLevel=1.4 -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="'.$new_filename.'" "'.$filename.'"');
|
|
unlink($filename);
|
|
rename($new_filename, $filename);
|
|
}
|
|
}
|