在浏览器中显示ajax响应的pdf


Display pdf in browser for ajax response

我想在浏览器中显示pdf ajax响应。问题是我不能直接打开url,因为pdf是动态创建的,我该如何显示它。

$.ajax({
                    url: url,
                    type: "POST",
                    data: JSON.stringify(data),
                    processData: false,
                    contentType: "application/json; charset=UTF-8",
                    complete: function (response) {
                        console.log(response);
                        window.open("pdf.php","_blank");
                    }
                });

PDF响应为

%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode /Length 1265>>

PHP代码

 header('Cache-Control: public');
 header('Content-type: application/pdf');
 header('Content-Disposition: attachment; filename="new.pdf"');  
 header('Content-Length: ' . strlen($data));
 echo $data;

任何帮助都将不胜感激。

将其放入您的pdf.php 中

header("Content-type: application/pdf");

我遇到了这个问题,我会给你解决方案。。。我希望它能解决你的问题。

当您呼叫您的服务时,您应该要求dataType: 'binary'响应。然后,使用saveAs(FileSaver.js)触发下载。

但是,$.ajax不允许您开箱即用地下载二进制内容,它会尝试从UTF-8解码您的二进制文件并将其损坏。要么使用jQuery插件来解决这个问题jQuery.binarytransport.js

示例:

$.ajax({
    type: "POST",
    url: $("form#data").attr("action"),
    data: formData,
    dataType: 'binary',     //--> using jquery.binarytransport.js
    success: function (response) {
        // Default response type is blob
        saveAs(response, "test.pdf"); //--> using FileSaver.js
    }
});

好看!:)