Hello,
I try to stream or download a PDF from a plugin controller with responseType blob. I use the Barryvdh\DomPDF\Facade\Pdf
.
Here’s part of my controller code in my onDownloadPdf
method:
$pdfMarkup = $this->makePdfPartial('$/acme/application/controllers/applications/_pdf-generation-partial.htm', $this->vars);
$pdf = Pdf::setPaper('A4', 'landscape')->setOption(['dpi' => 150, 'defaultFont' => 'sans-serif'])->setProtocol('https://')->loadHTML($pdfMarkup);
return $pdf->download('file-name.pdf');
Here I try to get the PDF blob with JS, after I tried to set responseType blob in ajaxSetup
:
$(document).on('ajaxSetup', function(event, context) {
context.options.responseType = 'blob';
context.options.timeout = 30000;
});
Inside a jQuery ready and a click event I try to get a blob, but receive a string:
$.request('onDownloadPdf', { data: { id: modelId },
complete: function(response) {
if (response.status === 200 && response.responseText) {
// `response.responseText` comes as string, not as blob
const pdfUrl = window.URL.createObjectURL(new Blob([response.responseText], { type: 'application/pdf' }));
const link = document.createElement('a');
link.href = pdfUrl;
link.setAttribute('download', 'bewerbung-erfassung_' + (new Date()).toISOString().split('T')[0] + '.pdf');
document.body.appendChild(link);
link.click(); // an empty PDF is opened
link.remove();
}
},
error: function(error) {
$.oc.flashMsg({
'text': 'Error message...',
'class': 'error',
'interval': 3,
});
},
});
});
Does someone know how to do this right?