【问题标题】:Transfering pdf from backend to frontend on request jQuery根据请求jQuery将pdf从后端传输到前端
【发布时间】:2019-11-18 07:09:35
【问题描述】:

如标题中所述,我正在尝试使用 jquery 将 pdf 从后端 php 传递到前端。

示例 php 代码。

public function printPdf(){
    header('Content-Disposition: attachment; filename="kainos.pdf"');
    $html = $this->request->post['pdf'];
    $mpdf = new \Mpdf\Mpdf();
    $mpdf->WriteHTML('<div>Section 1 text</div>');
    return $mpdf->Output();
}
function(response){
    var blob=new Blob([response], { type: 'application/pdf' });
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="Kainos.pdf";
    link.click();
}

我得到的是空的pdf。

我知道的:

数据正在正确传输,因为可以使用 javascript console.log 传输和查看纯 html

正在生成 PDF,因为我可以将函数的内容移动到其他函数并在其他页面中获取 pdf,但我不需要它。

我怀疑 pdf 在传输过程中被破坏,但似乎找不到任何信息 关于如何解决它。任何帮助表示赞赏

编辑

问题不在我发送的方法中,而是在 jquery 中,它处理 blob 很奇怪,所以我正在用 vanila js 重写所有内容。

var xhr = new XMLHttpRequest();
xhr.open('POST', document.location.origin + '/somelocation.php', true);
    //Send data to server
    xhr.send({$("#pdf").html()});
    //Set response type to file
    xhr.responseType = "blob";
    
    //On response do...
    xhr.onload = () => {
        //Create file in client side from xhr response
        var blob=new Blob([xhr.response], { type: 'application/pdf' });
        //create clickable element to download file and click it.
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download="kainos.pdf";
        link.click();
    }
});

【问题讨论】:

标签: javascript php jquery pdf mpdf


【解决方案1】:

尝试使用您的 php 脚本发送更多标头(并修改您当前的标头):

public function printPdf(){
    ob_clean();
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="kainos.pdf"');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    $html = $this->request->post['pdf'];
    $mpdf = new \Mpdf\Mpdf();
    $mpdf->WriteHTML('<div>Section 1 text</div>');
    return $mpdf->Output();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2020-06-21
    • 2020-07-08
    • 1970-01-01
    • 2021-05-25
    • 2021-08-15
    相关资源
    最近更新 更多