Laravel Package Tutorials

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Convert Html to PDF in laravel

 David
 March 31, 2021

 Share on Facebook
 Share on Twitter


Convert HTML to PDF in Laravel using the domPDF library will give you a very simple way
to convert HTML to PDF file and give to download that pdf step by step. In this tutorial, we
use laravel-dompdf package barryvdh to convert HTML to pdf in laravel and this package
also provides to download function.

Recently for a custom Laravel based Ecommerce project (which I am developing for a client
company), I needed to export the order in the form of an invoice into pdf file where I use
dynamic PDF generation feature for the customer’s order invoices so they could easily print
the order invoices on pdf. After searching for some hours I found a very nice DOMPDF
Wrapper for Laravel at GitHub, laravel-dompdf.

The Step by Step procedure is written you can follow all the steps properly. We assume you
have already set up a Laravel project.

1. Package Installation

Now let’s move to our project directory where you want to install the package.

like: D:\xampp\htdocs\projectname
composer require barryvdh/laravel-dompdf
You need to wait for the installation of the package until you see the cursor starts blinking
again at the end of the command interface.

2: Add service provider


Now open the config/app.php file

Add the following line to ‘providers’ array:

'providers' => [
....
Barryvdh\DomPDF\ServiceProvider::class,
],

Now add these lines to ‘aliases’:

'aliases' => [
....
'PDF' => Barryvdh\DomPDF\Facade::class,
]

3. Update routes/web.php

Open the routes/web.php file and add the following route.

Route::get(order/print-pdf,'PdfController@orderPrintPDF')-
>name('order.print-pdf');

In the above, you see I have a function in orderPrintPDF() in PdfController that will handle
the PDF generation. Now add that route to an anchor or button you want to use for PDF
generation.

<a href="{{route('order.printpdf')}}">Print PDF</a>

4: Create Controller
Create a file in app/Http/Controllers/PdfController.php

add the given code.

<?php

// Our Controller 

namespace App\Http\Controllers;

use Illuminate\Http\Request;

// This is important to add here. 

use PDF;

class PdfController extends Controller
{

    public function orderPrintPDF(Request $request)

    {

       // This  $data array will be passed to our PDF blade

       $data = [

          'title' => 'First PDF for Medium',

          'heading' => 'Hello from 99Points.info',

          'content' => 'Lorem Ipsum is simply dummy text of the printing an
d typesetting industry.'        

        ];

        $pdf = PDF::loadView('pdf_view', $data); 

        return $pdf->download('customorder.pdf');

    }

You can use the above function orderPrintPDF() into any of your existing controllers or you
can create a new one with any other name (I am using PdfController as an example in this
post). But make sure if you have a different controller name then you should update the
above route lines (Step 3) accordingly.

5. Create Blade View

A blade view is a file that will be rendered to our final PDF. To apply formatting on a PDF
file you need to add inline CSS to the elements and to make the elements fit the PDF use
HTML tables instead of Div, Span, or other markups tags.

Don’t forget to give the table 100% width if you want to create a PDF with edge to edge
layout.

Create a view pdf_view.blade.php in \resources\views\

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

 <title>{{ $title }}</title>

</head>

<body>

  <h1>{{ $heading}}</h1>
  

  <table width="100%" style="width:100%" border="0">

      <tr>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>

      <tr>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>

    </table>

</body>

</body>

</html>

I hope this example of HTML to pdf in laravel has made your work easier.

You can also check our Laravel Image Uploading with validation tutorials.

 Share on Facebook
 Share on Twitter


Previous Post

Make money from eBay selling

Next Post

Stripe integration in Laravel

Related Article
Laravel Programming
Stripe integration in Laravel
 October 12, 2021
 0

Laravel
Task Scheduling With Cron Job In Laravel
 November 10, 2020
 0

Laravel

Laravel 7 Image Upload with Validation Example


 September 1, 2020
 0

Nodejs Programming
How to send push notification in nodejs using firebase-
admin
 June 17, 2020
 0

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories

 Business (3)
 Entertainment (6)
 Food (3)
 International (3)
 Laravel (4)
 Lifestyle (10)
 News (14)
 Nodejs (1)
 Programming (3)
Laravel 7 Image Upload with Validation Example
 David
 September 1, 2020

