0

I am working with dompdf to generate and download PDF files, but when I call controller method via POST request, it just returns gibberish data instead of downloading the file. I don't know what I'm doing wrong here.

This is my Ajax Request to Controller.

            fetch('/exportPDF',{
                method: 'POST',
                cache: 'no-cache',
                credentials: 'same-origin',
                headers: {
                    'Content-type': 'application/json',
                    "X-CSRF-TOKEN": token
                },
                referrerPolicy: 'no-referrer',
                body: JSON.stringify({
                    record: appendTotalRecord
                })
            });

This is the Controller method.

public function exportCandidates(Request $request){
   $count_candidates = count($request->record[0]); 
   $basic =  implode("`,`", array_filter($request->record[1]));
   $academic =  implode("`,`", array_filter($request->record[2]));
   $experience =  implode("`,`", array_filter($request->record[3]));
   for($i = 0 ; $i < $count_candidates ; $i++){
       $id =  $request->record[0][$i];
       $basic_info[$i] = user::select(DB::raw("`".$basic."`"))->where('id', $id)->get()->toArray();
       $academic_info[$i] = acadamic_record::where('user_id', $id)->select(DB::raw("`".$academic."`"))->get()->toArray();
       $experience_info[$i] = Experience::where('id', $id)->select(DB::raw("`".$experience."`"))->get()->toArray();   
}

    $response_array = array(
        'basic' => $basic_info,
        'academic' => $academic_info,
        'experience' => $experience_info
    );

    $html = \View::make("pdf")->with('response', $response_array);
    $pdf = PDF::LoadHTML($html);
    return $pdf->download();

}

But the response I get instead of downloaded file is in this format

  %PDF-1.3
    1 0 obj
    << /Type /Catalog
    /Outlines 2 0 R
    /Pages 3 0 R >>
    endobj
    2 0 obj
    << /Type /Outlines /Count 0 >>
    endobj
    3 0 obj
    << /Type /Pages
    /Kids [6 0 R
    ]
    /Count 1
    /Resources <<
    /ProcSet 4 0 R
    /Font << 
    /F1 8 0 R
    /F2 9 0 R
    >>
    >>
    /MediaBox [0.000 0.000 595.280 841.890]
     >>
    endobj
    4 0 obj
    [/PDF /Text ]
    endobj
    5 0 obj
    <<
    /Producer (þÿdompdf <6782abfc> + CPDF)
    /CreationDate (D:20200228160323+05'00')
    /ModDate (D:20200228160323+05'00')
    /Title (þÿDocument)
    >>
    endobj
    6 0 obj
    << /Type /Page
    /MediaBox [0.000 0.000 595.280 841.890]
    /Parent 3 0 R
    /Contents 7 0 R
    >>
    endobj
    7 0 obj
    << /Filter /FlateDecode
    /Length 67 >>
    stream
    xã2Ð300P@&Ò¹BMôÍÌÍ,ô,-LBRôÝ¢
    !i

    Ñ©99ù±
    !^
    ®!~Ä
    endstream
    endobj
    8 0 obj
    << /Type /Font
    /Subtype /Type1
    /Name /F1
    /BaseFont /Times-Roman
    /Encoding /WinAnsiEncoding
    >>
    endobj
    9 0 obj
    << /Type /Font
    /Subtype /Type1
    /Name /F2
    /BaseFont /Times-Bold
    /Encoding /WinAnsiEncoding
    >>
    endobj
    xref
    0 10
    0000000000 65535 f 
    0000000009 00000 n 
    0000000074 00000 n 
    0000000120 00000 n 
    0000000284 00000 n 
    0000000313 00000 n 
    0000000500 00000 n 
    0000000603 00000 n 
    0000000741 00000 n 
    0000000850 00000 n 
    trailer
    <<
    /Size 10
    /Root 1 0 R
    /Info 5 0 R
    /ID[<ec8e072527b7823c3fd7c71f434dbb36><ec8e072527b7823c3fd7c71f434dbb36>]
    >>
    startxref
    958
    %%EOF
Hassan Malik
  • 130
  • 11
  • You are retrieving the data of the pdf file itself, give me 5 minutes and I will try to help you with an answer ;) – ItsEdgar94 Feb 28 '20 at 11:28

1 Answers1

0

I get a solution from this post: Handle file download from ajax post

(It's pure javascript btw)

I made changes to fit your code (didn't test it btw):

var formData = new FormData();
formData.append("record", appendTotalRecord);

var xhr = new XMLHttpRequest();
xhr.open('POST', '/exportPDF', true); //Try to use the route helper from laravel
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
    if (this.status === 200) {
        var filename = "";
        var disposition = xhr.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }
        var type = xhr.getResponseHeader('Content-Type');

        var blob;
        if (typeof File === 'function') {
            try {
                blob = new File([this.response], filename, { type: type });
            } catch (e) { /* Edge */ }
        }
        if (typeof blob === 'undefined') {
            blob = new Blob([this.response], { type: type });
        }

        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob(blob, filename);
        } else {
            var URL = window.URL || window.webkitURL;
            var downloadUrl = URL.createObjectURL(blob);

            if (filename) {
                // use HTML5 a[download] attribute to specify filename
                var a = document.createElement("a");
                // safari doesn't support this yet
                if (typeof a.download === 'undefined') {
                    window.location = downloadUrl;
                } else {
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                }
            } else {
                window.location = downloadUrl;
            }

            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
        }
    }
};
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', token);
xhr.send(formData);

EDITED Hope it works!

ItsEdgar94
  • 344
  • 1
  • 8
  • No, it is returning another issue. When I use this script this does not return anything in the $request parameter and I can't access any data without that. I have edited my question. Hope it will help you understand better – Hassan Malik Feb 28 '20 at 12:27
  • Oops, forgot to put your headers, try now – ItsEdgar94 Feb 28 '20 at 13:05