This tutorial is intended for the PHP programmer who needs to incorporate PDF generation in a script without using external libraries such as PDFlib (often unavailable due to licensing restrictions or lack of funds). This tutorial is the second of two parts, and builds on what was covered in the first part. Therefore, if you have not yet gone through Part 1, you are advised to do so (or at least read through it), before going through this tutorial (Part 2). Apart from what was dealt with in Part 1, no knowledge of PDF file structure is required to understand this tutorial, as all references are explained.
We have two different color settings to consider. The $_fill_color variable refers to the “non-stroke” color which is applied to fills and text. The $_draw_color variable is the “stroke” color applied to lines.
The following function will set the fill color:
function setFillColor
($cs = 'rgb', $c1, $c2 = 0, $c3 = 0, $c4 = 0) { $cs = strtolower($cs); if ($cs = 'rgb') { /* Using a three component RGB color. */ $this->_fill_color = sprintf('%.3f %.3f %.3f rg', $c1, $c2, $c3);
} elseif ($cs = 'cmyk') { /* Using a four component CMYK color. */ $this->_fill_color = sprintf('%.3f %.3f %.3f %.3f k', $c1, $c2, $c3, $c4); } else { /* Grayscale one component color. */ $this->_fill_color = sprintf('%.3f g', $c1); } /* If document started output to buffer. */ if ($this->_page > 0) { $this->_out($this->_fill_color); } }
Notice that we need to pass varying number of color components depending on the colorspace selected: one for grayscale, or several for full color.
Grayscale colors are represented by a single 3 decimal place number followed by the letter 'g'. 0 is black, 1 is white, with a whole lot of shades of gray in between.