Last active
June 26, 2020 01:24
-
-
Save devfelipereis/43e643075c4ba30adf6b033aae19d34a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
namespace App\Services; | |
use File; | |
use Nesk\Puphpeteer\Puppeteer; | |
class PDFService | |
{ | |
public function generateFromURL(String $url, String $fileName, String $savePath = ''): void | |
{ | |
if (filter_var($url, FILTER_VALIDATE_URL) === false) { | |
throw new \Exception('Url is not valid'); | |
} | |
if (empty($savePath)) { | |
throw new \Exception('$savePath needs to be set'); | |
} | |
$fileName = !empty($fileName) ? $fileName : uniqid(); | |
$fileName = $this->putExtension($fileName); | |
if (substr($savePath, 1) === '/') { | |
$savePath = substr($savePath, 0, 1); | |
} | |
if (substr($savePath, -1) !== '/') { | |
$savePath .= '/'; | |
} | |
$base_path = storage_path('app/public/'.$savePath); | |
$full_path = $base_path.$fileName; | |
if (!File::exists($base_path)) { | |
File::makeDirectory($base_path, 0755, true, true); | |
} | |
$puppeteer = new Puppeteer([ | |
'idle_timeout' => 10000, | |
'read_timeout' => 10000, | |
]); | |
$browser = $puppeteer->launch([ | |
'executablePath' => '/usr/bin/chromium-browser', | |
'slowMo' => '1000', | |
'args' => ['--no-sandbox', '--disable-dev-shm-usage'] | |
]); | |
$page = $browser->newPage(); | |
$page->goto($url, ['waitUntil'=> 'networkidle2', 'timeout' => 10000]); | |
$page->emulateMedia('screen'); | |
$page->pdf([ | |
'path' => $full_path, | |
'format' => 'A4', | |
'printBackground' => true, | |
// 'displayHeaderFooter' => true, | |
'margin' => [ | |
'top' => '2.54cm', | |
'left' => '1cm', | |
'bottom' => '3cm', | |
'right' => '1cm', | |
], | |
'pageNumber' => true | |
]); | |
$browser->close(); | |
} | |
private function putExtension($str) | |
{ | |
return $str . '.pdf'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment