WeasyPrintBundle icon indicating copy to clipboard operation
WeasyPrintBundle copied to clipboard

Include local images

Open 0x346e3730 opened this issue 1 year ago • 3 comments
trafficstars

Hello,

As anyone managed to include local images to pdfs created by the bundle ? I have no luck using the asset helper function, I can only use URLs for my img src attribute for now and got no luck loading images locally directly.

Thank you !

0x346e3730 avatar Jan 18 '24 04:01 0x346e3730

Hi! This depends of where is your local is: usually I use {{ asset('local/path/to/img.jpg') }} when the images are inside public directory (e.g. public/local/path/to/img.jpg).

When I use vich/uploader-bundle for dynamically uploaded files I replace asset() with vich_uploader_asset(product) that output the rigth file relative path.

If you assets reside outside of public dir you should pass it's absolute path to twig:

class SomeController extends AbstractController
{
    public function someAction()
    {
        $filePath = '/my/path/outside_my_project_root/';
        return $this->render('some/template.html.twig', ['filePath' => $filePath]);
    }
}
<img src="{{ filePath }}img.jpg" alt="My img">

Or even better, write a service/twig extension that elaborate the full path for you:

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class FileExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('get_file_path', [$this, 'getFilePath']),
        ];
    }

    public function getFilePath($fileName)
    {
        return '/var/www/outside_my_project/' . $fileName;
    }
}
<img src="{{ get_file_path('img.jpg') }}" alt="my img">

endelwar avatar Jan 19 '24 15:01 endelwar

Thank you for your answer ! I can't figure why my images are not rendering, do you see something wrong here ?

I'm inside a service and render the PDF like this

$this->pdf->getOutputFromHtml($this->twig->render($template, $context))

image image

0x346e3730 avatar Jan 19 '24 17:01 0x346e3730

Hello,

I also bumped on this issue. As I understood, it comes from weasyprint command & application that can't fetch the images correctly by using only the absolute path.

We solved it using this asset package config & asset function combination :

framework:
    assets:
        packages:
            pdf:
                base_urls: 'file://%kernel.project_dir%/assets/' # "file://" protocol indication seems very important here
  <img src="{{ asset('path/to/your/img.jpg', 'pdf') }}" alt="img"/> {# path to image at "%kernel.project_dir%/assets/path/to/your/img.jpg" #}

raneomik avatar Apr 03 '24 15:04 raneomik