应jQuery请求将pdf从后端传输到前端



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

示例php代码。

public function printPdf(){
header('Content-Disposition: attachment; filename="kainos.pdf"');
$html = $this->request->post['pdf'];
$mpdf = new MpdfMpdf();
$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中,它处理blobs wierd,所以我正在重写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();
}
});

尝试用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 MpdfMpdf();
$mpdf->WriteHTML('<div>Section 1 text</div>');
return $mpdf->Output();
}

最新更新