PDFs with PHP part 2 - Circles (Page 5 of 8 )
Drawing a circle is slightly more complex. There is no native PDF syntax to draw a circle. However, luckily, PDF can draw not only straight lines, but also complex cubic Bezier curves. Using a combination of these we can create our own function to draw a circle.
The following is a fairly good general introduction to Bezier curves in PDF, which you can use to create complex patterns or drawings, not only circles.
function circle
($x, $y, $r, $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.
}
$y = $this->_h - $y; // Adjust y value.
$b = $r * 0.552; // Length of the Bezier
// controls.
/* Move from the given origin and set the current point
* to the start of the first Bezier curve. */
$c = sprintf('%.2f %.2f m', $x - $r, $y);
$x = $x - $r;
/* First circle quarter. */
$c .= sprintf(' %.2f %.2f %.2f %.2f %.2f %.2f c',
$x, $y + $b, // First control point.
$x + $r - $b, $y + $r, // Second control point.
$x + $r, $y + $r); // Final point.
/* Set x/y to the final point. */
$x = $x + $r;
$y = $y + $r;
/* Second circle quarter. */
$c .= sprintf(' %.2f %.2f %.2f %.2f %.2f %.2f c',
$x + $b, $y,
$x + $r, $y - $r + $b,
$x + $r, $y - $r);
/* Set x/y to the final point. */
$x = $x + $r;
$y = $y - $r;
/* Third circle quarter. */
$c .= sprintf(' %.2f %.2f %.2f %.2f %.2f %.2f c',
$x, $y - $b,
$x - $r + $b, $y - $r,
$x - $r, $y - $r);
/* Set x/y to the final point. */
$x = $x - $r;
$y = $y - $r;
/* Fourth circle quarter. */
$c .= sprintf(' %.2f %.2f %.2f %.2f %.2f %.2f c %s',
$x - $b, $y,
$x - $r, $y + $r - $b,
$x - $r, $y + $r,
$op);
/* Output the whole string. */
$this->_out($c);
}
Note that the process is essentially one of creating four joined arcs, each one starting from where the previous one finished.
PDF is “aware” of the current x/y position after having drawn an object. This means that you can concatenate several draw objects, following each new object on from where the last one left over, without having to explicitly move to the new x/y start position.
Line Width
Since we have introduced lines and drawings, it will be good to have a function to control the line width of our drawings. This function sets our class variable $this->_line_width and outputs it to the buffer, if there is an open document.
function setLineWidth
($width)
{
$this->_line_width = $width;
if ($this->_page > 0) {
$this->_out(sprintf('%.2f w', $width));
}
}
Next: Page Add Modifications >>
More Zend Articles
More By Zend