Генерация docx по шаблону в yii2

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Генерация docx по шаблону в yii2

Сообщение svil »

Какие есть варианты для генерации документов из созданных записей в БД по шаблону ${v1}?
Если PhpWord, то как лучше использовать в виде подключенной библиотеки или готового расширения?
Есть ли другие способы?
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Генерация docx по шаблону в yii2

Сообщение svil »

Установила через composer https://github.com/PHPOffice/PHPWord . библиотеку
Последний раз редактировалось svil 2019.04.22, 22:27, всего редактировалось 1 раз.
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Генерация docx по шаблону в yii2

Сообщение svil »

В Контроллер вставила тестовый код с документации.
И в папку web загрузился сгенерированный helloWorld.docx
Теперь как шаблон из БД создать?

Код: Выделить всё

 public function actionIndex()
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();

        /* Note: any element you append to a document must reside inside of a Section. */

// Adding an empty Section to the document...
        $section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
        $section->addText(
            '"Learn from yesterday, live for today, hope for tomorrow. '
            . 'The important thing is not to stop questioning." '
            . '(Albert Einstein)'
        );

        /*
         * Note: it's possible to customize font style of the Text element you add in three ways:
         * - inline;
         * - using named font style (new font style object will be implicitly created);
         * - using explicitly created font style object.
         */

// Adding Text element with font customized inline...
        $section->addText(
            '"Great achievement is usually born of great sacrifice, '
            . 'and is never the result of selfishness." '
            . '(Napoleon Hill)',
            array('name' => 'Tahoma', 'size' => 10)
        );

// Adding Text element with font customized using named font style...
        $fontStyleName = 'oneUserDefinedStyle';
        $phpWord->addFontStyle(
            $fontStyleName,
            array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
        );
        $section->addText(
            '"The greatest accomplishment is not in never falling, '
            . 'but in rising again after you fall." '
            . '(Vince Lombardi)',
            $fontStyleName
        );

// Adding Text element with font customized using explicitly created font style object...
        $fontStyle = new \PhpOffice\PhpWord\Style\Font();
        $fontStyle->setBold(true);
        $fontStyle->setName('Tahoma');
        $fontStyle->setSize(13);
        $myTextElement = $section->addText('"Believe you can and you\'re halfway there." (Theodor Roosevelt)');
        $myTextElement->setFontStyle($fontStyle);

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

        return $this->render('index');
    }
someweb
Сообщения: 552
Зарегистрирован: 2017.03.09, 10:12

Re: Генерация docx по шаблону в yii2

Сообщение someweb »

Чтобы правильно задать вопрос, нужно знать бо́льшую часть ответа. Роберт Шекли.
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Генерация docx по шаблону в yii2

Сообщение svil »

Не работает header c foreach и я не могу скачать сгенерированные шаблоны

Код: Выделить всё

<?php
use PhpOffice\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;
/**
 * Created by PhpStorm.
 * User: svetlanailina
 * Date: 2019-04-23
 * Time: 16:24
 */
$templateWord = new TemplateProcessor('plantilla.docx');
//$q=Post::find()->all();
foreach ($q as $qi){
    $templateWord->setValue('nombre_empresa',$qi->title);
    $templateWord->setValue('direccion_empresa',$qi->description);
    $templateWord->setValue('municipio_empresa',$qi->id);
    $templateWord->setValue('provincia_empresa',$qi->id);
    $templateWord->setValue('cp_empresa',$qi->id);
    $templateWord->setValue('telefono_empresa',$qi->id);

    $file=$qi->title.'.docx';
    echo "$file";
    $templateWord->saveAs($file);
   header("Content-Disposition: attachment; filename=$file; charset=utf-8",  true, 200);
    //  header('Location: http://localhost/pages', true, 200);

    echo file_get_contents($file);
}

Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Генерация docx по шаблону в yii2

Сообщение svil »

zip файл скачивается, но не распаковывается

Код: Выделить всё

<?php
use PhpOffice\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;

//use PhpOffice\Common\Adapter\Zip;
/**
 * Created by PhpStorm.
 * User: svetlanailina
 * Date: 2019-04-23
 * Time: 16:24
 */
//$templateWord = new PhpOffice\PhpWord\TemplateProcessor('plantilla.docx');
//$q=Post::find()->all();
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($q as $qi) {
    $templateWord = new PhpOffice\PhpWord\TemplateProcessor('plantilla.docx');
    $templateWord->setValue('nombre_empresa', $qi->title);
    $templateWord->setValue('direccion_empresa', $qi->description);
    $templateWord->setValue('municipio_empresa', $qi->id);
    $templateWord->setValue('provincia_empresa', $qi->id);
    $templateWord->setValue('cp_empresa', $qi->id);
    $templateWord->setValue('telefono_empresa', $qi->id);

    $download_file = $qi->id .'.docx';
echo  $download_file;
    $zip->addFile( $download_file);
echo "<br/>";
    $templateWord->saveAs($download_file);


}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>


someweb
Сообщения: 552
Зарегистрирован: 2017.03.09, 10:12

Re: Генерация docx по шаблону в yii2

Сообщение someweb »

До header не должно быть никакого вывода.
Отправка файла
https://www.yiiframework.com/doc/api/2. ... e()-detail
Точно как в примере: return в контроллере, без echo и любого вывода где либо еще.
Чтобы правильно задать вопрос, нужно знать бо́льшую часть ответа. Роберт Шекли.
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Генерация docx по шаблону в yii2

Сообщение svil »

Вот так работает

Код: Выделить всё

$zipname = 'file3.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($q as $qi) {
    $templateWord = new PhpOffice\PhpWord\TemplateProcessor('plantilla.docx');
    $templateWord->setValue('nombre_empresa', $qi->title);
    $templateWord->setValue('direccion_empresa', $qi->description);
    $templateWord->setValue('municipio_empresa', $qi->id);
    $templateWord->setValue('provincia_empresa', $qi->id);
    $templateWord->setValue('cp_empresa', $qi->id);
    $templateWord->setValue('telefono_empresa', $qi->id);

    $download_file = $qi->id .'.docx';
echo  $download_file;
    $zip->addFile($download_file);
echo "<br/>";
    $templateWord->saveAs($download_file);


}
$zip->close();

header("Content-Disposition: attachment; filename=$zipname; charset=UTF-8");
echo file_get_contents($zipname);
Ответить