Last active
January 23, 2022 09:27
-
-
Save T3chW1zard/8f14b9719e9add3f54b4d53694a35798 to your computer and use it in GitHub Desktop.
Chrome headless with Symfony/Process and PHP Version 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Service; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Psr\Log\LoggerInterface; | |
use Symfony\Component\Process\Process; | |
class PdfExport | |
{ | |
private LoggerInterface $logger; | |
private string $chromePath = 'chrome'; | |
private ArrayCollection $commandArguments; | |
public function __construct(LoggerInterface $logger, string $chromePath = null) | |
{ | |
$this->logger = $logger; | |
if ($chromePath !== null) { | |
$this->chromePath = $chromePath; | |
} | |
$this->commandArguments = new ArrayCollection(); | |
$this->addDefaultCommandArguments(); | |
} | |
public function addCommandArgument(string $argument): self | |
{ | |
if (!$this->commandArguments->contains($argument)) { | |
$this->commandArguments[] = $argument; | |
} | |
return $this; | |
} | |
public function removeCommandArgument(string $argument): self | |
{ | |
if ($this->commandArguments->contains($argument)) { | |
$this->commandArguments->removeElement($argument); | |
} | |
return $this; | |
} | |
private function addDefaultCommandArguments() | |
{ | |
$defaultArguments = [ | |
$this->chromePath, | |
'--headless', | |
'--disable-gpu', | |
'--disable-software-rasterizer', | |
'--disable-dev-shm-usage', | |
'--run-all-compositor-stages-before-draw', | |
'--include-background', | |
'--print-to-pdf-no-header', | |
'--no-margins', | |
'--no-sandbox', | |
]; | |
foreach ($defaultArguments as $defaultArgument) { | |
$this->addCommandArgument($defaultArgument); | |
} | |
} | |
public function generatePdf($inFile, $outFile): bool | |
{ | |
$this->addCommandArgument('--print-to-pdf=' . $outFile); | |
$this->addCommandArgument($inFile); | |
$process = new Process($this->commandArguments->toArray(), null, null, null, null); | |
$this->logger->debug('Init process to convert HTML to PDF', ['cmdline' => $process->getCommandLine()]); | |
$process->start(); | |
$this->logger->debug('Process started', ['pid' => $process->getPid()]); | |
$process->wait(function ($type, $buffer) { | |
if (Process::ERR === $type) { | |
$this->logger->debug('Process stderr', ['msg' => $buffer]); | |
} else { | |
$this->logger->debug('Process stdout', ['msg' => $buffer]); | |
} | |
}); | |
$this->logger->debug('Process exit code', ['code' => $process->getExitCode()]); | |
$process->stop(0); | |
$this->logger->debug('Process stopped'); | |
return $process->isSuccessful(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment