Beispiel #1
5
 /**
  * @throws \PhpOffice\PhpWord\Exception\Exception
  * Создание word для юр вопросов
  */
 public static function ur_questions($row)
 {
     $user = User::findOne(\Yii::$app->user->identity->id);
     $file = \Yii::$app->basePath . '/temp/ur_questions/' . $row['qid'] . '.docx';
     $template = \Yii::$app->basePath . '/temp/ur_questions/Template.docx';
     $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template);
     // Variables on different parts of document
     $row['question'] = str_replace("\n", "<w:br/>", $row['question']);
     //Для пробелов
     $templateProcessor->setValue('vopros', $row['question']);
     $templateProcessor->setValue('date', date("d.m.Y"));
     $templateProcessor->setValue('ur_name', $row['uname']);
     $templateProcessor->setValue('ur_ruk', $row['contact_face']);
     $templateProcessor->setValue('ur_phone', $row['contact_phone']);
     $templateProcessor->setValue('ur_mail', $row['contact_mail']);
     $templateProcessor->setValue('ur_region', $row['rname']);
     //$templateProcessor->setValue('serverName', realpath(__DIR__)); // On header
     $templateProcessor->saveAs($file);
     $qf = explode("|", $row['qfiles']);
     if (!isset($qf[0])) {
         $qf[0] = $qf;
     }
     $mail = \Yii::$app->mail->compose('ur_questions', ['uname' => $row['uname'], 'username' => $user['username'], 'mail' => $user['mail']])->setFrom([\Yii::$app->params['infoEmail'] => 'СоюзФарма'])->setTo(\Yii::$app->params['uristEmail'])->setSubject('Юридический вопрос')->attach($file);
     foreach ($qf as $q) {
         if ($q != "") {
             $mail->attach($q);
         }
     }
     $mail->send();
     // if($templateProcessor->saveAs('results/Sample_07_TemplateCloneRow.docx')) {
     //      return true;
     //  }else{
     //    return false;
     // }
 }
