Search code examples
fpdftcpdffpdi

Is there a way to use the transactions in TCPDF when extending it with FPDI?


I am using TCPDF with FPDI's bridge. The issue I'm having is that as soon as I use the startTransaction() I get the following error:

TCPDF ERROR: Cannot access protected property FPDI:$numpages / Undefined property: FPDI::$numpages

and the script ends (because of the die in the TCPDF::Error() method).

Here is the code I'm using:

$pdf = new FPDI();

// add a page
$pdf->AddPage();

$pdf->startTransaction();
$pdf->Cell(0, 0, 'blah blah blah');
$pdf->rollbackTransaction();

$pdf->Output( . time() . '.pdf', 'D');

If I change it to:

$pdf = new FPDI();

// add a page
$pdf->AddPage();

$pdf->Cell(0, 0, 'blah blah blah');

$pdf->Output( . time() . '.pdf', 'D');

it works fine.

Is there anyway to make them work together and use TCPDF's transactions?


Solution

  • The solution I found was to to use PHP's object cloning which allows me to do transactions and roll them back whenever I want. Here's an example:

    $pdf = new FPDI();
    
    // add a page
    $pdf->AddPage();
    
    $pdf->Cell(0, 0, 'blah blah blah');
    
    $_pdf = clone $pdf;
    
    // do stuff that you may want to revert
    $pdf->Cell(0, 0, 'PDFs suck!');
    
    // revert the PDF
    $pdf = $_pdf;
    
    $pdf->Output( . time() . '.pdf', 'D');
    

    The PDF will only contain "blah blah blah".