Rapidly Generate Simple Pdf, CSV, & Excel Report Package on Laravel

Overview

Laravel Report Generators (PDF, CSV & Excel)

Rapidly Generate Simple Pdf Report on Laravel (Using barryvdh/laravel-dompdf or barryvdh/laravel-snappy) or CSV / Excel Report (using Maatwebsite/Laravel-Excel)

This package provides a simple pdf, csv & excel report generators to speed up your workflow. It also allows you to stream(), download(), or store() the report seamlessly.

Version

Version Laravel Version Php Version Maatwebsite/Excel Ver Feature
1.0 <= 5.6 <=7.0 ~2.1.0 using chunk() to handle big data
1.1 <= 5.6 <=7.0 ~2.1.0 using cursor() to handle big data
2.0 >= 5.5 ^7.0 ^3.1 Using new version of maatwebsite (v3.1)

Find the comparison between chunk and cursor in here

Installation

Add package to your composer:

composer require jimmyjs/laravel-report-generator

If you are running Laravel > 5.5 that's all you need to do. If you are using Laravel < 5.5 add the ServiceProvider to the providers array in config/app.php

Jimmyjs\ReportGenerator\ServiceProvider::class,

Optionally, you can add this to your aliases array in config/app.php

'PdfReport' => Jimmyjs\ReportGenerator\Facades\PdfReportFacade::class,
'ExcelReport' => Jimmyjs\ReportGenerator\Facades\ExcelReportFacade::class,
'CSVReport' => Jimmyjs\ReportGenerator\Facades\CSVReportFacade::class,

Optionally, You can publish the config file (then it will be available in config/report-generator.php)

php artisan vendor:publish --provider="Jimmyjs\ReportGenerator\ServiceProvider"

If you want to generate a pdf report, please install either dompdf / snappy pdf. This package will automatically use snappy pdf. If you want to use dompdf then please change config/report-generator.php:

return [
    'flush' => false,
    'pdfLibrary' => 'dompdf'
];

For better speed on generating pdf report, I recommend you to use laravel snappy package. To using laravel snappy, you should install wkhtmltopdf to work with this package (Jump to wkhtmltopdf installation)

Example Display PDF Code

use PdfReport;

public function displayReport(Request $request)
{
    $fromDate = $request->input('from_date');
    $toDate = $request->input('to_date');
    $sortBy = $request->input('sort_by');

    $title = 'Registered User Report'; // Report title

    $meta = [ // For displaying filters description on header
        'Registered on' => $fromDate . ' To ' . $toDate,
        'Sort By' => $sortBy
    ];

    $queryBuilder = User::select(['name', 'balance', 'registered_at']) // Do some querying..
                        ->whereBetween('registered_at', [$fromDate, $toDate])
                        ->orderBy($sortBy);

    $columns = [ // Set Column to be displayed
        'Name' => 'name',
        'Registered At', // if no column_name specified, this will automatically seach for snake_case of column name (will be registered_at) column from query result
        'Total Balance' => 'balance',
        'Status' => function($result) { // You can do if statement or any action do you want inside this closure
            return ($result->balance > 100000) ? 'Rich Man' : 'Normal Guy';
        }
    ];

    // Generate Report with flexibility to manipulate column class even manipulate column value (using Carbon, etc).
    return PdfReport::of($title, $meta, $queryBuilder, $columns)
                    ->editColumn('Registered At', [ // Change column class or manipulate its data for displaying to report
                        'displayAs' => function($result) {
                            return $result->registered_at->format('d M Y');
                        },
                        'class' => 'left'
                    ])
                    ->editColumns(['Total Balance', 'Status'], [ // Mass edit column
                        'class' => 'right bold'
                    ])
                    ->showTotal([ // Used to sum all value on specified column on the last table (except using groupBy method). 'point' is a type for displaying total with a thousand separator
                        'Total Balance' => 'point' // if you want to show dollar sign ($) then use 'Total Balance' => '$'
                    ])
                    ->limit(20) // Limit record to be showed
                    ->stream(); // other available method: store('path/to/file.pdf') to save to disk, download('filename') to download pdf / make() that will producing DomPDF / SnappyPdf instance so you could do any other DomPDF / snappyPdf method such as stream() or download()
}

