Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

basosneo's avatar

Generate pdf

Hello friends, right now I have been thinking and I think that something that I would like to have in my page would be some reports in pdf.

In my application, just after paying; My shopping cart disappears and no invoice comes out of the purchase ....

Can somebody help me?

paypalcontroller.php>getpaymentstatus

 public function getPaymentStatus()
 {
    // Get the payment ID before session clear
    $payment_id = \Session::get('paypal_payment_id');

    // clear the session payment ID
    \Session::forget('paypal_payment_id');

    $payerId = \Input::get('PayerID');
    $token = \Input::get('token');

    //if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
    if (empty($payerId) || empty($token)) {
        return \Redirect::route('home')
            ->with('message', 'Hubo un problema al intentar pagar con Paypal');
    }

    $payment = Payment::get($payment_id, $this->_api_context);

    // PaymentExecution object includes information necessary 
    // to execute a PayPal account payment. 
    // The payer_id is added to the request query parameters
    // when the user is redirected from paypal back to your site
    $execution = new PaymentExecution();
    $execution->setPayerId(\Input::get('PayerID'));

    //Execute the payment
    $result = $payment->execute($execution, $this->_api_context);

    //echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later

    if ($result->getState() == 'approved') { // payment made
        // Registrar el pedido --- ok
        // Registrar el Detalle del pedido  --- ok
        // Eliminar carrito 
        // Enviar correo a user
        // Enviar correo a admin
        // Redireccionar

        $this->saveOrder(\Session::get('cart'));

        \Session::forget('cart');


        return \Redirect::route('home')
            ->with('message', 'Compra realizada de forma correcta');
    }
    return \Redirect::route('home')
        ->with('message', 'La compra fue cancelada');
   }
0 likes
32 replies
basosneo's avatar

hey @joaomantovani, thanks for answer..

The truth is that I have not yet implemented anything .. just show my driver's code because that's where I want to make the pdf report (just before deleting the cart) .. I would like you to give me some advice on how to do it, thank you!

PS: I'm starting to work with dompdf

joaomantovani's avatar

Oh, I think I've got :]

I've worked a bit with the dompdf and I faced some troubles, may I can help you.

First of all, I used this version of DomPdf:

https://github.com/barryvdh/laravel-dompdf

To get start and generate the pdf, you should create a normal view in the resources/views folder.

The dompdf will convert the HTML to PDF, and thinking about that, you need to take some considerations, like:

  • Your html is not equal your pdf, some elements will work, and some will not work.

  • Css elements like, :first-child or :last-child may not work

  • You can work with fixed pixels sizes to your elements (because the size of pdf never change)

  • The more complex/big your html is, the more process time is needed to create the pdf.

  • You may have problems to load images in the localhost

  • You may have problems loading css from files (if does not load correct, try to put inline)

  • Not all the elements of an framework css (like bootstrap) will work

  • If you did not find the error, check the log storage/logs/laravel.log

  • If you are going to use custom fonts, you should create a folder to store the fonts in the storage folder mkdir storage/fonts/and give the permission: chmod -R 755 storage/fonts.

These tips are just advices, but the real resume is:

1 - Install the dompdf

2 - Create a "test route" in your web.php

Route::get('pdf/stream', function () {
    return 'Hello World';
});

3 - Create a view (html) to be converted to pdf. In the resources/views create a new folder (to be more organized)

mkdir resources/views/pdf

and create your blade.php file

touch resources/views/pdf/pdf-teste.blade.php

Write some text like Hello word in your file, just to test.

4 - Update your routes to pass variables and stream the pdf

Route::get('pdf/stream', function () {
    //Get the data to pass to view
    $data = Example::all()->first();    

    //create a pdf from view 
    $pdf = PDF::loadView('pdf.pdf-teste', $data);

    //Show the pdf in the browser
    return $pdf->stream('teste.pdf');

    //You can download the pdf too!
    //return $pdf->download('teste.pdf');
});

The ideia is simple, create your blade view like each other and always test using the stream or download method, if I remember something more important, I'll add another answer or edit this.

Feel free to ask questions and good luck! :]

[EDIT] One very useful hint, if you want to "sticky" your elements and avoid then to separate when a page break occurs, you can use the css page-break-element in your file

Using page-break-inside: auto; basically says to dompdf "do what you would normally do when breaking pages."

To force a page break before / after your table you would use page-break-before: always; / page-break-after: always;.

To ask dompdf to avoid breaking inside an element you would use page-break-inside: avoid;

Source

Be careful if you are going to use these elements with images!

