One of the nice things about PHP has to be its support for awide variety of different technologies. And one of the most overlookedextensions in PHP 4 is the PDFLib extension, which allows you todynamically construct PDF documents through your PHP scripts. Find outmore, inside.
Lines aren't the only thing you can draw - circles and rectangles also figure prominently on the menu. Take a look at the following example, which demonstrates.
<?php
// create handle for new PDF document
$pdf = pdf_new();
// open a file
pdf_open_file($pdf, "shapes.pdf");
// start a new page (A4)
pdf_begin_page($pdf, 595, 842);
// set a fill colour
pdf_setcolor($pdf, "fill", "rgb", 1, 1, 0);
// set a stroke colour
pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 0);
// draw a rectangle
pdf_rect($pdf, 50, 500, 200, 300);
pdf_fill_stroke($pdf);
// set a fill colour
pdf_setcolor($pdf, "fill", "rgb", 0, 1, 0);
// set a stroke colour
pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 1);
// draw a circle
pdf_circle($pdf, 400, 600, 100);
pdf_fill_stroke($pdf);
// end page
pdf_end_page($pdf);
// close and save file
pdf_close($pdf);
?>
Here's the output:
In this case, the pdf_rect() function has been used to draw a rectangle, given the coordinates of the lower left corner and the height and width. This rectangle has then been filled and outlined in two different colours, via the pdf_fill_stroke() function.
Circles are handled by the pdf_circle()
function, which accepts three arguments: the X and Y coordinates of the circle center, and the length of the circle radius.
pdf_circle($pdf, 400, 600, 100);
This ability to draw
geometric shapes on the fly can come in handy in a number of different situations. Consider the following one, in which a couple of "for" loops have been combined with the pdf_lineto() function to generate a PDF line grid.
<?php
// create handle for new PDF document
$pdf = pdf_new();
// open a file
pdf_open_file($pdf, "grid.pdf");
// start a new page (A4)
pdf_begin_page($pdf, 595, 842);
// set a stroke colour
pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 0);
// draw vertical lines (move along X axis)
for ($x=0; $x<=595; $x+=20)
{
pdf_moveto($pdf, $x, 0);
pdf_lineto($pdf, $x, 842);
pdf_stroke($pdf);
}
// draw horizontal lines (move along Y axis)
for ($y=0; $y<=842; $y+=20)
{
pdf_moveto($pdf, 0, $y);
pdf_lineto($pdf, 595, $y);
pdf_stroke($pdf);
}
// end page
pdf_end_page($pdf);
// close and save file
pdf_close($pdf);
?>