I\'m trying to display a PDF(which is created in the server side and pass to the client side as a web stream) through an AJAX call. My code is given below:
j
You can generate a temporary URL to access the PDF file stored on the server, instead of sending it back to the AJAX call. Just pass the generated URL back to the client. Then, when you receive the URL, you could for example do a window.location =
to redirect the browser to the download.
Make sure that the correct headers are set for the generated file (Content-Disposition: attachment
etc.), and all should be fine.
Edit: Although you could probably just use a regular (non-JavaScript) link to generate and download the file. But doing it via AJAX enables you to show some specific animation etc. to the user while the file is being generated.
Here is my way of dealing with this issue. It is based on line 50 of this pdfmake file (https://github.com/bpampuch/pdfmake/blob/master/src/browser-extensions/pdfMake.js).
assuming you have a pdf stream I convert it to base64 and echo it back to my AJAX:
$pdfString = $mpdf->Output('', 'S');
$pdfBase64 = base64_encode($pdfString);
echo 'data:application/pdf;base64,' . $pdfBase64;
Here is my AJAX code. When receiving data it opens a new window and replaces url with base64 endoded data:
var ajaxRequest = $.ajax({
url: "php/generate-pdf/print-control.php",
data: '',
cache: false,
contentType: 'application/json',
processData: false,
type: 'POST'
});
$.when(ajaxRequest).done(function (ajaxValue) {
var win = window.open('', '_blank');
win.location.href = ajaxValue;
});
The downside of this method is that you get a base64 string in the adress bar.
Why do you load it via AJAX? Why don't you load it in an IFRAME that you generate when you need it. The standard browsers plugin will display it then inside that Iframe.
$('#link').click(function(e) {
e.preventDefault(); // if you have a URL in the link
jQuery.ajax({
type: "POST",
processData: false,
url: "aaaa.p?name=pdf",
data: inputxml,
contentType: "application/xml; charset=utf-8",
success: function(data)
{
var iframe = $('<iframe>');
iframe.attr('src','/pdf/yourpdf.pdf?options=first&second=here');
$('#targetDiv').append(iframe);
}
});
});
create an "object url" from the blob that you can load into the iframe
axios({
url: `path/to/pdf`,
method: "GET",
responseType: 'arraybuffer'
}).then((response) => {
let blob = new Blob([response.data], { type: response.headers['content-type'] } );
let url = window.URL.createObjectURL(blob);
$('#frame').attr('src',url);
});