FPDF: Change text color while inside a Cell?

Michael Crothers picture Michael Crothers · Jan 15, 2013 · Viewed 52.8k times · Source

I want it so that the text saying white will use SetTextColor as white, and the orange to use orange.

$pdf->SetTextColor(255,255,255);
$pdf->Cell(50,0,'WHITE ORANGE ORANGE WHITE',0,1,'C');

How do I affect the 'ORANGE' words to use an orange text color?

Answer

Ioulian Alexeev picture Ioulian Alexeev · Jan 16, 2014

I needed that functionality too. This is the function I written to do a simple colored string:

function cellMultiColor($stringParts) {
    $currentPointerPosition = 0;
    foreach ($stringParts as $part) {
        // Set the pointer to the end of the previous string part
        $this->_pdf->SetX($currentPointerPosition);

        // Get the color from the string part
        $this->_pdf->SetTextColor($part['color'][0], $part['color'][1], $part['color'][2]);

        $this->_pdf->Cell($this->_pdf->GetStringWidth($part['text']), 10, $part['text']);

        // Update the pointer to the end of the current string part
        $currentPointerPosition += $this->_pdf->GetStringWidth($part['text']);
    }

and you use it like this:

cellMultiColor([
    [
        'text' => 'Colored string example: ',
        'color' => [0, 0, 0],
    ],
    [
        'text' => 'red',
        'color' => [255, 0, 0],
    ],
    [
        'text' => ', ',
        'color' => [0, 0, 0],
    ],
    [
        'text' => 'blue',
        'color' => [0, 0, 255],
    ],
]);