etzzz
etzzz

Reputation: 165

Unable to generate pdf in laravel controller

I had write some sample codes to generate pdf in my laravel controller. It get a 200 response code but the pdf is not generating.

Below is my code.

function exportPDF() {
    // instantiate and use the dompdf class
    $dompdf = new PDF();
    $dompdf->loadHtml('<h1>hello world</h1>');

    // (Optional) Setup the paper size and orientation
    $dompdf->setPaper('A4', 'landscape');

    // Render the HTML as PDF
    $dompdf->render();

    // Output the generated PDF to Browser
    return $dompdf->stream();
}

But this is working when i directly include the code inside route in web.php file.

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

EDITED

web.php

Route::post('/report-audit-export-pdf', 'ReportAuditController@exportPDF');

.js

window.exportPDF = function() {
  var hidden_category = $('#hidden_category').val();
  $.ajax({
      type: "POST",
      url: '/report-audit-export-pdf',
      data: {

      },
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      error: function(jqXHR, textStatus, errorThrown) {
          console.log("jqXHR : " + jqXHR + " and textStatus : " + textStatus + " and errorThrown : " + errorThrown);
      },
      success: function(content) {
        // alert("Success");
      }
  }); 
}

May i know what the problem is?

Upvotes: 0

Views: 1308

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

You cannot generate PDFs via Ajax because Ajax requests expect a response, which Laravel sends back as JSON by default. So what you could do, is make a normal GET route that will display the PDF e.g:

Route::get('display-pdf', 'ReportAuditController@exportPDF');

Since your ajax does not POST any data (your data object is empty), you could bypass your ajax request and simply use an anchor

<a href="/display-pdf">Display PDF</a>

If for some reason, you still want to use Ajax, you can use the success response from the ajax request like this

$.ajax({
    type: "POST",
    url: '/data-url',
    data: {},
    success: function(content) {
        window.location.href = '/display-pdf';
    }
}); 

Upvotes: 1

Related Questions