skip to Main Content

I am trying to use chrome-php/chrome to load a Blade view and then output it to the browser instead of saving it.

However using the docs in their GitHub I could not construct a working code that does that.

I tried:

public function createPdf(Request $request)
{
    $page = $browser->createPage();
    $page->navigate('http://example.com/path-to-blade-file')->waitForNavigation();
    $html = $page->getHtml(10000);
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename=filename.pdf');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');

    // How to then use the HTML from the Blade to display the PDF?
}

but then I could not use their method to output directly to the browser with echo base64_decode($pdf->getBase64()) because I have an HTML string and not $pdf object, and I could not find a way to create PDF from HTML

Also, is there a better way to load the Blade view instead of using the full URL?

2

Answers


  1. Chosen as BEST ANSWER

    I managed to get it working, I first needed to convert the blade view to raw HTML string, then set the page contents of the headless chrome instance using setHtml(), then call the pdf() method on the page and output that after decoding its base64 value:

    use HeadlessChromiumBrowserFactory;
    
        public function createPdf(Request $request)
        {
            $browserFactory = new BrowserFactory();
    
            // starts headless chrome
            $browser = $browserFactory->createBrowser();
    
            try {
                // convert blade view to raw HTML string
                $bladeViewRawHtmlString = view('blade-view')->render();
    
                // creates a new page and set the HTML
                $page = $browser->createPage();            
                $page->setHtml($bladeViewRawHtmlString);
    
                // pdf
                header('Content-Description: File Transfer');
                header('Content-Type: application/pdf');
                header('Content-Disposition: inline; filename=filename.pdf');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
    
                $pdf = $page->pdf(['printBackground' => false]);
                echo base64_decode($pdf->getBase64());
            } finally {
                // bye
                $browser->close();
            }
        }
    

  2. I used to save PDF files in Storage path, downloading it with Storage::download('path.pdf').

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search