Showing posts with label phpworddoc. Show all posts
Showing posts with label phpworddoc. Show all posts

Tuesday, September 25, 2018

PHPWord - Convert html to docx with header and footer layouts

Here is the simple and additional reasons to set the header with logo and address contents, and footer with positions on easy way.


       /* Convert HTML to word */
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->setDefaultFontSize($fontSize);
        $phpWord->setDefaultFontName($fontFamily);
        $phpWord->setDefaultParagraphStyle(
           [
                'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(0),
                'spacing' => 120,
                'lineHeight' => 1,
           ]
        );

        if ($addresstxt && ($headerlogoposition != $headercompanyposition)) {
            $imageStyle = [
                'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.50),
                'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.50),
                'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE,
                'posHorizontal' => $headerlogoposition,
                'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
                'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN
            ];
        } else {
            $imageStyle = [
                'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.50),
                'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.50),
                'alignment' => $headerlogoposition
            ];
        }
        $section = $phpWord->addSection();
        if($headerLogo || $addresstxt) {
            $header = $section->addHeader();

            if ($headerLogo) {
                $header->addImage($headerLogo, $imageStyle);
            }

            if ($addresstxt) {
                $textlines = explode("\n", $addresstxt);
                for ($i = 0; $i < sizeof($textlines); $i++) {
                    $header->addText($textlines[$i], ['size' => $headerfontsize], ['alignment' => $headercompanyposition]);
                }
            }
        }

        if ($footerTxt) {
            $footer = $section->addFooter();
            $footer->addText($footerTxt, ['size' => $footerfontsize], ['alignment' => $footerposition]);
        }

        $html = mb_convert_encoding($templateHtml, 'HTML-ENTITIES', 'UTF-8');
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($fileUrl);