How To Convert HTML To Image/PDF Using Snappy In Laravel 9

  • 22-08-2022
  • 8112
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Snappy PDF/Image Wrapper for Laravel; in this post, we will teach you how to generate pdf from the HTML content or convert HTML to an image using a snappy package with an example with step by step process.

Snappy is a PHP library that allows you to make snapshots, thumbnails, and PDFs generated from the given HTML page or URL.

To convert HTML To Image, HTML to PDF generate, or any other pdf views and the image-related thing you can do using snappy package in your laravel. This package available since the laravel 5 version and now it is a popular laravel package. This package is very simple to use and integrate into our application.

Generate PDF with Graph in Laravel using Laravel Snappy, we must need to install wkhtmltopdf & wkhtmltoimage for the command to execute. So we must install to install wkhtmltopdf and wkhtmltoimage before installing snappy.

How to convert HTML to jpg this post will help you simple way to generate. So let's start. integration in our application.

Preview:
image

Step 1. Create Laravel Project

Let's start by cloning a new laravel application. Use the below-provided command, Also you may change the project name as per your requirement. Goto terminal and run the command.

composer create-project --prefer-dist laravel/laravel example-app

Go to your project directory using "cd" and then give your project name and hit enter in your terminal.

cd example-app

Step 2. Install wkhtmltopdf & wkhtmltoimage

In this step, we will install `wkhtmltopdf` & `wkhtmltoimage` composer using the below provided command.

If you are using an x64 bit system then run the below given two commands in your terminal. This command will install wkhtmltopdf & wkhtmltoimage library file and dependency in the system of your laravel project vendor folder.

For x64 System:
composer require h4cc/wkhtmltopdf-amd64 0.12.x
composer require h4cc/wkhtmltoimage-amd64 0.12.x

Use the below two provided commands in your project command line terminal if you are using an x86 bit system.

For x86 System:
composer require h4cc/wkhtmltopdf-i386 0.12.x
composer require h4cc/wkhtmltoimage-i386 0.12.x

For the windows system please use the below-provided command in your project terminal. This command is for windows system users only.

For Windows:
composer require wemersonjanuario/wkhtmltopdf-windows "0.12.2.3"

Step 3. Install Laravel Snappy Composer

Install composer to use laravel snappy package, Use the below suggested command in your project terminal. This command will install the snappy package. This command will install composer snappy dependency in your laravel application.

composer require barryvdh/laravel-snappy

To run globally namespace we will define the app.php file. You will find it in your config folder from the root of the project. add in providers array attributes and aliases as below given code.

config/app.php
'providers' => [
    Barryvdh\Snappy\ServiceProvider::class,
],

'aliases' => [
    'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
    'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
]

Run the below command for the snappy package config setting. If you have already installed even though run this command in your application terminal. This command will update your configuration to the latest version. The file will generate in the config folder. the fill name you will find snappy.php in config folder form the root of the application.

php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"
For Windows (ONLY WINDOWS USERS):

If you are using a windows system, set your snappy.php file like the below example given. Give binary path to the "pdf" and "image".

This will access wkhtmltopdf & wkhtmltoimage from our application vendor folder.

config/snappy.php
<?php

return [
    'pdf' => [
        'enabled' => true,
        'binary' => base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltopdf'),
        'timeout' => false,
        'options' => [],
        'env'     => [],
    ],

    'image' => [
        'enabled' => true,
        'binary' => base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltoimage'),
        'timeout' => false,
        'options' => [],
        'env' => [],
    ],
];

For any other system, You need to config like the below given example. This configuration will not apply to windows users. apart from the window users the snappy.php file configuration should like blow given example.

For other systems (NOT FOR WINDOWS USERS):
<?php

return [
    'pdf' => array(
        'enabled' => true,
        'binary' => base_path('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'),
        'timeout' => false,
        'options' => array(),
        'env' => array(),
    ),
    'image' => array(
        'enabled' => true,
        'binary' => 'vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64',
        'timeout' => false,
        'options' => array(),
        'env' => array(),
    ),
];

In case you are getting 126 Occurs error (NOT FOR WINDOWS USERS) in that case you need to follow one more stem ahead.

In this case (126 error) you need to copy your wkhtmltopdf-amd64 and wkhtmltopdf-amd64 files to /usr/local/bin/ folder of your system.

Follow something as below given, open your project terminal, and run the below command. This will copy wkhtmltopdf-amd64 and wkhtmltopdf-amd64 files from the vender to /user/local/bin/ directory.

COPY TO /usr/local/bin/

cp vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64 /usr/local/bin/
cp vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64 /usr/local/bin/

To make it executable, we need to provide proper permission. hit the below command and give them fully access permission.

Permission:
chmod +x /usr/local/bin/wkhtmltoimage-amd64
chmod +x /usr/local/bin/wkhtmltopdf-amd64

Now your config of the snappy.php file should be like the below given. Just copy and paste it into your snappy.php config file.

Config after move to /usr/local/bin/ (NOT FOR WINDOWS USERS):

<?php

return [
    'pdf' => array(
        'enabled' => true,
        'binary' => base_path('/usr/local/bin/wkhtmltopdf-amd64'),
        'timeout' => false,
        'options' => array(),
        'env' => array(),
    ),
    'image' => array(
        'enabled' => true,
        'binary' => '/usr/local/bin/wkhtmltoimage-amd64',
        'timeout' => false,
        'options' => array(),
        'env' => array(),
    ),
];

Step 4. View File Render

This HTML view file, I want to print out in a pdf file. I will render this blade file and will put it into the snappy maker.

resources/views/welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Convert HTML to PDF with image generate Snappy - Webappfix</title>
</head>
<body>
    <h1>Convert HTML to PDF with image generate Snappy - Webappfix</h1>
    <h2>Convert HTML to PDF with image generate Snappy - Webappfix</h2>
    <h3>Convert HTML to PDF with image generate Snappy - Webappfix</h3>
    <h4>Convert HTML to PDF with image generate Snappy - Webappfix</h4>
    <h5>Convert HTML to PDF with image generate Snappy - Webappfix</h5>
    <h6>Convert HTML to PDF with image generate Snappy - Webappfix</h6>
</body>
</html>

Render HTML blade file using view()->render(). This will render the whole HTML content of the given HTML path file and print it in a pdf file and save in to a public folder as 123. pdf.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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('/', function () {

    $snappy = \App::make('snappy.pdf');

    $html = view('welcome')->render();

    $snappy->generateFromHtml($html, public_path('123.pdf'));

    dd('pdf generated');

    // PDF GENERATE FROM OTHER URL

        //$snappy->generate('https://www.webappfix.com', public_path('123.pdf'));

    // PDF RETURN OUTPUT WITHOUT SAVE PDF TEMP FOLDER

        // return new Response(
        //     $snappy->getOutputFromHtml($html),
        //     200,
        //     array(
        //         'Content-Type'          => 'application/pdf',
        //         'Content-Disposition'   => 'attachment; filename="123.pdf"'
        //     )
        // );

    // HTML TO IMAGE

        // $snappy = \App::make('snappy.image');
        // $html = view('welcome')->render();
        // $snappy->setOption('width',1); // FOR IMAGE WIDTH SET
        // $nameImage = \Str::random(5).'.jpg';
        // $snappy->generateFromHtml($html,public_path().$nameImage);
});

Start developing server and test snappy pdf generate.

php artisan serve

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :