0

I am using PHPWord to load a template file and create a new one from it.

$templateName = 'QuoteTemplate1.docx';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($templateName);

$values = ['clientAddressName' => $quote->company_name]; // this array typically has more values
foreach ($values as $key => $value) {
    $templateProcessor->setValue($key, $value);
}

Then I am adding a custom built table to this template, the code is like this:

$table = new PhpOffice\PhpWord\Element\Table([
    'borderSize' => 0,
    'borderColor' => 'none',
    'width' => 9200,
    'unit' => PhpOffice\PhpWord\SimpleType\TblWidth::TWIP
]);
$table->addRow();
$table->addCell(150)->addText('Cell A1');
$table->addCell(150)->addText('Cell A2');
$table->addCell(150)->addText('Cell A3');
$table->addRow();
$table->addCell(150)->addText('Cell B1');
$table->addCell(150)->addText('Cell B2');
$table->addCell(150)->addText('Cell B3');
$templateProcessor->setComplexBlock('quoteItemTable', $table);

I want to add font and paragraph styles to the text in this custom table - and here lies the problem.

If I try something like this:

$templateProcessor->addParagraphStyle('rightAlign', ['alignment' => 'right']);

The I get errors (addParagraphStyle is not a recognized method of $templateProcessor). And if I try:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->addParagraphStyle('rightAlign', ['alignment' => 'right']);

$table->addCell(25)->addText('Cell A1', 'fontStyle', 'rightAlign');

Then I get no errors, but my rightAlign paragraph style is ignored. Please note I get the same results when I try the steps with font styles as well as paragraph styles.

How can I set my own font and paragraph styles inside a template processor?

Jimmery
  • 9,783
  • 25
  • 83
  • 157

1 Answers1

2

The following worked for me:

$my_template = new \PhpOffice\PhpWord\TemplateProcessor(storage_path('template1.docx'));

$table = new \PhpOffice\PhpWord\Element\Table();

$myFontStyle = array('name' => 'Minion Pro', 'size' => 10, 'bold' => true);
$myParagraphStyle = array('align'=>'center', 'spaceBefore'=>50, 'spaceafter' => 50);

$table->addRow();
$table->addCell()->addText('Cell 1', $myFontStyle, $myParagraphStyle );
$table->addCell()->addText('Cell 2', $myFontStyle, $myParagraphStyle );
$table->addCell()->addText('Cell 3', $myFontStyle, $myParagraphStyle );
$my_template->setComplexBlock('table', $table);