Laravel显示“ FPDF错误:尚未添加页面”

问题描述

我正在为laravel项目使用fpdf库。我为页眉和页脚函数创建一个类。然后在我的pdf控制器上调用thess函数。我遇到此错误“ FPDF错误:还没有添加页面”,我也不知道此错误来自何处。您可以教我如何解决错误/错误。预先感谢。

我的控制器中的代码

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Codedge\Fpdf\Fpdf\Fpdf;
use App\Personnel;
use App\Classes\PDFClass;

class PFTReportController extends Controller
{
    public function postPFTReport(Request $request)
    {
        $pdf = new FPDF();
        $pdf->AddPage('P','A4');
    $pdf->Ln(4);
    $pdf->SetFont('Arial','',12);

    // Call the header for this report
    $pdfClass = new PDFClass();
    $header = $pdfClass->Header();

    $pdf->Cell(0,4,'Sample Report',1,'C');
    $pdf->Ln(2);
        
        $pdf->Output();
        exit;
    }
}

课程代码

namespace App\Classes;

use Codedge\Fpdf\Fpdf\Fpdf;

class PDFClass extends Fpdf
{
    protected $B = 0;
    protected $I = 0;
    protected $U = 0;
    protected $HREF = '';

    // Page header
    function Header()
    {
        $this->SetFont('Arial',11);
        $this->Cell(0,2,'Line 1','C');
        $this->Cell(0,8,'Line 2','C');
        $this->SetFont('Arial','B',12);
        $this->Cell(0,'Line 3','Line 4','Line 5','C');
        $this->Ln(8);
    }
}

解决方法

您创建2个类实例。第一个是FPDF,您可以在其中添加页面:

$pdf = new FPDF();
$pdf->AddPage('P','A4');
$pdf->Ln(4);
$pdf->SetFont('Arial','',12);

...然后创建一个新的方法,只需手动调用Header()方法:

$pdfClass = new PDFClass();
$header = $pdfClass->Header();

这没有意义,并且此时会引发错误,因为您在Header()中调用了多个方法,这些方法应该将内容输出到页面,但是您之前没有添加。

您应该只使用PDFClass,也不要手动调用Header()方法,因为它是called internally automatically

public function postPFTReport(Request $request)
{
    $pdf = new PDFClass();
    $pdf->AddPage('P','A4'); // NOW THE HEADER() METHOD IS INVOKED AUTOMATICALLY IN THIS CALL
    $pdf->Ln(4);
    $pdf->SetFont('Arial',12);

    $pdf->Cell(0,4,'Sample Report',1,'C');
    $pdf->Ln(2);
    
    $pdf->Output();
    exit;
}