Search code examples
phpimagesymfonyphpwordphpoffice

Insert Image PhpWord


I can add images using URL but not trying to get a local image file.

$portada->addImage('earth.jpg');

Getting this error:

Uncaught PHP Exception PhpOffice\PhpWord\Exception\InvalidImageException: "" at C:\Users\kaskull\Desktop\symfony\examsgenerator\vendor\phpoffice\phpword\src\PhpWord\Element\Image.php line 386

I'm createing my Word on a controller so my first idea is that should be something like this:

$portada->addImage('../Resources/Asset/images/logo.png');

Getting the same error.

EDIT:

If i do:

$path = realpath('../Resources/Asset/images/logo.png');var_dump(is_readable($path));

It returns FALSE

But if i use this, it runs.

$path=realpath('C:\Users\CARLES\Desktop\symfony\examsfinal\src\AppBundle\Resources\Asset\images\logo.png');

Solution

  • Let's say you have the following folder structure:

    C:\Users\kaskull\Desktop\symfony\examsgenerator\src\AppBundle\Controllers\MyController.php
    
    C:\Users\kaskull\Desktop\symfony\examsgenerator\src\AppBundle\Resources\Asset\images\logo.png
    

    UPDATE:

    Try this in your controller:

    $path = realpath(__DIR__ . '/../Resources/Asset/images/logo.png');
    $portada->addImage($path);
    

    __DIR__ in PHP is the directory of the file (documentation link). You need that because your controller class is executed from the other file context. That is why your relative path doesn't work.