Beispiel #2
2
function createFile($dt)
{
    // cleanup old prog files
    $oldPdfs = glob("files/prog_" . $dt['id'] . "*.html");
    foreach ($oldPdfs as $target) {
        unlink($target);
    }
    // load PhpWord & mpdf libraries via composer
    require_once 'vendor/autoload.php';
    // load, alter and save new docx based on template
    $templ = new \PhpOffice\PhpWord\TemplateProcessor('files/tmpl.docx');
    foreach ($dt as $k => $v) {
        $templ->setValue("{$k}", htmlspecialchars($v));
    }
    $docxFile = "files/exp_" . $dt['id'] . ".docx";
    $templ->saveAs($docxFile);
    // prepare PDF renderer (unused because of high overhead for sch.gr servers - left as a paradigm)
    //\PhpOffice\PhpWord\Settings::setPdfRendererPath(realpath(__DIR__ . '/vendor/mpdf/mpdf/'));
    //\PhpOffice\PhpWord\Settings::setPdfRendererName('MPDF');
    // open the new docx
    $phpWord = \PhpOffice\PhpWord\IOFactory::load($docxFile);
    $random = rand(1000, 3000);
    // add a window.print() section @ end of HTML
    $section = $phpWord->addSection();
    $section->addText('<script>window.print();</script>');
    // save HTML with a random number on filename
    $fileLink = 'files/prog_' . $dt['id'] . $random . '.html';
    $phpWord->save($fileLink, 'HTML');
    // save PDF (unused - see above)
    //$fileLink = 'files/prog_'.$dt['id'].$random.'.pdf';
    //$phpWord->save($fileLink, 'PDF');
    // delete docx
    unlink($docxFile);
    return $fileLink;
}
Beispiel #3
2
require_once "common.inc.php";
require_once "wechatLoop.php";
// Creating the new document...
//$phpWord = new \PhpOffice\PhpWord\PhpWord();
$wechatObj = new wechatFlow();
$uid = $_G[id];
$pro_name = $_GET[pro_name];
$pro_id = $_GET[pro_id];
$pro_level = $_GET[pro_level];
$scores = $_GET[scores];
$meet = $_GET[meet];
$tableName = "pro_process";
$data = $wechatObj->query_pro($tableName, $uid, $pro_id, 1130);
//$count = count($data);
if (is_array($data)) {
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('PHPWord/src/PhpWord/pingjia.docx');
    $templateProcessor->setValue('proname', $pro_name);
    $templateProcessor->setValue('date', date('Y-m-d'));
    //$templateProcessor->setValue('proname', '项目DDDD');
    $templateProcessor->setValue('prolevel', $pro_level);
    $templateProcessor->setValue('meet', $meet);
    $templateProcessor->setValue('scores', $scores);
    //$templateProcessor->cloneRow('num',2);
    //$templateProcessor->saveAs('./test32.docx');
    $str = 'num';
    $sum = 0;
    foreach ($data as $val) {
        $tec = $val["keywords"];
        $sum += count($tec);
    }
    $templateProcessor->cloneRow('num', $sum);
Beispiel #4
1
 function process($template_doc, $fname, $out_dir)
 {
     $values = $this->readSheet($fname);
     if (empty($values)) {
         return false;
     }
     $x = explode('.', basename($fname));
     $values['fname'] = $x[0];
     $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_doc);
     foreach ($values as $key => $value) {
         $templateProcessor->setValue($key, htmlspecialchars($value));
     }
     $save_as = $out_dir . $x[0] . '.' . basename($template_doc);
     if (is_file($save_as)) {
         $dt = (new DateTime('now', new DateTimeZone('america/toronto')))->format('Ymd_His');
         $ext = pathinfo($save_as, PATHINFO_EXTENSION);
         $bu_fname = $save_as . ".{$dt}.{$ext}";
         // die("$dt  $save_as  $bu_fname");
         rename($save_as, $bu_fname);
     }
     $templateProcessor->saveAs($save_as);
     return $save_as;
 }
 public function actionExport($id)
 {
     $filepath = dirname(__FILE__) . '/../runtime/result.docx';
     $template_filepath = dirname(__FILE__) . '/../runtime/templates/Template.docx';
     if (file_exists($template_filepath)) {
         $resource = Resource::findOne($id);
         $filename = $resource->name . '.docx';
         $coordinates = json_decode($resource->coordinates);
         $owner = PersonalData::findOne($resource->owner_data_id);
         $owner_name = $owner->last_name . ' ' . $owner->first_name . ' ' . $owner->middle_name;
         $resource_class = ResourceClass::findOne($resource->class_id)->name;
         $parameters = Parameter::find()->where(['resource_id' => $id])->all();
         $attributes = [];
         foreach ($parameters as $parameter) {
             $parameter_name = ResourceAttribute::findOne($parameter->attribute_id);
             $attributes[$parameter_name->name] = $parameter->value;
         }
         $linear_size = $attributes['length'];
         if ($attributes['width']) {
             $linear_size .= ':' . $attributes['width'];
         }
         if ($attributes['height']) {
             $linear_size .= ':' . $attributes['height'];
         }
         \PhpOffice\PhpWord\Autoloader::register();
         $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_filepath);
         // Template processing
         $templateProcessor->setValue('name', htmlspecialchars($resource->name, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('class', htmlspecialchars($resource_class, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('subclass', htmlspecialchars($subclass, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('owner', htmlspecialchars($owner_name, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('linear_size', htmlspecialchars($linear_size, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('area', htmlspecialchars($attributes['square'], ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('weight', htmlspecialchars($attributes['weight'], ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('perimeter', htmlspecialchars($attributes['perimeter'], ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('volume', htmlspecialchars($attributes['volume'], ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('reason', htmlspecialchars($reason, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('registrar', htmlspecialchars($registrar, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('registrar_address', htmlspecialchars($registrar, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('registration_number', htmlspecialchars($registration_number, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('registration_date', htmlspecialchars($creation_date, ENT_COMPAT, 'UTF-8'));
         $templateProcessor->setValue('registrar_shortname', htmlspecialchars($registrar_short_name, ENT_COMPAT, 'UTF-8'));
         for ($i = 1; $i <= 20; $i++) {
             $lat = "";
             $lng = "";
             if (count($coordinates) >= $i) {
                 $lat = $coordinates[$i - 1][0];
                 $lng = $coordinates[$i - 1][1];
             }
             $templateProcessor->setValue('lat#' . $i, htmlspecialchars($lat, ENT_COMPAT, 'UTF-8'));
             $templateProcessor->setValue('lng#' . $i, htmlspecialchars($lng, ENT_COMPAT, 'UTF-8'));
         }
         // Saving the document as OOXML file...
         $templateProcessor->saveAs($filepath);
         if (file_exists($filepath)) {
             return \Yii::$app->response->sendFile($filepath, $filename, ['inline' => false])->send();
         }
     }
 }
 function PlantillaCorrespondencia()
 {
     try {
         $this->objParam->addParametro('id_funcionario_usuario', $_SESSION["ss_id_funcionario"]);
         $this->objParam->defecto('ordenacion', 'id_correspondencia');
         $this->objParam->defecto('dir_ordenacion', 'desc');
         $this->objParam->addFiltro("cor.id_correspondencia = " . $this->objParam->getParametro('id_correspondencia'));
         $this->objFunc = $this->create('MODCorrespondencia');
         $this->res = $this->objFunc->listarCorrespondencia();
         if ($this->res->getTipo() == 'ERROR') {
             $this->res->imprimirRespuesta($this->res->generarJson());
             exit;
         }
         $correspondencia = $this->res->getDatos();
         //obtener detalle de envios
         $this->objParam->parametros_consulta['ordenacion'] = 'id_correspondencia';
         $this->objParam->parametros_consulta['filtro'] = ' 0 = 0 ';
         $this->objParam->parametros_consulta['cantidad'] = '1000';
         $this->objParam->addFiltro("cor.id_correspondencia_fk = " . $this->objParam->getParametro('id_correspondencia'));
         $this->objFunc = $this->create('MODCorrespondencia');
         $this->res = $this->objFunc->listarCorrespondenciaDetalle($this->objParam);
         if ($this->res->getTipo() == 'ERROR') {
             $this->res->imprimirRespuesta($this->res->generarJson());
             exit;
         }
         $correspondenciaDetalle = $this->res->getDatos();
         //desc_funcionario -> es el funcionario que lo envia
         //desc_uo ->
         //numero numero de la correspondencia
         /*generamos una imagen qr para ingresar a la plantilla*/
         $cadena_qr = '|' . $correspondencia[0]['numero'] . '|' . $correspondencia[0]['desc_uo'] . '|' . $correspondencia[0]['desc_funcionario'] . '';
         $barcodeobj = new TCPDF2DBarcode($cadena_qr, 'QRCODE,M');
         //todo cambiar ese nombre por algo randon
         $nombre_archivo = md5($_SESSION["ss_id_usuario_ai"] . $_SESSION["_SEMILLA"]);
         $png = $barcodeobj->getBarcodePngData($w = 8, $h = 8, $color = array(0, 0, 0));
         $im = imagecreatefromstring($png);
         if ($im !== false) {
             header('Content-Type: image/png');
             imagepng($im, dirname(__FILE__) . "/../../reportes_generados/" . $nombre_archivo . ".png");
             imagedestroy($im);
             $img_qr = dirname(__FILE__) . "/../../reportes_generados/" . $nombre_archivo . ".png";
             if ($correspondencia[0]['desc_ruta_plantilla_documento'] == NULL) {
                 throw new Exception('no tiene plantilla o no esta en el formato correspondiente');
             }
             /*agrego a la plantilla word los datos */
             $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($correspondencia[0]['desc_ruta_plantilla_documento']);
             $templateProcessor->cloneRow('destinatario', count($correspondenciaDetalle));
             for ($i = 0; $i < count($correspondenciaDetalle); $i++) {
                 $xml_destinatario = htmlspecialchars($correspondenciaDetalle[$i]['desc_funcionario']) . '</w:t>
                                 </w:r>
                             </w:p>
                             <w:p w:rsidR="003D7875" w:rsidRDefault="006C602F" w:rsidP="006C602F">
                                 <w:pPr>
                                     <w:pStyle w:val="Encabezado"/>
                                     <w:tabs>
                                         <w:tab w:val="clear" w:pos="4818"/>
                                         <w:tab w:val="left" w:pos="1276"/>
                                         <w:tab w:val="left" w:pos="2268"/>
                                         <w:tab w:val="left" w:pos="2552"/>
                                     </w:tabs>
                                     <w:jc w:val="both"/>
                                     <w:rPr>
                                         <w:b/>
                                         <w:bCs/>
                                         <w:iCs/>
                                         <w:color w:val="000000"/>
                                         <w:lang w:val="es-ES"/>
                                     </w:rPr>
                                 </w:pPr>
                                 <w:r>
                                     <w:rPr>
                                         <w:b/>
                                         <w:bCs/>
                                         <w:iCs/>
                                         <w:color w:val="000000"/>
                                         <w:lang w:val="es-ES"/>
                                     </w:rPr>
                                     <w:t>' . htmlspecialchars($correspondenciaDetalle[$i]["desc_cargo"]) . '</w:t>
                                 </w:r>
                             </w:p>';
                 $numero_key = $i + 1;
                 $key_name = '${destinatario#' . $numero_key . '}</w:t></w:r></w:p>';
                 $key_2 = '${destinatario#1}</w:t></w:r></w:p>';
                 $templateProcessor->setValueDestinatario($key_name, $xml_destinatario);
                 //$templateProcessor->setValue($key_name, $correspondenciaDetalle[$i]['desc_funcionario'].'<br /> '.$correspondenciaDetalle[$i]['desc_cargo']);
             }
             setlocale(LC_ALL, "es_ES@euro", "es_ES", "esp");
             $fecha_documento = strftime("%d/%m/%Y", strtotime($correspondencia[0]['fecha_documento']));
             $templateProcessor->setImg('firma_digital', array('src' => $img_qr, 'swh' => '150'));
             $templateProcessor->setImgFooter('qr', array('src' => $img_qr, 'swh' => '250'));
             //$templateProcessor->setImgHeader('qrh',array('src' => $img_qr, 'swh'=>'250'));
             $templateProcessor->setValue('remitente', htmlspecialchars($correspondencia[0]['desc_funcionario']));
             $templateProcessor->setValue('cargo_remitente', htmlspecialchars($correspondencia[0]['desc_cargo']));
             $templateProcessor->setValue('referencia', htmlspecialchars($correspondencia[0]['referencia']));
             $templateProcessor->setValue('fecha', htmlspecialchars($fecha_documento));
             $templateProcessor->setValue('mensaje', htmlspecialchars($correspondencia[0]['mensaje']));
             $templateProcessor->setValue('numero', htmlspecialchars($correspondencia[0]['numero']));
             //$templateProcessor->setValue('uo', htmlspecialchars($correspondencia[0]['desc_uo']));
             $templateProcessor->saveAs(dirname(__FILE__) . '/../../reportes_generados/' . $nombre_archivo . '.docx');
             $temp['docx'] = $nombre_archivo . '.docx';
             $this->res->setDatos($temp);
             $this->res->imprimirRespuesta($this->res->generarJson());
         } else {
             echo 'ocurrio un error al guardar la imagen.';
         }
     } catch (Exception $e) {
         throw new Exception($e->getMessage(), 2);
     }
     //fin catch
 }
Beispiel #7
0
 public function generateDocInvoice($data)
 {
     try {
         //$InvoiceNo = ;
         $today = date("Y-m-d");
         //$contacPerson = $data->ContactPerson;
         //$taxSize = sizeof($data->TaxJson);
         $invoiceDetails = $data->Invoice;
         $rownum = sizeof($data->Details);
         $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Invoice.docx');
         $templateProcessor->setValue('InvoiceNo', $invoiceDetails->InvoiceNo);
         $templateProcessor->setValue('InvoiceDate', $invoiceDetails->InvoiceDate);
         $templateProcessor->setValue('QuotationNo', $invoiceDetails->QuotationId);
         $templateProcessor->setValue('QuotationDate', $invoiceDetails->QuotationDate);
         $templateProcessor->setValue('WorkorderDate', $invoiceDetails->WorkOrderDate);
         $templateProcessor->setValue('ContactPerson', "Technicia");
         $templateProcessor->cloneRow('Description', $rownum);
         for ($i = 0; $i < $rownum; $i++) {
             $y = $i + 1;
             $sr = "SrNo#" . $y;
             $des = "Description#" . $y;
             $qt = "Qty#" . $y;
             $rat = "rate#" . $y;
             $amt = "Amount#" . $y;
             $templateProcessor->setValue($sr, htmlspecialchars($y, ENT_COMPAT, 'UTF-8'));
             $templateProcessor->setValue($des, htmlspecialchars($data->Details[$i]->quotationDescription, ENT_COMPAT, 'UTF-8'));
             $templateProcessor->setValue($qt, htmlspecialchars($data->Details[$i]->quotationQuantity, ENT_COMPAT, 'UTF-8'));
             $templateProcessor->setValue($rat, htmlspecialchars($data->Details[$i]->quotationUnitRate, ENT_COMPAT, 'UTF-8'));
             $templateProcessor->setValue($amt, htmlspecialchars($data->Details[$i]->amount, ENT_COMPAT, 'UTF-8'));
         }
         $templateProcessor->setValue('TotalAmount', $invoiceDetails->TotalAmount);
         $templateProcessor->setValue('RoundOff', $invoiceDetails->RoundingOffFactor);
         $templateProcessor->setValue('GrandTotal', $invoiceDetails->GrandTotal);
         $templateProcessor->saveAs('GeneratedDocs/Invoices/' . $invoiceDetails->InvoiceNo . '.docx');
     } catch (PDOException $e) {
         return "Exception in generateDocInvoice" . $e->getMessage();
     }
     return "Success";
 }
<?php

include_once 'Sample_Header.php';
// Template processor instance creation
echo date('H:i:s'), ' Creating new TemplateProcessor instance...', EOL;
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Sample_07_TemplateCloneRow.docx');
$block = $templateProcessor->getTemplateStructure();
echo date('H:i:s'), ' Done getting template structure...', EOL;
// Variables on different parts of document
$templateProcessor->setValue('weekday', htmlspecialchars(date('l')));
// On section/content
$templateProcessor->setValue('time', htmlspecialchars(date('H:i')));
// On footer
$templateProcessor->setValue('serverName', htmlspecialchars(realpath(__DIR__)));
// On header
// Simple table
$templateProcessor->cloneRow('rowValue', 10);
// clone block
$templateProcessor->cloneBlock('blockToday', 2);
$templateProcessor->deleteBlock('deleteBlock');
$templateProcessor->setValue('rowValue#1', htmlspecialchars('Sun'));
$templateProcessor->setValue('rowValue#2', htmlspecialchars('Mercury'));
$templateProcessor->setValue('rowValue#3', htmlspecialchars('Venus'));
$templateProcessor->setValue('rowValue#4', htmlspecialchars('Earth'));
$templateProcessor->setValue('rowValue#5', htmlspecialchars('Mars'));
$templateProcessor->setValue('rowValue#6', htmlspecialchars('Jupiter'));
$templateProcessor->setValue('rowValue#7', htmlspecialchars('Saturn'));
$templateProcessor->setValue('rowValue#8', htmlspecialchars('Uranus'));
$templateProcessor->setValue('rowValue#9', htmlspecialchars('Neptun'));
$templateProcessor->setValue('rowValue#10', htmlspecialchars('Pluto'));
$templateProcessor->setValue('rowNumber#1', htmlspecialchars('1'));
 public function actionExport($id)
 {
     $templateFilepath = dirname(__FILE__) . '/../runtime/templates/Template2.docx';
     $source = dirname(__FILE__) . '/../runtime/temp.docx';
     \PhpOffice\PhpWord\Autoloader::register();
     $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($templateFilepath);
     $months = ['Січня', 'Лютого', 'Березня', 'Квітня', 'Травня', 'Червня', 'Липня', 'Серпня', 'Вересня', 'Жовтня', 'Листопада', 'Грудня'];
     $date = getdate();
     $currentDate = $date['mday'] . ' ' . $months[$date['mon'] - 1] . ' ' . $date['year'] . ' року';
     $extractNumber = '№' . $date['mday'] . ($date['mon'] - 1) . substr($date['year'], -2);
     $templateProcessor->setValue('date', $currentDate);
     $templateProcessor->setValue('number', $extractNumber);
     $templateProcessor->saveAs($source);
     $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
     //$phpWord = new \PhpOffice\PhpWord\PhpWord();
     $phpWord->setDefaultFontName('Times New Roman');
     $phpWord->setDefaultFontSize(11);
     $sectionStyle = ['marginTop' => 1000];
     $tableStyle = ['borderSize' => 6, 'borderColor' => '000', 'cellMargin' => 0];
     $innerTableStyle = ['cellMargin' => 20];
     $boldFontStyle = ['bold' => true];
     $italicFontStyle = ['italic' => true];
     $styleCell = ['valign' => 'center'];
     $styleCellBTLR = ['valign' => 'center', 'textDirection' => \PhpOffice\PhpWord\Style\Cell::TEXT_DIR_BTLR];
     $innerTableCellStyle = ['borderRightSize' => 6, 'borderRightColor' => '000', 'borderLeftSize' => 6, 'borderLeftColor' => '000', 'borderBottomSize' => 6, 'borderBottomColor' => '000'];
     $innerTableRightCellStyle = ['borderLeftSize' => 6, 'borderLeftColor' => '000', 'borderBottomSize' => 6, 'borderBottomColor' => '000'];
     $innerTableFontStyle = ['size' => 9];
     $innerTableParagraphStyle = ['align' => 'center'];
     // Get resource data
     $resource = Resource::findOne($id);
     $filename = $resource->name . '.docx';
     $coordinates = json_decode($resource->coordinates);
     $owner_name = 'народ України (Український народ)';
     $resource_class = 'природний ресурс';
     $resource_subclass = ResourceClass::findOne($resource->class_id)->name;
     $creation_date = $resource->date;
     $registrar = PersonalData::findOne($resource->registrar_data_id);
     $registrar_info = $registrar->last_name . ' ' . $registrar->first_name . ' ' . $registrar->middle_name . ' ' . $registrar->address;
     $registrar_shortname = $registrar->last_name . $registrar->first_name[0] . '. ' . $registrar->middle_name[0] . '.';
     $parameters = Parameter::find()->where(['resource_id' => $id])->all();
     $attributes = [];
     foreach ($parameters as $parameter) {
         $parameter_name = ResourceAttribute::findOne($parameter->attribute_id);
         $attributes[$parameter_name->name] = $parameter->value;
     }
     $length = $attributes['length'];
     $width = $attributes['width'];
     $height = $attributes['height'];
     if ($length || $width || $height) {
         if (!$length) {
             $length = '0';
         }
         if (!$width) {
             $width = '0';
         }
         if (!$height) {
             $height = '0';
         }
         $attributes['linear_size'] = $length . ':' . $width . ':' . $height;
     }
     $reason = $resource->reason;
     function formatCoords($num)
     {
         $num = round($num, 4, PHP_ROUND_HALF_DOWN);
         $degrees = floor($num);
         $minfloat = ($num - $degrees) * 60;
         $minutes = floor($minfloat);
         $secfloat = ($minfloat - $minutes) * 60;
         $seconds = round($secfloat);
         if ($seconds == 60) {
             $minutes++;
             $seconds = 0;
         }
         if ($minutes == 60) {
             $degrees++;
             $minutes = 0;
         }
         return (string) $degrees . '°' . (string) $minutes . '\'' . (string) $seconds . '"';
     }
     $tableFields = ['Найменування об’єкту' => $resource->name, 'Клас об’єкту' => $resource_class, 'Підклас об’єкту' => $resource_subclass, 'Власник об’єкту' => $owner_name, 'Географічні координати кутів (вершин) об’єкту у форматі ГГ°ММ\'СС,СС". ' => $coordinates, 'Лінійні розміри об’єкту, Д:Ш:В, м' => $attributes['linear_size'], 'Загальна площа об’єкту, га' => $attributes['square'] / 10000, 'Маса (вага) об’єкту, кг' => $attributes['weight'], 'Периметр об’єкту, м' => $attributes['perimeter'], 'Об’єм об’єкту, м3' => $attributes['volume'], 'Підстава для внесення відомостей до Реєстру' => $reason, 'ПІБ та поштова адреса народного реєстратора' => $registrar_info, 'Реєстраційний номер об’єкту' => $registration_number, 'Дата створення запису' => $creation_date];
     $tableUnitalicFields = ['Клас об’єкту', 'Власник об’єкту'];
     $sections = $phpWord->getSections();
     $section = $sections[0];
     $phpWord->addTableStyle('Resource Table', $tableStyle);
     $table = $section->addTable('Resource Table');
     foreach ($tableFields as $key => $value) {
         if ($value) {
             if (!is_array($value)) {
                 $valueFontStyle = [];
                 if (in_array($key, $tableUnitalicFields)) {
                     $valueFontStyle = $italicFontStyle;
                 }
                 $table->addRow(200);
                 $table->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(8))->addText(htmlspecialchars($key, ENT_COMPAT, 'UTF-8'), $boldFontStyle);
                 $table->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(15))->addText(htmlspecialchars($value, ENT_COMPAT, 'UTF-8'), $valueFontStyle);
             } else {
                 $row = $table->addRow();
                 $row->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(8))->addText(htmlspecialchars($key, ENT_COMPAT, 'UTF-8'), $boldFontStyle);
                 $cell = $row->addCell();
                 $innerTable = $cell->addTable($innerTableStyle);
                 $innerTable->addRow(10);
                 $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars('Північна широта', ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle);
                 $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars('Східна довгота', ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle);
                 $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars("Північна широта \n(продовження)", ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle);
                 $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableRightCellStyle)->addText(htmlspecialchars("Східна довгота \n(продовження)", ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle);
                 $coordinatesNumber = count($coordinates);
                 for ($i = 1; $i <= round($coordinatesNumber / 2); $i++) {
                     $lat = '';
                     $lng = '';
                     $latCont = '';
                     $lngCont = '';
                     if ($coordinatesNumber >= $i) {
                         $lat = formatCoords($coordinates[$i - 1][0]);
                         $lng = formatCoords($coordinates[$i - 1][1]);
                     }
                     if ($coordinatesNumber >= round($coordinatesNumber / 2) + $i) {
                         $latCont = formatCoords($coordinates[$i + round($coordinatesNumber / 2) - 1][0]);
                         $lngCont = formatCoords($coordinates[$i + round($coordinatesNumber / 2) - 1][1]);
                     }
                     $innerTable->addRow(10);
                     $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars($lat, ENT_COMPAT, 'UTF-8'), $italicFontStyle);
                     $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars($lng, ENT_COMPAT, 'UTF-8'), $italicFontStyle);
                     $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars($latCont, ENT_COMPAT, 'UTF-8'), $italicFontStyle);
                     $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableRightCellStyle)->addText(htmlspecialchars($lngCont, ENT_COMPAT, 'UTF-8'), $italicFontStyle);
                 }
             }
         }
     }
     $section->addTextBreak(2);
     $section->addText('Народний реєстратор', $boldFontStyle);
     $section->addText(htmlspecialchars($registrar_shortname, ENT_COMPAT, 'UTF-8'));
     header("Content-Description: File Transfer");
     header('Content-Disposition: attachment; filename="' . $filename . '"');
     header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
     header('Content-Transfer-Encoding: binary');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Expires: 0');
     $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
     $xmlWriter->save("php://output");
 }
<?php

include_once 'Sample_Header.php';
// Template processor instance creation
echo date('H:i:s'), ' Creating new TemplateProcessor instance...', EOL;
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Sample_07_TemplateCloneRow.docx');
// Variables on different parts of document
$templateProcessor->setValue('weekday', htmlspecialchars(date('l')));
// On section/content
$templateProcessor->setValue('time', htmlspecialchars(date('H:i')));
// On footer
$templateProcessor->setValue('serverName', htmlspecialchars(realpath(__DIR__)));
// On header
// Simple table
$templateProcessor->cloneRow('rowValue', 10);
$templateProcessor->setValue('rowValue#1', htmlspecialchars('Sun'));
$templateProcessor->setValue('rowValue#2', htmlspecialchars('Mercury'));
$templateProcessor->setValue('rowValue#3', htmlspecialchars('Venus'));
$templateProcessor->setValue('rowValue#4', htmlspecialchars('Earth'));
$templateProcessor->setValue('rowValue#5', htmlspecialchars('Mars'));
$templateProcessor->setValue('rowValue#6', htmlspecialchars('Jupiter'));
$templateProcessor->setValue('rowValue#7', htmlspecialchars('Saturn'));
$templateProcessor->setValue('rowValue#8', htmlspecialchars('Uranus'));
$templateProcessor->setValue('rowValue#9', htmlspecialchars('Neptun'));
$templateProcessor->setValue('rowValue#10', htmlspecialchars('Pluto'));
$templateProcessor->setValue('rowNumber#1', htmlspecialchars('1'));
$templateProcessor->setValue('rowNumber#2', htmlspecialchars('2'));
$templateProcessor->setValue('rowNumber#3', htmlspecialchars('3'));
$templateProcessor->setValue('rowNumber#4', htmlspecialchars('4'));
$templateProcessor->setValue('rowNumber#5', htmlspecialchars('5'));
$templateProcessor->setValue('rowNumber#6', htmlspecialchars('6'));
<?php

include_once 'Sample_Header.php';
// Template processor instance creation
echo date('H:i:s'), ' Creating new TemplateProcessor instance...', EOL;
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Sample_23_TemplateBlock.docx');
// Will clone everything between ${tag} and ${/tag}, the number of times. By default, 1.
$templateProcessor->cloneBlock('CLONEME', 3);
// Everything between ${tag} and ${/tag}, will be deleted/erased.
$templateProcessor->deleteBlock('DELETEME');
echo date('H:i:s'), ' Saving the result document...', EOL;
$templateProcessor->saveAs('results/Sample_23_TemplateBlock.docx');
echo getEndingNotes(array('Word2007' => 'docx'));
if (!CLI) {
    include_once 'Sample_Footer.php';
}
 function mergeDOCX($source_file, $merged_file)
 {
     // Important: we get the merge data first, because the phpWord
     // autoloader included below stuffs up the Jethro autoloader
     // and causes errors.
     $data = array_values($this->getMergeData());
     // NB THIS FILE HAS BEEN CHANGED!
     require_once 'include/phpword/src/PhpWord/Autoloader.php';
     \PhpOffice\PhpWord\Autoloader::register();
     \PhpOffice\PhpWord\Settings::setTempDir(dirname($source_file));
     $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($source_file);
     if (!$templateProcessor->cloneBlock('MERGEBLOCK', count($data))) {
         $vars = $templateProcessor->getVariables();
         if (empty($vars)) {
             trigger_error("You don't seem to have included any \${keywords} in your file; cannot merge");
             return;
         }
         $templateProcessor->cloneRow(reset($vars), count($data));
     }
     foreach ($data as $num => $row) {
         foreach ($row as $k => $v) {
             $templateProcessor->setValue(strtoupper($k) . '#' . ($num + 1), $this->xmlEntities($v));
         }
     }
     $templateProcessor->saveAs($merged_file);
 }