How To Set Password In PDF Laravel?




How To Set Password In PDF Laravel?

Hi Dev,

I want to add password protection for PDF file, i searched on the internet but only found solution of adding password protection when download PDF file from HTML to PDF.

So,I will discuss how to set password in pdf laravel 8.We will use php-pdftk github composer package to protect the pdf file. php-pdftk provide setPassword() method that can help to set password.

You can use this example with laravel 6, laravel 7 and laravel 8 version. so let's follow bellow tutorial.

Step 1 : Install Laravel Application

So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Install php-pdftk Package

first of all we will install mikehaertl/php-pdftk composer package by following composer command in your laravel application.

composer require mikehaertl/php-pdftk

And after run this command in terminal.

sudo apt install pdftk

Step 3 : Add Route

Open your "routes/web.php" file and add following route.



use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PDFController;



| 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('download-pdf', [PDFController::class, 'downloadPDF']);

Step 4 : Add Controller

Here,we require to create new controller PDFController that will manage downloadPDF method of route.

Make sure you have created "files" folder in public directory and put "NiceSnippets.pdf" dummy pdf file, so we are using that existing pdf file here.

So let's put bellow code.



namespace App\Http\Controllers;

use mikehaertl\pdftk\Pdf;

class PDFController extends Controller



* Write code on Method


* @return response()


public function downloadPDF()


$filePath = public_path('files/NiceSnippets.pdf');

$pdf = new Pdf($filePath);

$password = '123456';

$userPassword = '123456a';

$result = $pdf->allow('AllFeatures')





if ($result === false) {

$error = $pdf->getError();


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



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:



Enter password : 123456

I hope it can help you...