Note: For downloading to excel / CSV, just change PdfReport facade to ExcelReport / CSVReport facade with no more modifications

Data Manipulation

$columns = [
    'Name' => 'name',
    'Registered At' => 'registered_at',
    'Total Balance' => 'balance',
    'Status' => function($customer) { // You can do data manipulation, if statement or any action do you want inside this closure
        return ($customer->balance > 100000) ? 'Rich Man' : 'Normal Guy';
    }
];

Will produce a same result with:

$columns = [
    'Name' => function($customer) {
        return $customer->name;
    },
    'Registered At' => function($customer) {
        return $customer->registered_at;
    },
    'Total Balance' => function($customer) {
        return $customer->balance;
    },
    'Status' => function($customer) { // You can do if statement or any action do you want inside this closure
        return ($customer->balance > 100000) ? 'Rich Man' : 'Normal Guy';
    }
];

Report Output

Report Output with Grand Total

With this manipulation, you could do some eager loading relation like:

$post = Post::with('comments')->where('active', 1);

$columns = [
    'Post Title' => function($post) {
        return $post->title;
    },
    'Slug' => 'slug',
    'Latest Comment' => function($post) {
        return $post->comments->first()->body;
    }
];

Example Code With Group By

Or, you can total all records by group using groupBy method

    ...
    // Do some querying..
    $queryBuilder = User::select(['name', 'balance', 'registered_at'])
                        ->whereBetween('registered_at', [$fromDate, $toDate])
                        ->orderBy('registered_at', 'ASC'); // You should sort groupBy column to use groupBy() Method

    $columns = [ // Set Column to be displayed
        'Registered At' => 'registered_at',
        'Name' => 'name',
        'Total Balance' => 'balance',
        'Status' => function($result) { // You can do if statement or any action do you want inside this closure
            return ($result->balance > 100000) ? 'Rich Man' : 'Normal Guy';
        }
    ];

    return PdfReport::of($title, $meta, $queryBuilder, $columns)
                    ->editColumn('Registered At', [
                        'displayAs' => function($result) {
                            return $result->registered_at->format('d M Y');
                        }
                    ])
                    ->editColumn('Total Balance', [
                        'class' => 'right bold',
                        'displayAs' => function($result) {
                            return thousandSeparator($result->balance);
                        }
                    ])
                    ->editColumn('Status', [
                        'class' => 'right bold',
                    ])
                    ->groupBy('Registered At') // Show total of value on specific group. Used with showTotal() enabled.
                    ->showTotal([
                        'Total Balance' => 'point'
                    ])
                    ->stream();

PLEASE TAKE NOTE TO SORT GROUPBY COLUMN VIA QUERY FIRST TO USE THIS GROUP BY METHOD.

Output Report With Group By Registered At

Output Report with Group By Grand Total

Wkhtmltopdf Installation

  • Download wkhtmltopdf from https://wkhtmltopdf.org/downloads.html
  • Change your snappy config located in /config/snappy.php (run php artisan vendor:publish if snappy.php file is not created) to:
    'pdf' => array(
        'enabled' => true,
        'binary'  => '/usr/local/bin/wkhtmltopdf', // Or specified your custom wkhtmltopdf path
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    ),

Other Method

1. setPaper($paper = 'a4')

Supported Media Type: PDF

Description: Set Paper Size

Params:

  • $paper (Default: 'a4')

Usage:

PdfReport::of($title, $meta, $queryBuilder, $columns)
         ->setPaper('a6')
         ->make();

2. setCss(Array $styles)

Supported Media Type: PDF, Excel

Description: Set a new custom styles with given selector and style to apply

Params:

  • Array $styles (Key: $selector, Value: $style)

Usage:

ExcelReport::of($title, $meta, $queryBuilder, $columns)
            ->editColumn('Registered At', [
                'class' => 'right bolder italic-red'
            ])
            ->setCss([
                '.bolder' => 'font-weight: 800;',
                '.italic-red' => 'color: red;font-style: italic;'
            ])
            ->make();

3. setOrientation($orientation = 'portrait')

Supported Media Type: PDF

