Skip to content
Advertisement

Trigger PDF Download PHP – Laravel 7

I have a simple report page, and I am using Laravel 7 to build it.

enter image description here

I want to trigger auto-download a PDF with that view.

What would be the most lightweights I should look into? I did a quick Google, and I saw so many options.

I decided to try this and did all the steps, below is my final code

Final Codes

Note this line : $pdf = PDF::loadView('layouts.be.baby.report', get_defined_vars());

JavaScript

It is working, when I visit the route :

Route::get(‘/baby/{id}/report/download’,’BabyController@downloadReportPDF’);

But the styles seems very messed up.

  • Images are missing, and so on.

enter image description here

How do I improve on that ?


Updated

I’ve updated my images links to remote url now… they loaded now.

enter image description here

Somehow styles still messed up.

I even tried inline style for my padding, and still rendering wrong… 🙁

report.blade.php

JavaScript

Advertisement

Answer

If you want use trigger print you can do it by using window.print, it’s will show print dialog that contain print as pdf. example code

JavaScript

For print another page you can use iframe. you can hide it using CSS too. example:

JavaScript

I tried print page contain chartjs and works 100%, you can test it out

If you want to trigger download as PDF, you should use package. JS solution is jsPDF and PHP/laravel solution is laravel-dompdf . Both packages will not print exactly as browser render especially if you are using CSS3 or Image source from local. You need to custom the CSS and asset that compatible for both packages.

If you are using laravel dompdf you need to change below code:

JavaScript

to

JavaScript

you can using asset() but you need activate remote asset in laravel dompdf too.

You can check DomPDF CSS Compatibility here.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement