Export PDF from laravel

491 0 0 0

Last Updated : 2024-04-28 04:26:52

Incase you want to export HTML content as a PDF file in laravel here is a simple package that you could use: https://github.com/barryvdh/laravel-dompdf


  1. Use the following package and run the following code:
    composer require barryvdh/laravel-dompdf​


  2. - Create a method that will accept the HTML code
    use PDF;

    /**
    * Export the weekly report as PDF
    */
    public function exportPDF(Request $request) {
    $htmlCode = $request->post('htmlContent');

    $cssFile = url('/css/DomPDF.css');
    $pdf = PDF::loadHtml("<link type='text/css' href='{$cssFile}' rel='stylesheet' />".$htmlCode);
    return $pdf->download('testPDFDownloaded.pdf');
    }​


  3. - Create a route
    Route::match(['get', 'post'], 'exportPDF/{htmlContent?}', [TheController::class, 'exportPDF'])->name('exportPDF');​


  4. - Create the blade that will hold pdf download BTN
    {{-- ------------------------------- EXPORT FORM ----------------------------- --}}
    <form id="exportPDFForm" method="post" action="{{ URL::route('exportPDF') }}" >
    <input type="hidden" name="_token" value="{{csrf_token()}}" />
    <input type="hidden" name="htmlContent" value=""/>

    <div class="container-fluid text-right" style="margin:5px;">
    <div class="col-xs-12 text-right">
    <button class="btn btn-success" id="exportPDFBTN">Export PDF</button>
    </div>
    </div>
    </form>
    {{-- ------------------------------- EXPORT FORM ----------------------------- --}}​


  5. -

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .