How to convert blade file into pdf and image in laravel?

Member

by deron , in category: PHP Frameworks , 3 months ago

How to convert blade file into pdf and image in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 3 months ago

@deron 

You can convert a Blade file into a PDF and an image in Laravel using the following steps:

  1. Install the required packages: First, you need to install the following packages using composer:
1
2
composer require barryvdh/laravel-dompdf
composer require intervention/image


  1. Convert Blade file into PDF: Create a route in your web.php file to render the Blade file and convert it into a PDF using the following code:
1
2
3
4
5
6
7
8
9
Route::get('pdf', function () {
    $data = [
        'title' => 'Sample PDF',
        'content' => 'This is the content of the PDF file'
    ];

    $pdf = PDF::loadView('pdf.blade', $data);
    return $pdf->download('pdf_file.pdf');
});


  1. Convert Blade file into an image: Create a route in your web.php file to render the Blade file and convert it into an image using the following code:
1
2
3
4
5
6
7
8
9
Route::get('image', function () {
    $data = [
        'title' => 'Sample Image',
        'content' => 'This is the content of the image'
    ];

    $img = Image::make('pdf.blade')->encode('jpg');
    return $img->response();
});


  1. Create the Blade file: Create a Blade file (pdf.blade.php) in your resources/views directory with the content you want to convert into a PDF or image.


Now you can access the /pdf and /image routes in your browser to download the converted PDF and image files respectively.