To add the image from the media library to the PDF created with barryvdh/laravel-dompdf, you can follow these steps:
-
First, make sure you have installed and configured the
barryvdh/laravel-dompdfpackage in your Laravel project. -
In your controller method
showPDFpreview, you can retrieve the image URL from the media library using thegetFirstMediaUrlmethod, 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");
}
- In your
show_pdf2.blade.phpview file, you can access the$imageUrlvariable 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.