I am using DynamicPDF and I am opening my file in new tab to generate my file which is working absolutely fine. Here is what I have sone so far (in one of my plugin's update.htm
file).
<a href="<?= url('/'); ?>/regency-brochure" class="btn btn-primary" target="_blank">Preview Brochure</a>
Now I am trying to somehow do the same by opening/downloading the same file via AJAX response. Hence I have put below code inside my update.htm
file.
<button
type="submit"
data-request="onPreview"
data-load-indicator="Loading Preview"
class="btn btn-primary">Preview Brochure Ajax
</button>
And Inside my controller I have done this.
public function onPreview()
{
return PDF::loadTemplate('renatio::invoice')->download('download.pdf');
}
Now as soon as I click on it, my browser getting hanged, but I am able to see some random binary long string in my response.
I have checked and read library's documentation and they are giving a tip saying...
Tip: Download PDF via Ajax response
OctoberCMS ajax framework cannot handle this type of response.
Recommended approach is to save PDF file locally and return redirect to PDF file.
And I tried to open / download by using return
but its not working.
Can someone guide me how can I solve this ? How can I make my PDF file open / download using AJAX here ?
Eventually, I have implemented above feature.
Here is what I have done.
update.htm
<button type="submit" data-request="onPreviewDownload" data-load-indicator="Generating Brochure..."
data-request-success="formSuccess( context, data, textStatus, jqXHR)" class="btn btn-primary">Preview Brochure
</button>
<script>
function formSuccess( context, data, textStatus, jqXHR){
window.open(data.result, '_blank');
}
</script>
ControllerFile.php
public function onPreviewDownload()
{
$templateCode = 'renatio::invoice'; // unique code of the template
$storagePath = storage_path('app/uploads/');
$pdf_file_name = 'regency-brochure-test.pdf' ;
$pdf_file_name_directory = $storagePath . $pdf_file_name;
PDF::loadTemplate($templateCode)->setPaper('a4', 'landscape')->save($pdf_file_name_directory);
return $baseUrl = url(Config::get('cms.storage.uploads.path')) . '/' . $pdf_file_name;
}
As you can see in update.htm file, I have used data-request="onPreviewDownload"
, data-load-indicator="Generating Brochure..."
and data-request-success="formSuccess( context, data, textStatus, jqXHR)"
.
Then onPreviewDownload
method in my ControllerFile
, I have used save
method instead of download
method, PDF::loadTemplate($templateCode)->setPaper('a4', 'landscape')->save($pdf_file_name_directory);
mentioned in Documentation of DynamicPDF through which, I am saving the file in particular location and once I am able to save the file.
Then I am opening from my formSuccess
method in update.htm file using window.open(data.result, '_blank');
.
Hope this helps.