首页 > 解决方案 > Dompdf 在 laravel 中使用 post 方法返回乱码数据

问题描述

我正在使用 dompdf 生成和下载 PDF 文件,但是当我通过 POST 请求调用控制器方法时,它只返回乱码数据而不是下载文件。我不知道我在这里做错了什么。

这是我对控制器的 Ajax 请求。

            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
                })
            });

这是控制器方法。

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();

}

但是我得到的响应而不是下载的文件是这种格式

  %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

标签: laravelmpdf

解决方案


我从这篇文章中得到了一个解决方案:Handle file download from ajax post

(这是纯javascript顺便说一句)

我进行了更改以适合您的代码(顺便说一句,没有对其进行测试):

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);

已编辑希望它有效!


推荐阅读