basosneo's avatar

thanks for your answere @joaomantovani, I started very excited with dompdf and I installed it, add the classes to my app.php and I got the following error;

 FatalThrowableError in ProviderRepository.php line 201: Class 'Barryvdh\DomPDF\ServiceProvider' not found

Then when I remove the classes from my repositories I get the following error;

 Class example not found

I try to change 'example' to the items saved in my OrderItem table (which is what I want to print), but I did not work either because I think the view is there, I hope it does not bother you, but can you help me?

joaomantovani's avatar

Maybe you forgot to declare the serviceproviders and the facade at the DomPdf installation

Open the config/app.php

declare this at the providers array

Barryvdh\DomPDF\ServiceProvider::class,

and this to the aliases array

'PDF' => Barryvdh\DomPDF\Facade::class,

Source

basosneo's avatar

No, no friend, the error was fixed, so i now have these error

 FatalThrowableError in web.php line 266: Class 'pdf' not found
basosneo's avatar

I edit:

I Create a controller and put a test there;

 public function generate()
{
    $pdf = App::make('dompdf.wrapper');
    $pdf->loadHTML('<h1>Jackfer</h1>');
    return $pdf->stream();
}

so its work... Now @joaomantovani, How can I create an invoice for my model order item so it looks like there?

hajrovica's avatar

@basosneo So if i am understanding correctly that test from controller is working now and You are asking how to make invoice. In controller You have posted You are creating PDF and passing some HTML to be rendered to pdf.

@joaomantovani already pointed You in right direction.

  1. Create view for invoice and send whatever data You wish to it. You can search some of already built bootstrap forms -which will shorten view creation and correct rendering to PDF. For example invoice: https://github.com/sitepointweb/bootstrap-invoice/blob/master/sample-invoice.html , preview: https://jsfiddle.net/u8qvLsoy/

  2. Test it from Your controller with opening view as standard page.

  3. When You are happy with general looks of Your invoice than pass that view with required data to create pdf

//Get the data to pass to view
$data = Example::all()->first();    

//create a pdf from view 
$pdf = PDF::loadView('invoice-view', $data);

//Show the pdf in the browser
return $pdf->stream('invoice.pdf');

You can basically output view as PDF in lets say new window and let the user save it from there, or You can save it and after that pass it to user.

basosneo's avatar

@hajrovica Absolutely thank you friend, all help is welcome; I have been 'playing' a bit with the pdf and wanted to make a view calling variables from different database, but nothing worked and I'm creating an 'invoice' but not being able to call any variables like 'auth :: user' or ' Oder_detail 'frustrates me a little.

I tried to put this code but I got a lot of errors;

any idea?

   @extends('store.template')

   @section('content')

   <div class="container text-center">
    
        <div class="page-header">
            <h1>
                <i class="fa fa-shopping-cart"></i> Detalle del pedido
            </h1>
        </div>

    <div class="page">
        <div class="table-responsive">
            <h3>Detalle del Usuario</h3>
            <table class="table table-striped table-hover table-bordered">
                <tr><td>Nombre: </td><td>{{ Auth::user()->name . " " . Auth::user()->last_name }}</td></tr>
                <tr><td>Usuario: </td><td>{{ Auth::user()->user }}</td></tr>
                <tr><td>E-mail: </td><td>{{ Auth::user()->email }}</td></tr>
                <tr><td>Direccion:</td><td>{{ Auth::user()->address }}</td></tr>
            </table>
        </div>

        <div class="table-responsive">
            <h3>Detalle del pedido</h3>
            <table class="table table-striped table-hover table-bordered">
                <tr>
                    <th>Producto</th>
                    <th>Precio</th>
                    <th>Cantidad</th>
                    <th>Subtotal</th>
                </tr>
                @foreach($cart as $item)
                    <tr>
                        <td>{{ $item->name }}</td>
                        <td>€{{ number_format($item->price,2) }}</td>
                        <td>{{ $item->quantity }}</td>
                        <td>€{{ number_format($item->price * $item->quantity,2) }}</td>
                    </tr>
                @endforeach
            </table><hr>
            <h3>
                <span class="label label-success">
                    Total: €{{ number_format($total, 2) }}
                </span>
            </h3><hr>
            <p>
                <a href="{{ route('cart-show') }}" class="btn btn-primary">
                    <i class="fa fa-chevron-circle-left"></i> Regresar
                </a>

                <a href="{{ route('payment') }}" class="btn btn-warning">
                    Pagar <i class="fa fa-cc-paypal fa-2x"></i>
                </a>
            </p>
        </div>
    </div>


