Create word file in PHP [duplicate]

0

I have a docx file, a contract template. In it, buyer data and other data are variable. The system in PHP needs to get information from the database and replace it in the docx template file. That is, keep the main structure and replace only a few words. After, save the word and make it available for download.

I have seen some libraries that do this, where you can define variables and make these substitutions. However, I do not remember the name or how to do it.

Someone who could help me? With resources that I can use and / or small examples?

Example: The document has a fixed paragraph. In this paragraph, a word will be defined variable at the time of generating the file and after customizing the template, it should be saved in docx.

    
asked by anonymous 01.06.2018 / 01:39

1 answer

1

Use PHPOffice/PHPWord , you must use composer , read about this: / p>

  • Then in the project folder run:

    composer require phpoffice / phpword

Then in your file you are going to execute:

<?php

require_once '../vendor/autoload.php';

$phpWord = new \PhpOffice\PhpWord\PhpWord();

// Adiciona sessão com texto
$section = $phpWord->addSection();
$section->addText('Foo bar baz, etc etc etc 1');

$section->addText('Foo bar baz, etc etc etc 2', array(
    'name' => 'Tahoma',
    'size' => 10
));

// Adiciona texto com fonte customizada
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
    $fontStyleName,
    array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);

$section->addText('Teste test', $fontStyleName);

// Texto com fonte diferente
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('Foo Bar Baz');
$myTextElement->setFontStyle($fontStyle);

// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

//Local para salvar o documento
$objWriter->save('exemplo.docx');
    
01.06.2018 / 19:54