I'm working with Laravel 9 and Dompdf to generate some pdf files from the information provided on the form, so I tried this:
composer require barryvdh/laravel-dompdf
And then register it at config.php
:
'aliases' => Facade::defaultAliases()->merge([
'PDF' => Barryvdh\DomPDF\PDF::class,
])->toArray(),
'providers' => [
Barryvdh\DomPDF\ServiceProvider::class,
],
Then in the Controller:
use Barryvdh\DomPDF\PDF;
use Dompdf\Dompdf;
class ResumeController extends Controller
{
public function generate(Request $request)
{
// Generate HTML for the resume using the form data
$html = '<h1>' . $request->input('name') . '</h1>';
$html .= '<p>Email: ' . $request->input('email') . '</p>';
$html .= '<p>Phone: ' . $request->input('phone') . '</p>';
$html .= '<p>Address: ' . $request->input('address') . '</p>';
// Create a new PDF instance
$pdf = new PDF();
// Generate the PDF from the HTML
$pdf->loadHTML($html);
// Return the PDF as a download
return $pdf->download('resume.pdf');
}
}
But now I get this error:
Too few arguments to function Barryvdh\DomPDF\PDF::__construct(), 0 passed in C:\xampp\htdocs\resume-maker\app\Http\Controllers\ResumeController.php on line 21 and exactly 4 expected
I asked ChatGPT this error and it says change the code to this:
public function generate(Request $request)
{
// Generate HTML for the resume using the form data
$html = '<h1>' . $request->input('name') . '</h1>';
$html .= '<p>Email: ' . $request->input('email') . '</p>';
$html .= '<p>Phone: ' . $request->input('phone') . '</p>';
$html .= '<p>Address: ' . $request->input('address') . '</p>';
// Create a new PDF instance with the required arguments
$pdf = new PDF([
'font_path' => base_path('resources/fonts/'),
'font_family' => 'Roboto',
'margin_top' => 0,
'margin_left' => 0,
'margin_right' => 0,
'margin_bottom' => 0,
'default_font_size' => 12,
'default_font' => 'Roboto'
], 'A4', 'portrait', true);
// Generate the PDF from the HTML
$pdf->loadHTML($html);
// Return the PDF as a download
return $pdf->download('resume.pdf');
}
But now I get this error:
Barryvdh\DomPDF\PDF::__construct(): Argument #1 ($dompdf) must be of type Dompdf\Dompdf, array given, called in C:\xampp\htdocs\resume-maker\app\Http\Controllers\ResumeController.php on line 30
So what's going wrong here? How can I fix this issue and produce pdf file properly?
Note that my dompdf version is "barryvdh/laravel-dompdf": "^2.0",
use Facade instead of instantiating class.
import
use Barryvdh\DomPDF\Facade\Pdf as PDF;
then in code
// Generate the PDF from the HTML
$pdf=PDF::loadHTML($html);
// Return the PDF as a download
return $pdf->download('resume.pdf');