</div>


  @stop

edit: the github link is break

basosneo's avatar

yes friend @hajrovica, the biggest problem is the cart item (foreach) ... I still can not think of anything

    ErrorException in 53f9f68e4f0771d591a98683e4a32b5ee3f8dd1a.php line 31: Undefined variable: cart (View: /home/niverd/Escritorio/laravel/jackfer/resources/views/pdf/pdf-teste.blade.php) 
hajrovica's avatar

yeah so basically You are not sending properly $cart variable to Your view? How do you call view from controller? Post a code

basosneo's avatar

-cartcontroller

  // Show cart
      public function show()
    {
    $cart = \Session::get('cart');
    $total = $this->total();
    return view('store.cart', compact('cart', 'total'));
    }

    // Add item
    public function add(Products $products)
    {
    $cart = \Session::get('cart');
    $products->quantity = 1;
    $cart[$products->slug] = $products;
    \Session::put('cart', $cart);
    return redirect()->route('cart-show');
   }
   // Delete item
   public function delete(Products $products)
   {
    $cart = \Session::get('cart');
    unset($cart[$products->slug]);
    \Session::put('cart', $cart);
    return redirect()->route('cart-show');
   }
    // Update item
     public function update(Products $products, $quantity)
    {
    $cart = \Session::get('cart');
    $cart[$products->slug]->quantity = $quantity;
    \Session::put('cart', $cart);
    return redirect()->route('cart-show');
    }
     // Trash cart
    public function trash()
    {
    \Session::forget('cart');
    return redirect()->route('cart-show');
     }
    // Total
    private function total()
    {
    $cart = \Session::get('cart');
    $total = 0;
    foreach($cart as $item){
        $total += $item->price * $item->quantity;
       }
      return $total;
     }
   // Detalle del pedido
      public function orderDetail()
    {
    if(count(\Session::get('cart')) <= 0) return redirect()->route('home');
    $cart = \Session::get('cart');
    $total = $this->total();
    return view('store.order-detail', compact('cart', 'total'));
    
     }

web,php

 Route::get('cart/show', [
'as' => 'cart-show',
'uses' => 'CartController@show'
  ]);

   Route::get('cart/add/{products}', [
'as' => 'cart-add',
'uses' => 'CartController@add'
  ]);

 Route::get('cart/delete/{products}',[
'as' => 'cart-delete',
'uses' => 'CartController@delete'
  ]);

  Route::get('cart/trash', [
'as' => 'cart-trash',
'uses' => 'CartController@trash'
 ]);

  Route::get('cart/update/{products}/{quantity?}', [
'as' => 'cart-update',
'uses' => 'CartController@update'
 ]);

 //order_detail
  Route::get('order-detail', [
'middleware' => 'auth:web',
'as' => 'order-detail',
'uses' => 'CartController@orderDetail'
 ]);
hajrovica's avatar

Does dd($cart) is showing anything?

  public function orderDetail()
{
if(count(\Session::get('cart')) <= 0) return redirect()->route('home');
$cart = \Session::get('cart');
$total = $this->total();
dd($cart);
return view('store.order-detail', compact('cart', 'total'));

 }
basosneo's avatar

Well, I changed and removed many functions from my pdfcontroller, now I'm like this

   <?php

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;
  use Barryvdh\DomPDF\Facade as PDF;
  use App;
  use App\Products;
  use App\Http\Requests;
  use App\User;
  use Auth;


  class PdfController extends Controller
    {
   public function generate()
    {
    $pdf = App::make('dompdf.wrapper');
    $pdf->loadView('pdf.pdf-teste');
    return $pdf->stream();
     }

  public function orderDetail()
    {
    if(count(\Session::get('cart')) <= 0) return redirect()->route('home');
    $cart = \Session::get('cart');
    $total = $this->total();
    dd($cart);
    //return view('store.order-detail', compact('cart', 'total'));
    }

    // Show cart
    public function show()
    {
    $cart = \Session::get('cart');
    $total = $this->total();
    return view('store.cart', compact('cart', 'total'));
    }
  }

But I still have the same error

    ErrorException in  53f9f68e4f0771d591a98683e4a32b5ee3f8dd1a.p hp line 31: Undefined variable: cart (View:  /home/niverd/Escritorio/laravel/jackfer /resources/views/pdf/pdf-teste.blade.php)
hajrovica's avatar
Level 9

