Thursday, 19 September 2019

Drawing Dash Lines in PDF by Using the FPDF library

PHP  FPDF 

FPDF is a free pure PHP library for generating PDF file format. It provides flexible functions to access PDF content stream operators for manipulating file content directly.

The PDF file format uses various operators to describe graphic and text objects. Details of the operator definitions can be referred to the PDF Reference. The following dash pattern format is used to set the dash: Dash_array Dash_phase d, where Dash_array is an array that specifies the lengths of dashes and gaps, the Dash_phase specifies the distance into the dash pattern at which to start the dash and the d is the setdash operator. For example, the pattern format [3] 0 d defines the dash pattern as 3 units of dash and 3 units of gap, the pattern format [2 1] 0 d defines the dash pattern as 2 units of dash and 1 unit of gap and the pattern format [] 0 d defines a solid line with no dash.

To draw the dash line, we need create a new class that extends the class FPDF in a new PHP file called mydrawing.php.

require('fpdf.php');

class MyDrawing extends FPDF
{
    function SetDash($pattern = null, $black = null, $white = null) 
    {
        // k is the scale factor (number of points in user unit)
        $s = sprintf($pattern, $black*$this->k, $white*$this->k);
        $this->_out($s);
    }

    function SetLineWidth($width = 1)
    {
        $s = sprintf('%.2F w', $width);
        $this->_out($s);
    }
}

In the above code snippet, the new class, MyDrawing, is created and it extends from the class FPDF. The function SetDash() sets the dash pattern regarding the input dash pattern format $pattern, the number of black units $black and the number of gap units $white. The k is the protected variable in the class FPDF for the scale factor. After setting the dash pattern in line 8, the protected function $this->_out($s); is called to add a new line to the document.


The function SetLineWidth() is intended to set the line width in the PDF document. It uses the PDF's setlinewidth operator w in line 14: '%.2F w'.

The following codes show how to draw the dash line:

require('mydrawing.php');

$pdf=new MyDrawing();
$pdf->AddPage();

$pdf->SetDash('[%.2F %.2F] 0 d', 1, 1);
$pdf->Line(20, 10, 190, 10);

$pdf->SetLineWidth(2);
$pdf->SetDash('[%.2F %.2F] 0 d', 3, 1);
$pdf->Line(20, 20, 190, 20);

$pdf->SetDash('[] 0 d');
$pdf->SetLineWidth();
$pdf->Line(20, 30, 190, 30);
$pdf->Output();

In line 6, the dash pattern format '[%.2F %.2F] 0 d' is used to set the dash pattern as 1 unit of dash and 1 unit of gap. In line 9, the line width is set as 2 and then in line 10 the dash pattern is set as 3 units of dash and 1 unit of gap. In line 13, the dash pattern format '[] 0 d' is used to set as a no dash, solid line and then the line width is set as default 1 in line 14.

The output of the PDF file looks like this:

The drawing output


Search