How to redirect after downloading pdf using fpdf

2.4k Views Asked by At

Is there any approach to redirect to certain route/ refresh current page after download the pdf? I've tried to return an URL but it just goes to the url without generating the file. If I use the code below, it will generate the file and display a blank page. I am using laravel and fpdf here.

Route:

Route::post('alumni/labels','AlumniController@labels')->name('alumni/labels');

Controller:

public function labels(){
            $alumni = Alumni::whereIn('id', Session::get('alumniId'))->get();
            $pdf = new PDF_Label('TJ103');
            $pdf->AddPage();
            foreach ($alumni as $alumnus) {
                $text = sprintf("%s %s\n%s\n%s %s", $alumnus->firstName, $alumnus->lastName, $alumnus->address, $alumnus['hp1'], $alumnus['phone']);
                $pdf->Add_Label($text);
            }
            return $pdf->Output('d');
 }

View:

<form method="post" action="labels">
                    {!! csrf_field() !!}
                    <button class="btn btn-primary" id="btn-submit">Generate Label</button>
                    </form>
2

There are 2 best solutions below

0
On

This is not proper way but if you can open pdf in new page

var pdfPage = window.open('printMyPdf.php');
$(pdfPage).bind('beforeunload',function(){ 
     location.reload(); // redirect to your custom page
});
0
On

you can redirect your page using the switch php statement. For details see: switch php statement. Here is an example:

$location = "/opt/lampp/htdocs/registration/register/2019/".$filename.".pdf";
// output
switch ($pdf->Output("F", $location)) {
    default:
        header("location: reg.php?");
} 

you'll notice that the 'case ... break' parte of the statement is removed and left with the 'default' parte of the statement, it is forced to run only the default. I hope this helps you. I came up with this solution after two days of searching the web and not finding any solution. Now it works perfectly.