Search code examples
laraveldompdf

DomPDF does not download file for AJAX request on Laravel


I'm working on 'DomPDF' using Ajax Post request on Laravel project. Below is ajax code.

       $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url:"{{ route('screen.pdfticket') }}",
            method:"POST",
            data:{
                id:$('#screenid').val()
            },
            success:function(data){
                console.log(data);
            }
        });

And below is code in controller.

    $customPaper = array(0,0,216,158);
    $pdf->loadView("screen.ticket" , [ 
        'clinic' => 'clinic name' , 
        'queno' => $screen->que
    ])->setPaper($customPaper, 'landscape');
    return $pdf->download($screen->que .'.pdf');  

I can get correct response but it's not readable format. I would like to save in pdf format after ajax called success instead. Any advise or guidance would be greatly appreciated, Thanks.


Solution

  • Since you're making the request using AJAX, you need a way to have the browser load the resource.

    There are ways to go but not limited to the following:

    • Return the resource URL in the response to the AJAX request then make a separate browser request to load the resource.

    • Make a blob of the resource response to the AJAX request then load it from the blob's URL.
      This is shown in the example below.

    function downloadFile(response) {
      var blob = new Blob([response], {type: 'application/pdf'})
      var url = URL.createObjectURL(blob);
      location.assign(url);
    } 
    
    $.ajax({
      url: "{{ route('screen.pdfticket') }}",
      method: 'POST',
      data: {
        id: $('#screenid').val()
      }
    })
    .done(downloadFile);