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.
All that is required for drawing a line in PDF is a starting point and an end point. The below function takes an x1/y1 start, and an x2/y2 end point.
The actual PDF syntax to achieve this is: • 'x1 y1 m' - move the current x/y position to x1/y1; • 'x2 y2 l' - continue in a straight line to x2/y2; • 'S' - set a “stroke” on the resulting path. As in Part 1, we compensate for PDF's inverted y scale by subtracting the user supplied $y value from the $this->_h value for page height, to obtain the vertical distance from the bottom of the page.
Rectangles A rectangle function requires a starting x/y point, a width, and a height. A fifth parameter defines the rectangle style, which can be 'f' for filled, 'd' for drawn, or 'fd' (or 'df', the order doesn’t matter) for both filled and drawn.
Similar to the line drawing function, the PDF output for the rectangle involves creating a rectangular path and applying a path-painting operator to it: • 'x y w h re' - the rectangular path; • 'f', 'S' or 'B' - the path-painting operators.
function rect
($x, $y, $width, $height, $style = '') { $style = strtolower($style); if ($style == 'f') { $op = 'f'; // Style is fill only. } elseif ($style == 'fd' || $style == 'df') { $op = 'B'; // Style is fill and stroke. } else { $op = 'S'; // Style is stroke only. } $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s', $x, $this->_h - $y, $width, -$height, $op)); }
Note that the end result of calling a drawn and filled rectangle ('fd') is exactly the same as first creating a filled rectangle ('f') and then creating a drawn one ('d').