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.
Why stop there? PHP's PDF extension comes with a whole bag of functions designed to let you draw lines, circles and other shapes in your PDF document. Consider the following example, which demonstrates the process of drawing a line.
<?php
// create handle for new PDF document
$pdf = pdf_new();
// open a file
pdf_open_file($pdf, "letterhead.pdf");
// start a new page (A4)
pdf_begin_page($pdf, 595, 842);
// get and use a font object
$arial = pdf_findfont($pdf, "Arial", "host", 1); pdf_setfont($pdf,$arial, 12);
// set a colour for the line
pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 0);
// place a logo in the top left corner
$image = pdf_open_image_file($pdf, "jpeg", "logo.jpg");
pdf_place_image($pdf, $image, 50, 785, 0.5);
// draw a line under the logo
pdf_moveto($pdf, 20, 780);
pdf_lineto($pdf, 575, 780);
pdf_stroke($pdf);
// draw another line near the bottom of the page
pdf_moveto($pdf, 20,50);
pdf_lineto($pdf, 575, 50); pdf_stroke($pdf);
// and write some text under it
pdf_show_xy($pdf, "Confidential and proprietary", 200, 35);
// end page
pdf_end_page($pdf);
// close and save file
pdf_close($pdf);
?>
Here's what you should see in the PDF
document
In this case, the process of drawing a line involves creative use of the pdf_moveto(), pdf_lineto() and pdf_stroke() functions.
In the example above, I'd like to draw a line from the position (20,780) to the new position (575, 780). In order to do this, I first need to place the cursor at the starting point (20,780), via a call to pdf_moveto().
pdf_moveto($pdf, 20, 780);
Next, I need to set the end
point of the line, via pdf_lineto():
pdf_lineto($pdf, 575, 780);
Finally, the line is actually
rendered using pdf_stroke().
pdf_stroke($pdf);
The stroke colour is set via a call to
pdf_setcolor(), which accepts a number of parameters: the PDF document handle, whether the colour being set is for "stroke", "fill" or "both", the colour scheme to use (RGB or CMYK), and a list of colour values appropriate to the selected colour scheme.
pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 0);
It's
important to note that the list of colour values provided to pdf_setcolor() must be specified in terms of percentage intensity - that is, the intensity of that colour, expressed as a percentage of the maximum intensity possible. So, if I wanted to set red (RGB: 255,0,0) as the stroke colour, my call to pdf_setcolor() would look like this,
pdf_setcolor($pdf, "stroke", "rgb", 1, 0, 0);
while a
fill colour of yellow (RGB: 255,255,0) would be