Description: Set Orientation to Landscape or Portrait

Params:

  • $orientation (Default: 'portrait')

Usage:

PdfReport::of($title, $meta, $queryBuilder, $columns)
         ->setOrientation('landscape')
         ->make();

4. withoutManipulation()

Supported Media Type: PDF, Excel, CSV

Description: Faster generating report, but all columns properties must be matched the selected column from SQL Queries

Usage:

$queryBuilder = Customer::select(['name', 'age'])->get();
$columns = ['Name', 'Age'];
PdfReport::of($title, $meta, $queryBuilder, $columns)
         ->withoutManipulation()
         ->make();

5. showMeta($value = true)

Supported Media Type: PDF, Excel, CSV

Description: Show / hide meta attribute on report

Params:

  • $value (Default: true)

Usage:

PdfReport::of($title, $meta, $queryBuilder, $columns)
         ->showMeta(false) // Hide meta
         ->make();

6. showHeader($value = true)

Supported Media Type: PDF, Excel, CSV

Description: Show / hide column header on report

Params:

  • $value (Default: true)

Usage:

PdfReport::of($title, $meta, $queryBuilder, $columns)
         ->showHeader(false) // Hide column header
         ->make();

7. showNumColumn($value = true)

Supported Media Type: PDF, Excel, CSV

Description: Show / hide number column on report

Params:

  • $value (Default: true)

Usage:

PdfReport::of($title, $meta, $queryBuilder, $columns)
         ->showNumColumn(false) // Hide number column
         ->make();

8. simple()

Supported Media Type: Excel

Description: Generate excel in simple mode (no styling on generated excel report, but faster in generating report)

Params:

  • None

Usage:

ExcelReport::of($title, $meta, $queryBuilder, $columns)
         ->simple()
         ->download('filename');