 Share on Facebook
 Share on Twitter


Laravel 7 Image uploading with validation complete example step by step procedure.

Today, I will show you how to create a simple image upload in Laravel 7. I write an article
step by step about image upload in the Laravel 7 version with image validation.

I added image upload validation like image, mimes like jpeg, png, gif, and max file upload,
So you can easily understand and use this code in your project.

We will create two routes one for GET method and another for the POSTmethod. We created
a simple form with file input. You can select an image and then it will upload in the “images”
directory of the public folder.

If you have an already installed Laravel project then you can simply skip the steps and just
add the controller code function where we code for image uploading in Laravel.

Step 1: Install Laravel 7 App


First of all, we need to get a fresh Laravel 7 version application using bellow command
because we are going from scratch, so open your terminal OR command prompt and run
bellow command:

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

Step 2: Create Routes

In the next step, we have created two routes in the web.php file. One route for generate form
and another for post method so let’s simply create both routes as bellow listed:

Folder: routes/web.php

Route::get('image-upload', 'ImageUploadController@imageUpload')-
>name('image.upload');
Route::post('image-upload', 'ImageUploadController@imageUploadPost')-
>name('image.upload.post');

Step 3: Create Controller

In the third step, we will have to create a new ImageUploadController and we have written
two methods imageUpload() and imageUploadPost(). So one method will handle get method
another one for post. So let’s add code.

app/Http/Controllers/ImageUploadController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageUploadController extends Controller


{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function imageUpload()
{
return view('imageUpload');
}

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function imageUploadPost(Request $request)
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$rules = ['image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'];
$request->validate($rules);

$imageName = time().'.'.$request->file('image')-
>getClientOriginalExtension();
$request->file('image')->move(public_path('images'), $imageName);
return back()
->with('success','You have successfully upload image.')
->with('image',$imageName);
}
}

Step 3: Create Blade File

In the last step, we need to create an imageUpload.blade.php file and in this file, we will
create a form with a file input button. So copy bellow and put on that file.

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 7 image upload example - HDTuto.com</title>
<link rel="stylesheet"
href="http://getbootstrap.com/dist/css/bootstrap.css">
</head>
<body>
<div class="container">

<div class="panel panel-primary">


<div class="panel-heading"><h2>Laravel 5.7 image upload example -
HDTuto.com</h2></div>
<div class="panel-body">

@if ($message = Session::get('success'))


<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="images/{{ Session::get('image') }}">
@endif

@if (count($errors) > 0)


<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<form action="{{ route('image.upload.post') }}" method="POST"


enctype="multipart/form-data">
@csrf
<div class="row">

<div class="col-md-6">
<input type="file" name="image" class="form-control">
</div>

<div class="col-md-6">
<button type="submit" class="btn btn-success">Upload</button>
</div>

</div>
</form>

</div>
</div>
</div>
</body>
</html>

Step 4: Create “images” Directory

In the last step, we need to create new directory “images” with full permission, so let’s create
a new folder in the public folder.

If you found any difficulties or issues you can comment to us. We will respond to you as
soon as possible. and you can explore more on laravel official documentation.

Thanks

picqer/php-barcode-generator
composer re

An easy to use, non-bloated, barcode generator in PHP. Creates SVG, PNG, JPG and HTML
images from the most used 1D barcode standards.
Maintainers

Details

github.com/picqer/php-barcode-generator

Homepage

Source

Issues

Fund package maintenance!


casperbakker

Installs: 4 069 694

Dependents: 37

Suggesters: 1

Security: 0

Stars: 1 196

Watchers: 62

Forks: 336

Open Issues: 11

v2.2.0 2021-03-27 09:06 UTC

Requires

 php: ^7.3|^8.0
 ext-mbstring: *

Requires (Dev)

 phpunit/phpunit: ^9.5

Suggests

 ext-bcmath: Barcode IMB (Intelligent Mail Barcode) needs bcmath extension


 ext-gd: For JPG and PNG generators, GD or Imagick is required
 ext-imagick: For JPG and PNG generators, GD or Imagick is required

Provides

None

Conflicts

None

Replaces

None

LGPL-3.0-or-later 7df93b40099e5fefad055543320a36b80dccda05

 Nicola Asuni <info@tecnick.com>


 Casper Bakker <info@picqer.com>

phphtmlbarcodepngEAN13svgjpegeanbarcode
generatorCODABARupcjpgPharmacode39Standard 2 of
5MSIPOSTNETKIXcode128Code93KIXCODECode11

 dev-main
 dev-master
 v2.2.0
 v2.1.0
 v2.0.1
 v2.0.0
 v0.4.0
 v0.3
 v0.2.2
 v0.2.1
 v0.2
 v0.1

This package is auto-updated.

Last update: 2021-10-27 10:32:39 UTC

README

