在浏览器中查看 pdf 流
View pdf stream in browser
我有一个 PDF 文件,我想在浏览器选项卡中查看。我知道我可以直接使用 file link 来显示它,但是我想读取一个变量中的文件内容并使用该变量来显示文件。背后的原因是,我想在读入变量后立即删除文件。
PHP:
$fdata = file_get_contents($tmppdf);
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=".$tmppdf);
return $fdata;
Ajax:
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
// window.location.href = "/purchases/print" + '/' + purchase_id;
window.open('/purchases/print' + '/' + purchase_id, '_blank');
});
我在结果中得到二进制内容。有人可以帮忙吗,我的代码有什么问题。
更新:
将我的 ajax 代码更改为以下,现在我得到一个空白的 pdf 页面
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
$.ajax({
type: "GET",
url: "/purchases/print" + '/' + purchase_id,
success: function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
var blobURL = window.URL.createObjectURL(blob);
window.open(blobURL,'_blank');
},
error: function (data) {
alert("Unable to Print !!!");
}
});
Laravel 实际上比 return file responses 具有 built-in 功能。这将自动设置正确的 headers,以便文件显示在浏览器中。
return response()->file($tmppdf);
也许:
return Response::make($fdata, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$tmppdf.'"'
]);
如果你想流式传输文件,你可以使用它来显示文件:
这适用于二进制字符串。
return Response::make($file, 200, [
'Content-Type' => 'application/pdf',
]);
我有一个 PDF 文件,我想在浏览器选项卡中查看。我知道我可以直接使用 file link 来显示它,但是我想读取一个变量中的文件内容并使用该变量来显示文件。背后的原因是,我想在读入变量后立即删除文件。
PHP:
$fdata = file_get_contents($tmppdf);
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=".$tmppdf);
return $fdata;
Ajax:
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
// window.location.href = "/purchases/print" + '/' + purchase_id;
window.open('/purchases/print' + '/' + purchase_id, '_blank');
});
我在结果中得到二进制内容。有人可以帮忙吗,我的代码有什么问题。
更新: 将我的 ajax 代码更改为以下,现在我得到一个空白的 pdf 页面
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
$.ajax({
type: "GET",
url: "/purchases/print" + '/' + purchase_id,
success: function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
var blobURL = window.URL.createObjectURL(blob);
window.open(blobURL,'_blank');
},
error: function (data) {
alert("Unable to Print !!!");
}
});
Laravel 实际上比 return file responses 具有 built-in 功能。这将自动设置正确的 headers,以便文件显示在浏览器中。
return response()->file($tmppdf);
也许:
return Response::make($fdata, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$tmppdf.'"'
]);
如果你想流式传输文件,你可以使用它来显示文件:
这适用于二进制字符串。
return Response::make($file, 200, [
'Content-Type' => 'application/pdf',
]);