Comments
  • How to generate report for parent child relationship

    How to generate report for parent child relationship

    Hello,

    I have two tables:

    1. Parent table - Having parentId, parentName, parentGender
    2. Child table - Having childid, parentid, childname, child gender, childbirthdate

    I want to generate report something like

    Parent Name, Parent Gender Child Name, Child Date of Birth, Child Gender

    Now e.g. Parent table has 2 records:

    1. Tom, Male
    2. Jerry, Female

    Child table has 3 records.

    1. Parent Id - 1, Child Name - Bob, Child Gender - Male, DOB - 20thFeb2016
    2. Parent Id - 1, Child Name - Tos, Child Gender - Female, DOB - 14Jan2014
    3. Parent Id - 2, Child Name - Mary, Child Gender - Female, DOB - 17Sept2017

    How to generate such report where single parent can have 2 child rows after that another parent has 1 child row etc.

    Please advise.

    opened by bkinnari 8
  • Report Generator did not install

    Report Generator did not install

    I got the following error trying to install: "Your requirements could not be resolved to an installable set of packages" "Problem 1

    • Conclusion: remove Laravel/Framewokr v5.8.17
    • Conclusion: don't install Laravel/framework v5.8.17" Isnt framework the base of laravel?
    opened by dan3460 7
  • Compatibility with Maatwebsite excel 3.0

    Compatibility with Maatwebsite excel 3.0

    Hi, I would like to use Maatwebsite Excel 3.0 and report generator but report generator requires 2.1.* and I am not able to use thge package. Will this be compatible with Excel 3.0?

    opened by tszaniszlo 7
  • I'm try like this, but i can't get pdf report.

    I'm try like this, but i can't get pdf report.

    public function report(){
        $title = 'Registered User Report';
    
        $meta = [
            'Registered on To ',
            'Sort By'
        ];
    
        $queryBuilder = User::select(['emp_code', 'first_name', 'middle_name', 'last_name']);
    
        $columns = [
            'EMP Code' => 'emp_code',
            'First Name' => 'first_name',
            'Middle Name' => 'middle_name',
            'Last Name' => 'last_name'
        ];
    
        return PdfReport::of($title, $meta, $queryBuilder, $columns)
            ->limit(20)
            ->stream();
    }
    

    capture

    opened by dilshan8kt 6
  • facing issue `Method Illuminate\Database\Eloquent\Collection::cursor does not exist` while creating and downloading PdfReport

    facing issue `Method Illuminate\Database\Eloquent\Collection::cursor does not exist` while creating and downloading PdfReport

    Method Illuminate\Database\Eloquent\Collection::cursor does not exist. (View: ~demo_project\vendor\jimmyjs\laravel-report-generator\src\views\general-pdf-template.blade.php)

    image

    how do resolve this??

    opened by iabduul7 4
  • CSV Report adds number column without header, causing wrong header order

    CSV Report adds number column without header, causing wrong header order

    In CSV Report generation, no. column header is not being added but number is added in value, this causes wrong header order. Ex.

    my_column_1 my_column_2 my_column_3 my_column_4 auto_added_no my_val_1 my_val_2 my_val_3 my_val_4

    Is this expected behavior?

    Also we can't use showNumColumn in CSV to prevent this

    opened by kambadprashant 4
  • cursor() doesn't use eager loading of relationships

    cursor() doesn't use eager loading of relationships

    Is there any work around to avoid the n + 1 query issues? Model::with('relation') isn't respected for cursors so do we just have no choice at this point?

    opened by localpath 3
  • Possbile to add ->save() or ->store() on all 3 reports?

    Possbile to add ->save() or ->store() on all 3 reports?

    I am looking a easier way to store files locally on the server, not downloading or streaming. What I am trying to do is setting a scheduling service, auto creating reports and leaving them on server for user to download, or email them the report.

    I know for ExcelReport you can make() then store() the LaravelExcelWriter object, and for CSV you can set path in Writer::createFromPath then store all data by using insertAll().

    Do you think you can create something like store() that can store file on server for all 3 reports PdfReport, ExcelReport and CSVReport?

    opened by ckegg 3
  • Undefined property: stdClass::$i_d on vendor/jimmyjs/laravel-report-generator/src/views/general-pdf-template.blade.php

    Undefined property: stdClass::$i_d on vendor/jimmyjs/laravel-report-generator/src/views/general-pdf-template.blade.php

    test.blade.php

     <form method="GET" action="/generateItemsReport">
                            @csrf
                            <button class="py-2 px-4 bg-blue-400 hover:bg-blue-600 rounded-lg">Generate Report</button>
                        </form>
    

    and this is web.php

    Route::get("/generateItemsReport", [ReportController::class, 'GenerateItemsReport']);
    

    and this is GenerateItemsReport method on ReportController

    $items = DB::table("items")
                ->leftJoin("category", function ($join) {
                    $join->on("items.category_id", "=", "category.id");
                })
                ->select("items.id as item_id", "items.name as name", "items.purchase_price", "items.selling_price", "category.name as category_name")
                ->groupBy("items.id", "items.name", "items.purchase_price", "items.selling_price", "items.category_id", "category.name", "category.id");
    
    
            $title = 'Items by Category';
            $meta = [
                'Date' => now()
            ];
    
            $columns = [
                "ID", "Name", "Purchase Price", "Selling Price", "Category Name"
            ];
    
            $pdf = new PdfReport();
    
            return $pdf->of($title, $meta, $items, $columns)->stream();
    

    its produce

    Screenshot from 2021-10-04 18-08-34

    opened by z41dth3c0d3r 2
  • Call to undefined method Symfony\\Component\\HttpFoundation\\StreamedResponse::header()?

    Call to undefined method Symfony\\Component\\HttpFoundation\\StreamedResponse::header()?

    Hola all,

    I have installed lib using composer and using laravel-dompdf.

    First issue that i am facing is that when i use this package i get

    Illuminate\Contracts\Container\BindingResolutionException Target class [snappy.pdf.wrapper] does not exist.

    but default it's taking snappy for report generation but when i install snappy using

    composer require barryvdh/laravel-snappy i get error as below :

    Call to undefined method Symfony\Component\HttpFoundation\StreamedResponse::header()?

    Any help is appreciated for this .

    Sample code :

    public function displayReport()
    {
    
      $title = 'Registered User Report'; 
    
      $meta = [
      ];
    
      $queryBuilder = User::select(['name']);
    
      $columns = [ 
    	'Name' => 'name',
           'Registered On' => function($queryBuilder){
                    return $queryBuilder->created_at;
                }
      ];
    
      return PdfReport::of($title, $meta, $queryBuilder, $columns)
    	->limit(20) 
    	->stream(); 
    }
    
    
    opened by ershadow786 2
  • Target class [snappy.pdf.wrapper] does not exist.

    Target class [snappy.pdf.wrapper] does not exist.

    I am already using laravel-dompdf for invoice generation. But, when I use this package to generate a report. this is all I get.

    Illuminate\Contracts\Container\BindingResolutionException
    Target class [snappy.pdf.wrapper] does not exist.
    

    The code I use for a dummy report generation is,

    public function displayReport()
    {
    
      $title = 'Registered User Report'; 
    
      $meta = [
      ];
    
      $queryBuilder = User::select(['name']);
    
      $columns = [ 
    	'Name' => 'name',
      ];
    
      return PdfReport::of($title, $meta, $queryBuilder, $columns)
    	->limit(20) 
    	->stream(); 
    }
    

    In the package source code file, PdfReport.php

    try {
      $pdf = \App::make('snappy.pdf.wrapper');
      $pdf->setOption('footer-font-size', 10);
      $pdf->setOption('footer-left', 'Page [page] of [topage]');
      $pdf->setOption('footer-right', 'Date Printed: ' . date('d M Y H:i:s'));
    } catch (\ReflectionException $e) {
      try {
        $pdf = \App::make('dompdf.wrapper');
      } catch (\ReflectionException $e) {
        throw new \Exception('Please install either barryvdh/laravel-snappy or laravel-dompdf to generate PDF Report!');
      }
    }
    

    If I change interchange the detection of snappy and dompdf wrappers like this,

    try {
       $pdf = \App::make('dompdf.wrapper');
    } catch (\ReflectionException $e) {
      try {
        $pdf = \App::make('snappy.pdf.wrapper');
        $pdf->setOption('footer-font-size', 10);
        $pdf->setOption('footer-left', 'Page [page] of [topage]');
        $pdf->setOption('footer-right', 'Date Printed: ' . date('d M Y H:i:s'));
      } catch (\ReflectionException $e) {
        throw new \Exception('Please install either barryvdh/laravel-snappy or laravel-dompdf to generate PDF Report!');
      }
    }
    

    it works perfectly.

    Any help on this is much appreciated. Thanks.

    opened by pravnkay 2
  • number of pages not showing up in footer

    number of pages not showing up in footer

    i am trying get number of pages in my pdf currently in using dompdf , i was working with snappy it had the number of pages values but with the dompdf in not showing up .

    opened by fareed-baloch 1
  • Add Method Set Total Label for change label total and Modify showTotal method for custom operation.

    Add Method Set Total Label for change label total and Modify showTotal method for custom operation.

    • Add setTotalLabel Method
    return PdfReport::of($title, $meta, $queryBuilder, $columns)
           ->setTotalLabel('Total');
    

    Modify showTotal method for change object options and add option function for values "sum", "avg" or function($total).

    return PdfReport::of($title, $meta, $queryBuilder, $columns)
    ->setTotalLabel('Total')
    ->showTotal([
    'Percentage' => [
    'format' => 'point',
    'function' => function($total) {
    return round(($total['COLUMN_NAME1'] / $total['COLUMN_NAME2']) *100);
    }
    ]
    ]);
    
    opened by 3dluis 1
  • Generating a report with Ajax

    Generating a report with Ajax

    Can I generate a report with an Ajax request? I'm using JQuery's ajax method to pass the data to my controller, it gets to the server but the response is odd, is there a way to generate the report in a pop-up window o a blank window?

    opened by danielalejandromatheus 6
