0

TCPDF allows to set the text color by SetTextColor method but I wasn't able to find any method to get the current text color. Is this simply not supported or did I missed something?

Use case: I'm writing a reusable helper for TCPDF which needs to modify text color but should reset it after it's done.

Disclaimer: I know that current version of TCPDF is deprecreated but the new version is not ready yet. I know that there are other options to render PDFs (e.g. chrome headless), which are easier to use and more stable for many use cases, but I can't use them cause my use cases require functionality not possible with HTML / CSS.

jelhan
  • 6,149
  • 1
  • 19
  • 35

2 Answers2

2

I needed this functionality for a reusable helper class as written in my question. Since this helper class should work with all TCPDF instances extending TCPDF to add an additional public method as suggested in EPB's answer was not an option. I decided to use a ReflectionProperty:

$r = new \ReflectionObject($pdf);
$p = $r->getProperty('fgcolor');
$p->setAccessible(true);
$textColor = $p->getValue($pdf);
jelhan
  • 6,149
  • 1
  • 19
  • 35
1

There isn't one. At least, not as a public function.

However, the protected property $fgcolor is an array that can be handed right back to setTextColorArray. Knowing this - it's pretty easy to extend the class to provide a getter for the current text color.

<?php
class MYTCPDF_HELPER extends TCPDF {
    public function getTextColor() {
        return $this->fgcolor;
    }
}

$pdf = new MYTCPDF_HELPER();

/*...*/

$prevcolor = $pdf->getTextColor();
$pdf->setTextColorArray(array(100, 0, 0, 0), false);
$pdf->WriteHTML('<p>Test Text</p>');
$pdf->WriteHTML('<p>More Text</p>');
$pdf->setTextColorArray($prevcolor);
$pdf->WriteHTML('<p>Final Line</p>');
// "Final Line" is written in whatever color was set when we called getTextColor.

I got the idea from looking at how TCPDF itself handled reverting the text color in the parser for writeHTML.

(Note: For other color arrays: draw color is stored in $stokecolor and fill color is in $bgcolor.)

EPB
  • 3,939
  • 1
  • 24
  • 26