Zaheer Ahmed
Zaheer Ahmed

Reputation: 61

View pdf stream in browser

I have a PDF file that I want to view in browser tab. I know that I can use file link directly to display it, but I want to read contents of file in a variable and use the variable to display file. Reason behind is, I want to delete the file immediately after reading in variable.

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

I am getting binary contents in result. Can someone help, what is wrong with my code.

enter image description here

UPDATE : Changed my ajax code to below and now I am getting a blank pdf page

$('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 !!!");
        }
});

Upvotes: 0

Views: 2735

Answers (3)

Jesper54
Jesper54

Reputation: 31

If you want to stream the file you can use this to display the file:

This worked with a binary string.

return Response::make($file, 200, [
    'Content-Type' => 'application/pdf',
]);

Upvotes: 0

James
James

Reputation: 1123

Perhaps:

return Response::make($fdata, 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'inline; filename="'.$tmppdf.'"'
]);

Upvotes: 1

Jerodev
Jerodev

Reputation: 33186

Laravel actually has built-in functionality to return file responses. This will automatically set the correct headers so the file gets displayed in the browser.

return response()->file($tmppdf);

Upvotes: 1

Related Questions