Releases(2.2.0)
Magento 2 Invoice PDF Generator - helps you to customize the pdf templates for Magento 2

Magento 2 Invoice PDF Generator - helps you to customize the pdf templates for Magento 2. If you have an enabled template and a default template for the store you need your template the system will print the pdf template.

EAdesign 64 Oct 18, 2021
Generate simple PDF invoices with PHP

InvoiScript Generate simple PDF invoices with PHP. Installation Run: composer require mzur/invoiscript Usage Example use Mzur\InvoiScript\Invoice; re

Martin Zurowietz 16 Aug 24, 2022
Generate PDF invoices for your customers in laravel

What is Invoices? Invoices is a Laravel library that generates a PDF invoice for your customers. The PDF can be either downloaded or streamed in the b

Erik C. Forés 399 Jan 2, 2023
Official clone of PHP library to generate PDF documents and barcodes

TCPDF PHP PDF Library Please consider supporting this project by making a donation via PayPal category Library author Nicola Asuni [email protected] co

Tecnick.com LTD 3.6k Jan 6, 2023
Generate pdf file with printable labels

printable_labels_pdf Generate pdf file with printable labels with PHP code. CREATE A PDF FILE WITH LABELS EASELY: You can get a pdf file with labels f

Rafael Martin Soto 5 Sep 22, 2022
Official clone of PHP library to generate PDF documents and barcodes

