Is there a way to use the transactions in TCPDF when extending it with FPDI?
Question
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".
OTHER TIPS
in your first example you should use $pdf = $pdf->rollbackTransaction
or $pdf->rollbackTransaction(true)
instead of just $pdf->rollabackTransaction()
this is because rollbackTransaction takes a boolean parameter (default is false), to know if it have to return the rollbackvalue (false) or set the object to the rollback state (true).
$pdf = new FPDI();
$pdf->AddPage();
$pdf->startTransaction(true);
$pdf->Cell(0, 0, 'blah blah blah');
$pdf->rollbackTransaction(true);
$pdf->Output( . time() . '.pdf', 'D');
Adding true as parameter in the Transaction Method Calls solved the Problem for me.