This is an easy to use, non-bloated, framework independent, barcode generator in PHP.

It creates SVG, PNG, JPG and HTML images, from the most used 1D barcode standards.
The codebase is based on the TCPDF barcode generator by Nicola Asuni. This code is
therefor licensed under LGPLv3.

No support for...
We do not support any 2D barcodes, like QR codes. We also only generate the 'bars' part of a
barcode. If you want text of the code below the barcode, you could add it later to the output
of this package.

Installation
Install through composer:

composer require picqer/php-barcode-generator

If you want to generate PNG or JPG images, you need the GD library or Imagick installed on
your system as well.

Usage
Initiate the barcode generator for the output you want, then call the ->getBarcode() routine as
many times as you want.

<?php
require 'vendor/autoload.php';

// This will output the barcode as HTML output to display in the browser
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
echo $generator->getBarcode('081231723897', $generator::TYPE_CODE_128);

The getBarcode() method accepts the following parameters:

 $barcode String needed to encode in the barcode


 $type Type of barcode, use the constants defined in the class
 $widthFactor Width is based on the length of the data, with this factor you can make the
barcode bars wider than default
 $height The total height of the barcode in pixels
 $foregroundColor Hex code as string, or array of RGB, of the colors of the bars (the
foreground color)

Example of usage of all parameters:

<?php

require 'vendor/autoload.php';

$redColor = [255, 0, 0];

$generator = new Picqer\Barcode\BarcodeGeneratorPNG();


file_put_contents('barcode.png', $generator->getBarcode('081231723897',
$generator::TYPE_CODE_128, 3, 50, $redColor));
Image types
$generatorSVG = new Picqer\Barcode\BarcodeGeneratorSVG(); // Vector based
SVG
$generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG(); // Pixel based
PNG
$generatorJPG = new Picqer\Barcode\BarcodeGeneratorJPG(); // Pixel based
JPG
$generatorHTML = new Picqer\Barcode\BarcodeGeneratorHTML(); // Pixel based
HTML
$generatorHTML = new Picqer\Barcode\BarcodeGeneratorDynamicHTML(); //
Vector based HTML

Accepted barcode types


These barcode types are supported. All types support different character sets or have
mandatory lengths. Please see wikipedia for supported chars and lengths per type.

Most used types are TYPE_CODE_128 and TYPE_CODE_39. Because of the best scanner
support, variable length and most chars supported.

 TYPE_CODE_39
 TYPE_CODE_39_CHECKSUM
 TYPE_CODE_39E
 TYPE_CODE_39E_CHECKSUM
 TYPE_CODE_93
 TYPE_STANDARD_2_5
 TYPE_STANDARD_2_5_CHECKSUM
 TYPE_INTERLEAVED_2_5
 TYPE_INTERLEAVED_2_5_CHECKSUM
 TYPE_CODE_128
 TYPE_CODE_128_A
 TYPE_CODE_128_B
 TYPE_CODE_128_C
 TYPE_EAN_2
 TYPE_EAN_5
 TYPE_EAN_8
 TYPE_EAN_13
 TYPE_UPC_A
 TYPE_UPC_E
 TYPE_MSI
 TYPE_MSI_CHECKSUM
 TYPE_POSTNET
 TYPE_PLANET
 TYPE_RMS4CC
 TYPE_KIX
 TYPE_IMB
 TYPE_CODABAR
 TYPE_CODE_11
 TYPE_PHARMA_CODE
 TYPE_PHARMA_CODE_TWO_TRACKS
See example images for all supported barcode types

A note about PNG and JPG images


If you want to use PNG or JPG images, you need to install Imagick or the GD library. This
package will use Imagick if that is installed, or fall back to GD. If you have both installed but
you want a specific method, you can use $generator->useGd() or $generator-
>useImagick() to force your preference.

Examples
Embedded PNG image in HTML
$generator = new Picqer\Barcode\BarcodeGeneratorPNG();
echo '<img src="data:image/png;base64,' . base64_encode($generator-
>getBarcode('081231723897', $generator::TYPE_CODE_128)) . '">';

Save JPG barcode to disk


$generator = new Picqer\Barcode\BarcodeGeneratorJPG();
file_put_contents('barcode.jpg', $generator->getBarcode('081231723897',
$generator::TYPE_CODABAR));

Oneliner SVG output to disk


file_put_contents('barcode.svg', (new Picqer\Barcode\
BarcodeGeneratorSVG())->getBarcode('6825ME601', Picqer\Barcode\
BarcodeGeneratorSVG::TYPE_KIX));

You might also like