TCPDF PHP PDF Library Please consider supporting this project by making a donation via PayPal category Library author Nicola Asuni [email protected] co

Tecnick.com LTD 3.6k Dec 26, 2022
A PHP report generator

PHPJasper A PHP Report Generator Docs About PHPJasper is the best solution to compile and process JasperReports (.jrxml & .jasper files) just using PH

PHPJasper 404 Dec 29, 2022
Simple wrapper package around MPDF's setProtection method that allows you to set password on PDF files

Laravel PDF Protect (fork) Simple wrapper package around MPDF's setProtection method that allows you to set password on PDF files. Installation You ca

Raphael Planer 2 Jan 23, 2022
A Laravel package for creating PDF files using LaTeX

LaraTeX A laravel package to generate PDFs using LaTeX · Report Bug · Request Feature For better visualization you can find a small Demo and the HTML

Ismael Wismann 67 Dec 28, 2022
Laravel package to convert HTML to PDF, supporting multiple drivers.

eve/pdf-converter A Laravel package to help convert HTML to PDF. Supports multiple drivers. Requirements and Installation eve/pdf-converter requires L

eve.io 11 Feb 15, 2022
Laravel Snappy PDF

Snappy PDF/Image Wrapper for Laravel 5 and Lumen 5.1 This package is a ServiceProvider for Snappy: https://github.com/KnpLabs/snappy. Wkhtmltopdf Inst

Barry vd. Heuvel 2.3k Jan 2, 2023
Convert HTML to PDF using Webkit (QtWebKit)

wkhtmltopdf and wkhtmltoimage wkhtmltopdf and wkhtmltoimage are command line tools to render HTML into PDF and various image formats using the QT Webk

wkhtmltopdf 13k Jan 4, 2023
HTML to PDF converter for PHP

Dompdf Dompdf is an HTML to PDF converter At its heart, dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is

null 9.3k Jan 1, 2023
PHP library generating PDF files from UTF-8 encoded HTML

mPDF is a PHP library which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF (see CREDITS), with a number of enhancement

null 3.8k Jan 2, 2023
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage

Snappy Snappy is a PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. It uses the excellent webkit-based wkhtmltopd

KNP Labs 4.1k Dec 30, 2022
TCPDF - PHP PDF Library - https://tcpdf.org

tc-lib-pdf PHP PDF Library UNDER DEVELOPMENT (NOT READY) UPDATE: CURRENTLY ALL THE DEPENDENCY LIBRARIES ARE ALMOST COMPLETE BUT THE CORE LIBRARY STILL

Tecnick.com LTD 1.3k Dec 30, 2022
Pdf and graphic files generator library written in php

Information Examples Sample documents are in the "examples" directory. "index.php" file is the web interface to browse examples, "cli.php" is a consol

Piotr Śliwa 335 Nov 26, 2022
PdfParser, a standalone PHP library, provides various tools to extract data from a PDF file.

PdfParser Pdf Parser, a standalone PHP library, provides various tools to extract data from a PDF file. Website : https://www.pdfparser.org Test the A

Sebastien MALOT 1.9k Jan 2, 2023
Convert html to an image, pdf or string

Convert a webpage to an image or pdf using headless Chrome The package can convert a webpage to an image or pdf. The conversion is done behind the sce

Spatie 4.1k Jan 1, 2023