Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phayes0289's avatar

How to Add a Media Libray Pro Image to a PDF created with barryvdh/laravel-dompdf

This is the code I use on my "laravel "show" page

 <img src="{{ $post->getFirstMediaUrl('Post Images') }}" class="card-img-top" alt="..." style="object-fit: cover;max-height: 400px;">

I want to use the same image on a PDF that is created using barryvdh/laravel-dompdf. This is the current controller that creates the PDF:

 public function showPDFpreview(Post $post)
    {
       
        // Load the blog post view with the $blogPost data
        $content = view('posts.show_pdf2', compact('post'))->render();

        // Generate PDF using DomPDF
        $pdf = PDF::loadHTML($content);

        // (Optional) Set paper size and orientation
        $pdf->setPaper('A4', 'portrait');

         // (Optional) Set paper size and orientation
         $pdf->setPaper('A4', 'portrait');

         // (Optional) Add headers and footers
         // $pdf->setOptions([
         //     'header-html' => view('pdf.header')->render(),
         //     'footer-html' => view('pdf.footer')->render(),
         // ]);

        return $pdf->stream("post.pdf");
    }

How do i do that? Calling for it directly on the blade page returns a missing image

0 likes
2 replies
LaryAI's avatar
Level 58

To add the image from the media library to the PDF created with barryvdh/laravel-dompdf, you can follow these steps:

  1. First, make sure you have installed and configured the barryvdh/laravel-dompdf package in your Laravel project.

  2. In your controller method showPDFpreview, you can retrieve the image URL from the media library using the getFirstMediaUrl method, just like you did in your "laravel show" page. Then, pass this URL to the view.

public function showPDFpreview(Post $post)
{
    $imageUrl = $post->getFirstMediaUrl('Post Images');

    // Load the blog post view with the $blogPost data and the image URL
    $content = view('posts.show_pdf2', compact('post', 'imageUrl'))->render();

    // Generate PDF using DomPDF
    $pdf = PDF::loadHTML($content);

    // Set paper size and orientation
    $pdf->setPaper('A4', 'portrait');

    return $pdf->stream("post.pdf");
}
  1. In your show_pdf2.blade.php view file, you can access the $imageUrl variable and include it in the PDF content using an <img> tag.
<!-- Use the $imageUrl variable to display the image in the PDF -->
<img src="{{ $imageUrl }}" class="card-img-top" alt="..." style="object-fit: cover; max-height: 400px;">

Make sure the show_pdf2.blade.php view file is properly located in the resources/views/posts directory.

With these changes, the image from the media library will be included in the PDF generated by barryvdh/laravel-dompdf.

Please or to participate in this conversation.