Home » Php » Failed to load PDF using Response Class

Failed to load PDF using Response Class

Posted by: admin October 26, 2017 Leave a comment

Questions:

I am using Laravel 5.2, with Dompdf “barryvdh/laravel-dompdf”: “^0.7.0”.
At first step, I am creating a PDF file with HTML input and saving it in storage path, which works fine. Later I have a link which helps rendering this saved PDF file in browser using Response class.
The code snippet for that is shown below-

$filename = 'file.pdf';
$path = storage_path($filename);
return \Response::make(file_get_contents($path), 200, [
      'Content-Type' => 'application/pdf',
      'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);

This works fine on my local machine, but throws error on pre-production and production server with alert message “Failed to load PDF”.

Please need your help in understanding what’s going wrong. Or else, is there any workaround I can do to load PDF file in browser?

Your help is much appreciated.

Answers:

using response classes in laravel

return response()->download($pathToFile);

OR

return response()->file($pathToFile);

using dompdf method chaining

return PDF::loadFile(public_path().'/myfile.html')->save('/path-to/my_stored_file.pdf')->stream('download.pdf');

EDIT
From dompdf source the stream method requires only a filepath

public function stream($filename = 'document.pdf' ){
        $output = $this->output();
        return new Response($output, 200, array(
            'Content-Type' => 'application/pdf',
            'Content-Disposition' =>  'inline; filename="'.$filename.'"',
        ));
    }

so you can try dompdfobj->stream($filepath);

OR

i found it online

 $headers = [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; ' . $fileName,
        ];

        return Response::make(File::get($filePath . $fileName), 200, $headers);

Leave a Reply

Your email address will not be published. Required fields are marked *