Row.java

package org.docascode.api.core.office.table;

import org.docascode.api.core.office.ParagraphFormat;
import org.docascode.api.core.office.Utils;
import org.docx4j.XmlUtils;
import org.docx4j.wml.Tc;
import org.docx4j.wml.Tr;

import java.util.ArrayList;
import java.util.List;

public class Row {
    private List<Cell> cells = new ArrayList<>();

    private ParagraphFormat paragraphFormat;

    public Row add(Cell cell){
        this.cells.add(cell);
        return this;
    }

    Tr toTr(Tr templateRow){
        Tr tr = XmlUtils.deepCopy(templateRow);
        if (tr.getContent().size() != this.cells.size()){
            throw new IllegalArgumentException(
                    String.format(
                            "The current row has '%s' item(s), but you specified '%s' cell(s)",
                            tr.getContent().size(),
                            this.cells.size()));
        }
        List<Tc> listRows = Utils.getTargetElements(tr,Tc.class);
        int i=0;
        for (Tc tc : listRows){

            tc.getContent().clear();
            tc.getContent().add(0,this.cells
                    .get(i)
                    .setParagraphFormat(this.paragraphFormat)
                    .toP());
            i++;
        }
        return tr;
    }

    public void setParagraphFormat(ParagraphFormat paragraphFormat) {
        if (this.paragraphFormat == null) {
            this.paragraphFormat = paragraphFormat;
        }
    }
}