Laravel Dompdf Print Multiple Charts Step By Step 2020

So today we are going to Print charts on pdf. Using laravel and dompdf.

Complete Step By Step Practical Guide

Create a project

So create a project first if you have't. Check laravel guide for creating new project.

If you have your project up and running in any of the view file you can have your charts as you like but for this post we are going to add it in "welcome.blade.php". The view file you get out of the box from laravel.

Make welcome.blade.php file empty remove all links and custom html. It should look like this.

 <!DOCTYPE html><html lang="">    <head>        <meta charset="utf-8">        <meta name="viewport" content="width=device-width, initial-scale=1">        <title>Laravel</title>        <!-- Styles -->        <style>        </style>    </head><body></body></html>

Lets add charts into view

In view file we include google cdn so we can use "google charts".We also add a div with id "draw-charts", where all charts will be rendered. Then we have array of data that we will use to print charts. Have a look

 <body>
   <div class="flex-center position-ref full-height">
       <div class="content">
          <div align="center">
               //Charts will print here appending this div
               <div id="draw-charts"></div>
          </div>
//LOADING JQUERY CDN 
<script src="https://code.jquery.com/jquery-3.5.1.js"
 integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
 crossorigin="anonymous"></script>
//LOADING GOOGLE CDN
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>


<script type="text/javascript">
                $(function(){
                    //ARRAY OF DATA
                            let weekOne = [
                                              ['Week', 1],
                                              ['Sunday', 800],
                                              ['Monday', 500],
                                              ['Tuesday', 690],
                                              ['Wednesday', 467],
                                              ['Friday', 890]
                                            ];

                            let weekTwo = [
                                              ['Week', 2],
                                              ['Sunday', 340],
                                              ['Monday', 670],
                                              ['Tuesday', 620],
                                              ['Wednesday', 497],
                                              ['Friday', 290]
                                            ];

                            let weekThree = [
                                              ['Week', 3],
                                              ['Sunday', 540],
                                              ['Monday', 234],
                                              ['Tuesday', 520],
                                              ['Wednesday', 297],
                                              ['Friday', 990]
                                            ];
//FINAL ARRAY OF ARRAYS WILL BE USED TO PRINT CHARTS
let weeksData = [weekOne,weekTwo,weekThree];
//LOOPING THROUGH ARRAYS
for(let r =0; r<weeksData.length; r++){
   //APPENDING DIVS SO WE CAN HAVE CHART ON EACH DIV
   $("#draw-charts").append("<div id='draw-charts"+r+"'></div>");
       google.charts.load('current',{
               callback: function(){
                  var data = new google.visualization.DataTable();
                 //ADDING COLUMN WITH DEFINING TYPE OF CONTENT
                  data.addColumn('string','Days');
                  data.addColumn('number','Income');
                   //ADDING DATA TO GOOGLE CHART
                  data.addRows(weeksData[r]);
                  //SETTING TITLE WIDTH AND HEIGHT OF CHARTS
                  var options = {
                      title:"Printing Charts In Loop",
                      width:300,
                      height:200
                    };
      let chart_div = document.getElementById("draw-charts"+r);
      let chart = new google.visualization.PieChart(chart_div);
   google.visualization.events.addListener(chart,'ready',function(){
   //DISPLAYING CHARTS AS IMAGES
   chart_div.innerHTML = '<img src="'+chart.getImageURI() +'">';
        });

   chart.draw(data,options);
   },
   packages: ['corechart']
 })
}
</div>
</div>
</body>

So in above code we are looping through "weeksData" array. and each time we loop through we are appending a div to another div with id "draw-charts".

 $("#draw-charts").append("<div id='draw-charts"+r+"'></div>");

We are defining data

 //that array should have 1st value string
data.addColumn('string','Days');
//so in our array we have value as string days
['Week', 3],
//second value should be number so we have number
data.addColumn('number','Income');
['Sunday', 540],

//Passing all array data as rows
//r will be changing on each loop iteration.
data.addRows(weeksData[r]);


//Defining title, width, and height of charts
 var options = {
         title:"Printing Charts In Loop",
         width:300,
         height:200
      };                  
                  
                 

Setting output charts as image

 //Charts will print as images then we can pass them to print on pdf
chart_div.innerHTML = '<img src="'+chart.getImageURI() +'">';

//drawing charts with variables data and options
chart.draw(data,options);

Output should be something like this

It's time to print charts on pdf.

Add a form with input type hidden and set HTML data from div with id "draw-charts" to that input as all charts are appending to div with id "draw-charts".

  <form action="/print_chart" method="post" enctype="multipart/form-data">
     @csrf
     //input with type hidden
    <input type="hidden" name="chartData" id="chartInputData">
    <input type="submit" value="Print Chart">
</form>

Set html data to hidden input

 //Setting chart data to Input
    setTimeout(function(){
         let chartsData = $("#draw-charts").html();
         $("#chartInputData").val(chartsData);
    },1000);

So once the charts loded on page after 1 second. Add charts html content to input with id "chartInputData" and type hidden. In the form action is set to "/print_chart". So we need to create a route for it. So go into routes/web.php. and add a route something like this.

 //Route for main blade 
Route::get('/', function () {
    return view('welcome');
});

//Route for printing pdf 
Route::post('/print_chart',[
	'uses'=>'ChartController@print'
]);

In our route we are using ChartController and print method. So let's Create it. In terminal navigate to project folder and run this command.

 php artisan make:controller ChartController

It will create a controller under App/http/Controller. Go there and open this ChartController and define a function with name print.

 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;


class ChartController extends Controller
{
    public function print(Request $request){

    }
}

Time to install Dompdf Package

Install Dompdf Package using this command. Read official documentation or follow these steps.

 //RUN THIS COMMAND IN TERMINAL ON PROECT DIRECTORY
composer require barryvdh/laravel-dompdf

//go to config/app.php and under providers add this line
Barryvdh\DomPDF\ServiceProvider::class,

//In the same file config/app.php under "aliases" add this line
'PDF' => Barryvdh\DomPDF\Facade::class,

Now run this command in project directory

 php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

It will create a config file for DOMPDF under "config/dompdf.php". Go there and open this file and change temp directory path. See here

 //For MacOS
"temp_dir" => '/Applications/XAMPP/xamppfiles/temp',

//skip for other operating systems if face error the check dompdf documentation

Print PDF

DOMPDF is all set. So go to ChartController and add DomPDF code something like this

 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
//Calling DOMPDF
use PDF;

class ChartController extends Controller
{
    public function print(Request $request){
        //Getting chart data from hidden input field
    	$data = $request->chartData;
        //passing data to temp view blade file 
    	$pdf = PDF::loadView('temp',compact('data'));
        //generating pdf
    	return $pdf->download('charts.pdf');

    }
}

In above code we are calling DOMPDF as PDF. and loading a view and then generating pdf using that view. Note we are also passing data into view file. Wait we missed the "temp" view file which is converting into pdf, So let's create it. it should look something like this.

 <!DOCTYPE html>
<html>
<head>
	<title>Dom PDF Printing Google Charts</title>
</head>
<body>

	<h1>Printing Multiple Charts Using DomPdf In Loop </h1>
	<div align="center">
                //checking if data present
		@if($data)
                        //printing data if present
			{!! $data !!}
		@endif
	</div>
</body>
</html>

So we are getting data in "temp view" file and then we are printing it using DOMPDF. Check Video Guide For More Info