phpphpword

In PHPWord, Right and Left Align Words


I was wondering if there was anyway to left and right align some text on the same line. So for example a resume would have a company name aligned to the left, and a date aligned to the right, on the same line.

I was trying to do this with a text run, but doesn't seem to work. I know I can use \t\t but the left text is going to be different lengths, so the tabs will be very inconsistent.

This is just a simple example:

$section = $phpWord->addSection();
$textrun = $section->addTextRun();
$textrun->addText("Left Text", array(), array("align" => "left"));
$textrun->addText("Right Text", array(), array("align" => "right"));

Solution

  • You can achieve the effect of different alignment on the same line of text using a paragraph style with a single custom tab stop, right aligned against the right margin.

    $section = $phpWord->addSection();
    
    $section_style = $section->getStyle();
    $position =
        $section_style->getPageSizeW()
        - $section_style->getMarginRight()
        - $section_style->getMarginLeft();
    $phpWord->addParagraphStyle(
        'leftRight',
        ['tabs' => [new \PhpOffice\PhpWord\Style\Tab('right', $position)]]);
    
    $section->addText('Left Text\tRight Text', [], 'leftRight');