How to use FPDF force download in custom plugin to force pdf download?
-
Hello,
I’m currently building a custom plugin that retrieves some data from the database include the file name of an existing pdf. Afterwards, I use FPDF and FPDI to make a few alterations to the existing pdf (like stamping it with some user data). Then, I would like the user to be able to download the new pdf with the alterations. However, the problem is that when the download button is clicked (it’s a submit button with some hidden fields and it uses $_POST so technically it’s a form submission because I need it to do somethings shortly before the download begins), the download does not start but I get this error on the page:
FPDF error: Some data has already been output, can’t send PDF file (output started at /home/www/mysite.com/wp-includes/admin-bar.php:844)
I tried putting this is a function that I use in an action but it didn’t work.
function dl_force() { $pdf->Output(WP_PLUGIN_DIR . "/my-plugin-folder/tempcontent/modify/modified_pdf.pdf", "D"); } add_action('init', 'dl_force');
I also tried this:
function dl_force() { $pdf->Output(WP_PLUGIN_DIR . "/my-plugin-folder/tempcontent/modify/modified_pdf.pdf", "D"); } add_action('admin_init', 'dl_force');
And this:
function dl_force() { $pdf->Output(WP_PLUGIN_DIR . "/my-plugin-folder/tempcontent/modify/modified_pdf.pdf", "D"); } add_action('wp_head', 'dl_force');
And this:
function dl_force() { $pdf->Output(WP_PLUGIN_DIR . "/my-plugin-folder/tempcontent/modify/modified_pdf.pdf", "D"); } add_action('template_redirect', 'dl_force');
but none of them worked. So instead I tried to send the new pdf to the modify folder and use headers to force the download but that didn’t work either. I tried transferring the pdf code to another page so that I can remove any kind of space but that didn’t work either. So I decided to make a download.php page where I put some headers and use javascript to redirect to it as soon as the download ( / submit) button is clicked but it doesn’t redirect. It just loads the same page but this time without an error. However, when I access the download.php page directly, the download starts.
Here is the content of the download.php:
<?php header('Content-Type: application/pdf'); header('Content-disposition: attachment;filename=wp-content/plugins/my-plugin-folder/tempcontent/modify/modified_pdf.pdf'); readfile('wp-content/plugins/my-plugin-folder/tempcontent/modify/modified_pdf.pdf'); ?>
So my question is, how can I force the pdf to download? Is there anything that I can use to trigger the headers to start the force download before the admin-bar.php or any other thing on the page? Or is there any another way I can force the download?
I know it’s a long read so thanks for reading and I’ll appreciate any help!
By the way, I’ve also tried header(‘Location: https://…..’); but that didn’t work either. ??
- The topic ‘How to use FPDF force download in custom plugin to force pdf download?’ is closed to new replies.