Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel: How to insert an image in the first page header and enlarge it to fit it's content?

Tags:

php

phpexcel

I have an Excel file made with PHPExcel which have an header with a left aligned logo and right aligned date & user text. For the first page, I want a similar header (same logo and same date & user text) but with some added information (title and parameters of the file centered a couples lines later).

This is what I'm doing so far:

<?php

    $sheet = $this->_spreadsheet->getActiveSheet(); //_spreadsheet is an instance of PHPExcel

    $logo = new PHPExcel_Worksheet_HeaderFooterDrawing();
    $logo->setName('Logo');
    $logo->setPath(DOCUMENT_ROOT . '/public/logo.jpg'); //Path is OK & tested under PHP
    $logo->setHeight(38); //If image is larger/smaller than that, image will be proportionally resized
    $sheet->getHeaderFooter()->addImage($logo, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);

    $sheet->getHeaderFooter()->setOddHeader('&L&G&RExport date: ' . date('Y-m-d H:i:s') . "\n" . 'User: ' . $user->name);

    if ($grid->getTitle() != '') {
        $sheet->getHeaderFooter()->setDifferentFirst(true);

        $sheet->getHeaderFooter()->addImage($logo, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);
        $sheet->getHeaderFooter()->setFirstHeader('&L&G&C&"-,Bold"' . "\n\n\n" . $grid->getTitle() . "\n" . $grid->getParameters() . '&RExport date: ' . date('Y-m-d H:i:s') . "\n" . 'User: ' . $user->name);
    }

?>

For the "regular" header, logo and text is all there so everything is OK. For the first page header I have 2 problems:

  1. The logo isn't showing on the first page header (but the text is OK).
  2. Since the centered title will be followed by some text (dynamically loaded with getParameters) I want the first page header to stretch to fit it's content.

How can I do this with PHPExcel?

like image 632
AlexV Avatar asked Nov 04 '22 20:11

AlexV


1 Answers

I don't have an answer for why the logo isn't showing on the first page header, but to stretch the height to fit the content you need to manually alter the page margins.

I'm not sure the best way to do it, whether counting newline characters or what. But once you know how many lines you have, you could do something like:

$headerHeight = ( $imageHeight / 72 ) + ( $headerLineCount * $lineHeight );
$objPHPExcel->getActiveSheet()->getPageMargins()->setHeader( $margin );
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop( $margin + $headerHeight );

** The "$imageHeight / 72" clause is just a guess at how to convert your image's screen height into inches.

like image 127
Farray Avatar answered Nov 15 '22 00:11

Farray