How to Create PDF using Headless Chrome in Laravel?

By Hardik Savani January 6, 2024 Category : Laravel

Hello Artisan,

In this quick example, let's see how to create pdf using headless chrome in laravel. This post will give you a simple example of laravel generate pdf using headless chrome. If you have a question about laravel headless chrome pdf then I will give a simple example with a solution. if you want to see an example of laravel pdf headless chrome example then you are in the right place.

In this tutorial, i will show you how to convert webpage to pdf file using headless chrome in laravel. To achieve this, we'll leverage chrome-php/chrome to initiate headless Chrome and capture a PDF screenshot within the Laravel framework. We'll establish two straightforward routes employing the GET and POST methods. Subsequently, the PDFChromeController will be created with the necessary methods. Additionally, we'll design a form allowing users to input a URL and click a submit button. Upon submission, users will have the option to download the resulting PDF file.

Step for Laravel Generate PDF using Headless Chrome

  • Step 1: Install Laravel 10
  • Step 2: Install chrome-php/chrome
  • Step 3: Create Controller
  • Step 4: Create Routes
  • Step 5: Create Blade File
  • Run Laravel App

So, let's see the simple step to done this example.

Step 1: Install Laravel

first of all, we need to get a fresh Laravel version application using the bellow command, So open your terminal OR command prompt and run the bellow command:

composer create-project laravel/laravel example-app

Step 2: Install chrome-php/chrome

Here, we will install following commands to install PHP Chrome. so, let's run the bellow command:

composer require chrome-php/chrome

Step 3: Create Controller

In this step, we will create new PDFChromeController for store image. in this controller we will add two method call index() and store(). so let's create new controller by following command.

php artisan make:controller PDFChromeController

Next, let's update the following code to that file.

Make Sure you have uploads folder in public folder with permission. we are going to store image on that folder so.

app/Http/Controllers/PDFChromeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use HeadlessChromium\BrowserFactory;

class PDFChromeController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

return view('pdfChrome');

}

/**

* Write code on Method

*

* @return response()

*/

public function store(Request $request)

{

$browserFactory = new BrowserFactory();

/* starts headless Chrome */

$browser = (new BrowserFactory())->createBrowser([

'windowSize' => [1920, 1080]

]);

try {

/* creates a new page and navigate to an URL */

$page = $browser->createPage();

$page->navigate($request->url)->waitForNavigation();

/* get page title */

$pageTitle = $page->evaluate('document.title')->getReturnValue();

$options = [

'landscape' => true,

'printBackground' => false,

'marginTop' => 0.0,

'marginBottom' => 0.0,

'marginLeft' => 0.0,

'marginRight' => 0.0,

];

$name = public_path("uploads/".time().'.pdf');

$page->pdf($options)->saveToFile($name);

return response()->download($name);

} finally {

$browser->close();

}

}

}

Step 4: Create Routes

Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for call view and store image.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PDFChromeController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('pdf-chrome', [PDFChromeController::class, 'index']);

Route::post('pdf-chrome', [PDFChromeController::class, 'store'])->name('pdf.chrmoe.download');

Step 5: Create Blade File

now here we will create pdfChrome.blade.php file and here we will create bootstrap simple form. So, let's create following file:

resources/views/pdfChrome.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 10 Generate PDF using Headless Chrome Example - ItSolutionStuff.com</title>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

<div class="container">

<div class="row">

<div class="col-md-8">

<div class="card">

<div class="card-header">

<h2>Laravel 10 Generate PDF using Headless Chrome Example - ItSolutionStuff.com</h2>

</div>

<div class="card-body">

<form method="POST" action="{{ route('pdf.chrmoe.download') }}">

{{ csrf_field() }}

<div class="mb-3">

<label class="form-label" for="inputName">URL:</label>

<input

type="url"

name="url"

id="inputName"

class="form-control @error('url') is-invalid @enderror"

placeholder="URL">

<!-- Way 2: Display Error Message -->

@error('url')

<span class="text-danger">{{ $message }}</span>

@enderror

</div>

<div class="mb-3">

<button class="btn btn-success btn-submit">Download PDF</button>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/pdf-chrome

Output:

You will see following pdf file:

I hope it can help you...

Tags :
Shares