ah i see here is your error

  public function generate()
  {
  $pdf = App::make('dompdf.wrapper');
  $pdf->loadView('pdf.pdf-teste');
  return $pdf->stream();
  }

you are loding view but not sending the data to it

  $pdf->loadView('pdf.pdf-teste');

you should be doing something like

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

and where data, before in controller is

    $data['cart'] = $cart;

then $cart variable should be available in your view

basosneo's avatar

Sorry but I do not know where in the controller place the command of the cart

   $data['cart'] = $cart;

Then if I put the command only e html view, I get the following error

 ErrorException in PdfController.php line 20: Undefined variable: data

But if I put it in the generate me function the following error occurs

    ErrorException in PdfController.php line 20: Undefined variable: cart

Should I delete my other functions from my pdfcontroller? I think they are not doing anything

vipin93's avatar

use laravel-snappy because its support external css, image file

hajrovica's avatar

so function generate is giving You error when calling it, you need to prepare data in that function and to pass it to view, lets say something like this:

  public function generate()
  {
  //Get session data for cart
  $cart = $request->session()->get('cart');
   
  //some total from Your app
   $total = $this->total();

$data['cart'] = $cart;
$data['total'] = $total;

  //start pdf 
  $pdf = App::make('dompdf.wrapper');
  
  //load view and pass data to it 
  $pdf->loadView('pdf.pdf-teste', $data);
  
  //stream pdf 
  return $pdf->stream();
 } 

This should allow view to use $cart and $total variables while generating pdf

hajrovica's avatar

Mind you for this kind of work by my opinion it is better to work out view with proper data display first, so in this example You should have used function like this

   public function generate()
    {
    //Get session data for cart
    $cart = $request->session()->get('cart');
      
    //some total from Your app
     $total = $this->total();
   
     $data['cart'] = $cart;
     $data['total'] = $total;
     
     return view('pdf.pdf-teste', compact('data'));

   } 

and when You are sure all is working correctly: data display and all other little things you have going for this view then replace

     return view('pdf.pdf-teste', compact('data'));

with pdf part

    //start pdf 
    $pdf = App::make('dompdf.wrapper');
     
    //load view and pass data to it 
    $pdf->loadView('pdf.pdf-teste', $data);
    
    //stream pdf 
    return $pdf->stream();
basosneo's avatar

I understand friend, now he gives me another error with the request

    ErrorException in PdfController.php line 21: Undefined variable: request
hajrovica's avatar

Change

 $cart = $request->session()->get('cart');

to

 $cart = \Session::get('cart');

I suppose $cart is giving You data in other views?

basosneo's avatar

yes friend, in the other views the car is working normally. Only in the pdf view is the difficult

Now I get the following error:

   BadMethodCallException in Controller.php line 82: Method [total] does not exist.
hajrovica's avatar

Yeah remove

    $total = $this->total();

and if you have used

 $data['total'] = $total;

because You have "carried" total() method from some other file i have just notice that total is not defined at all.

basosneo's avatar

if i remove the comand

  $total = $this->total();

i have this error;

     ErrorException in PdfController.php line 27: Undefined variable: total

if i delete the comand

  $data['total'] = $total;

i have these error;

    BadMethodCallException in Controller.php line 82: Method [total] does not exist.

is insane

hajrovica's avatar

Read the errors you have more total methods down the road, in this case on line 82 remove it, heck if this is new controller remove all except function you are working on

basosneo's avatar

these are the line 82 from controller.php

   public function __call($method, $parameters)
    {
    throw new BadMethodCallException("Method [{$method}] does not exist.");
    }

And I delete everything from my pdfcontroller and it only stays like this

  class PdfController extends Controller
   {


   public function generate()
    {
       //Get session data for cart
       $cart = \Session::get('cart');


       //some total from Your app
       $total = $this->total();

       $data['cart'] = $cart;
       

       //start pdf 
       $pdf = App::make('dompdf.wrapper');

       //load view and pass data to it 
       $pdf->loadView('pdf.pdf-teste', $data);

       //stream pdf 
       return $pdf->stream();
         } 
   }

@hajrovica Still does not work

basosneo's avatar

any? @hajrovica

Delete the total of my controller and change the total of my view, then I need to delete all my styles and it works .. now my questions are:

What styles can I add? Can I add logo images?

hajrovica's avatar

hi so if i understood correctly it works now?

For styles and images i am not sure what are You asking, but construct that view 'pdf.pdf-teste' as You would like to and when You are satisfied then pass it to PDF to render it and to clear out irregularities in pdf if any.

Next

Please or to participate in this conversation.