Skip to content

Draw Polygon Graphics Shape in PDF Document Using PHP FPDF Library.

This script allows to draw polygons.

Polygon(array points [, string style])

points: array of points (x1, y1, x2, y2, …, xn, yn) where (x1, y1) is the starting point and (xn, yn) is the last one.
style: rendering style, the same as for Rect() function: D, F or FD.

polygon.php

<?php
require('fpdf.php');

class PDF_Polygon extends FPDF
{

function Polygon($points, $style='D')
{
    //Draw a polygon
    if($style=='F')
        $op = 'f';
    elseif($style=='FD' || $style=='DF')
        $op = 'b';
    else
        $op = 's';

    $h = $this->h;
    $k = $this->k;

    $points_string = '';
    for($i=0; $i<count($points); $i+=2){
        $points_string .= sprintf('%.2F %.2F', $points[$i]*$k, ($h-$points[$i+1])*$k);
        if($i==0)
            $points_string .= ' m ';
        else
            $points_string .= ' l ';
    }
    $this->_out($points_string . $op);
}

}
?>

index.php

<?php
require('polygon.php');

$pdf=new PDF_Polygon();
$pdf->AddPage();
$pdf->SetDrawColor(255,0,0);
$pdf->SetFillColor(0,0,255);
$pdf->SetLineWidth(4);
$pdf->Polygon(array(50,115,150,115,100,20),'FD');
$pdf->Output();
?>