I have a PHP file where I create a PDF. I call to this PHP using AJAX and give some visual feedback (I show and then hide a spinner), because I will create a 500-pages-PDF and this process is a little bit slow.
To create the PDF I use PDFMerger (because I need to merge a few PDFs). And to call this PHP I have a button which has a JavaScript function associated.
The question is, How I can download the file using AJAX. Because if I don't use AJAX and I use the PHP, the file will be downloaded but if I use AJAX instead PHP I will have all the 'PDF-data' on success ( ...06 P endstreamendobj965 0 obj<</Filter /FlateDecode /Type /XObject/Subtype /Form/FormType 1/BBox [0.00 0.00 595.28 841.89]/Resources <</ProcSet [/PDF /Text /ImageB /ImageC /ImageI ]/Font <</F1 960 0 R/F2 961 0 R>>/XObject <<>>/Properties...
).
My question is not exactly like how to download a file by AJAX. I'm trying to find out how to combine PDFMerger and AJAX to get the PDF.
JavaScript
showSpinner();
$.ajax({
url: 'downloadPDF.php',
success: function (data) {
//And now I want to download the PDF
},
complete: function () {
hideSpinner();
}
});
PHP ( downloadPDF.php
)
$pdf = new PDFMerger();
foreach ($arrayPDFs as $url) {
$pdf->addPDF($url, 'all');
}
$pdf->merge('download');
Well if you use ajax you obviously get the PDF contents as data.
If you want the user to click a link and get a PDF as result, you do not need ajax. The user clicks the link in his browser and the browser will download the PDF file - no additional tab etc. required.
If you are not able to provide this link for whatever reason you could take the PDF contents from JavaScript by passing the raw data to a JavaScript PDF library (eg jsPDF).
To tell the browser to display a file as PDF through PHP direct download use the headers like described in this question: Show a PDF files in users browser via PHP/Perl
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.