Laravel 9 & Dompdf: 参数太少,无法运行 Barryvdh\DomPDF\PDF::__construct(), 0 通过



我正在使用Laravel 9和Dompdf从表单上提供的信息生成一些pdf文件,所以我尝试了这个:

composer require barryvdh/laravel-dompdf

然后注册到config.php:

'aliases' => Facade::defaultAliases()->merge([
'PDF' => BarryvdhDomPDFPDF::class,
])->toArray(),
'providers' => [
BarryvdhDomPDFServiceProvider::class,
],

然后在控制器中:

use BarryvdhDomPDFPDF;
use DompdfDompdf;
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');
}
}

但是现在我得到这个错误:

参数太少,无法发挥作用BarryvdhDomPDFPDF::__construct(), 0在C:xampphtdocsresume-makerappHttpControllersResumeController.php第21行中传递,正好4

我问ChatGPT这个错误,它说把代码改成这样:

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');
}

但是现在我得到这个错误:

BarryvdhDomPDFPDF::__construct():参数#1 ($ DomPDF)必须是类型为DomPDF DomPDF,数组给定,在C:xampphtdocsresume-makerappHttpControllersResumeController.php中调用,第30行

那么这里出了什么问题?如何解决此问题并正确生成pdf文件?

注意我的dompdf版本是"barryvdh/laravel-dompdf": "^2.0",

使用Facade代替实例化class。

进口
use BarryvdhDomPDFFacadePdf 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');

裁判:https://github.com/barryvdh/laravel-dompdf

相关内容

  • 没有找到相关文章

最新更新