Skip to content

Instantly share code, notes, and snippets.

@devfelipereis
Last active June 26, 2020 01:24

Revisions

  1. devfelipereis renamed this gist Jun 26, 2020. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. devfelipereis created this gist Jun 26, 2020.
    73 changes: 73 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    <?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';
    }
    }