phpphpword

How can I add margins (not padding) to elements in PHPWord?


I'm working on a modification to PHPWord to include the ability to convert html to Word.
I have page margins working using sections.

I have determined that containers (section, header, footer, div, p, etc.) having styles are pretty much limited to Cell and TextRun elements.
If a div tag includes styles defining borders, margins, padding, backgrounds, etc. I use a table having 1 row and 1 cell.
I have everything working except margins, which would be outside a border.

I tried the code below but it put the margins inside the border so I ended up using that for padding.
I also tried using spaceBefore and spaceAfter for top and bottom margins. It was ignored.

How can I add margins to a Cell element?

$arPadding = self::mapCSSMarginPadding($CSSStyles, 1);
$Style = null;
if($arPadding[0] > 0) $Style["CellMarginTop"] = Converter::pixelToTwip((int)$arPadding[0]);
if($arPadding[1] > 0) $Style["CellMarginRight"] = Converter::pixelToTwip((int)$arPadding[1]);
if($arPadding[2] > 0) $Style["CellMarginBottom"] = Converter::pixelToTwip((int)$arPadding[2]);
if($arPadding[3] > 0) $Style["CellMarginLeft"] = Converter::pixelToTwip((int)$arPadding[3]);

Solution

  • indentation affects Word paragraphs (PHPWord text runs) but not tables.
    indentation can be used for left and right margins, not top and bottom margins.
    indentation: firstLine adds indent to the left of the first line.
    hanging subtracts indent from the first line, thereby making the margin shorter by the value of hanging
    neither firstLine nor hanging adds padding to the value of start/left and end/right
    Word 2016 indentation recognizes either left and right or start and end.
    spaceBefore adds padding to the top of the paragraph (text run).
    spaceAfter adds padding to the bottom of the paragraph (text run).

    Tables can use CellMargin[Top Right Bottom Left] styles on the Table element to add padding to the cells so you can create a 1 cell table with padding. Values are in twips.
    You can put borders and/or backgrounds on the margin cell's style. They will appear outside the 'cellMargin', which is actually padding.

    To add margins you can create a single celled table with cellMargin and put another single cell table inside it. If you also need padding add cellMargin to the second table.