Skip to content

Word Wrap Text inside a Paragraph or Cell in PDF Document Using PHP FPDF Library.

wordwrap.php

<?php
require('fpdf.php');
class PDF extends FPDF
{
// function to wrap text in a cell
function WordWrap(&$text, $maxwidth)
{
    // reset text before start wrapping
    $text = trim($text);
    if ($text==='')
        return 0;
    // get the string Width to calculate the space between words
    $space = $this->GetStringWidth(' ');
    $lines = explode("\n", $text);
    $text = '';
    $count = 0;

    foreach ($lines as $line)
    {
        // split the lines into words
        $words = preg_split('/ +/', $line);
        $width = 0;

        foreach ($words as $word)
        {
            // get the width of a word
            $wordwidth = $this->GetStringWidth($word);
            if ($wordwidth > $maxwidth)
            {
                // Word is too long, split it into single letters
                for($i=0; $i<strlen($word); $i++)
                {
                    // get the width of a single letter
                    $wordwidth = $this->GetStringWidth(substr($word, $i, 1));
                    // if the width of a single letter plus the width of the word is less than the max width then add the letter to the text
                    if($width + $wordwidth <= $maxwidth)
                    {
                        $width += $wordwidth;
                        $text .= substr($word, $i, 1);
                    }
                    // if the width of a single letter plus the width of the word is greater than the max width then add the letter to the next line
                    else
                    {
                        $width = $wordwidth;
                        $text = rtrim($text)."\n".substr($word, $i, 1);
                        $count++;
                    }
                }
            }
            elseif($width + $wordwidth <= $maxwidth)
            {
                // if the width of the word is less than the max width then add the word to the text
                $width += $wordwidth + $space;
                $text .= $word.' ';
            }
            else
            {
                $width = $wordwidth + $space;
                $text = rtrim($text)."\n".$word.' ';
                $count++;
            }
        }
        $text = rtrim($text)."\n";
        $count++;
    }
    $text = rtrim($text);
    return $count;
}
}
?>

index.php

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

//create new pdf object
$pdf=new PDF();
//add new page in pdf
$pdf->AddPage();
//set the font for pdf
$pdf->SetFont('Arial','',12);
//create the text for pargraph
$text=str_repeat('this is a word wrap test ',20);
//calculate the number of lines in the paragaph
$nb=$pdf->WordWrap($text,120);
//write the text in pdf
$pdf->Write(5,"This paragraph has $nb lines:\n\n");
$pdf->Write(5,$text);
//output the pdf
$pdf->Output();
?>