This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

planetadeleste
planetadeleste

Hello everyone!

Like the subject say, Is there some way to force download a pdf file throw Ajax? In my script, the construction of the PDF file is made after button ajax request, and them I use

return Redirect::to( $store_pdf_file );

But this redirect and open the PDF, I want to download the file.

Thanks

Last updated

rick.harrison [gatenbysanderson]
rick.harrison [gatenbysanderson]

If you've returned no content at this point (or if you redirect to a custom php/cms page instead of redirecting straight to the pdf file), you could provide your own headers (and stream the file) so the browser just downloads it instead of trying to view it?

example code:



$file_name = "path/to/my-document.pdf";

if (file_exists($file_name)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename($file_name)));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file_name));
    ob_clean();
    flush();
    readfile($file_name);
    exit;
}

(as the php is streaming the pdf then obviously you mustn't output any other content on that request otherwise it'll corrupt the download)

Last updated

planetadeleste
planetadeleste

Thanks @rick.harrison [gatenbysanderson]

Maybe the solution is redirect to a "pdf" action, inside the current controller, with your code.

1-3 of 3

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.