How to display preview of uploaded pdf in laravel?

Member

by rollin , in category: PHP Frameworks , 6 months ago

How to display preview of uploaded pdf in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 6 months ago

@rollin 

To display a preview of an uploaded PDF in Laravel, you can use a package like spatie/pdf-to-image. This package allows you to convert a PDF file into multiple images, which can then be displayed in your application.


Here's a step-by-step guide on how to display a preview of an uploaded PDF in Laravel using this package:

  1. Install the spatie/pdf-to-image package by running the following composer command in your Laravel project:
1
composer require spatie/pdf-to-image


  1. In your controller, include the necessary namespaces:
1
2
use SpatiePdfToImagePdf;
use IlluminateSupportFacadesStorage;


  1. In your controller method where you handle the file upload, convert the uploaded PDF to images and store them in a public directory:
1
2
3
$pdf = new Pdf($request->file('pdf_file')->path());
$images = $pdf->setResolution(300)
                ->saveImage(public_path('pdf_previews'));


  1. In your view, loop through the images and display them:
1
2
3
@foreach($images as $image)
    <img src="{{ asset('pdf_previews/' . $image) }}" alt="PDF Preview">
@endforeach


  1. Make sure to create the pdf_previews directory in your public folder to store the generated images.
  2. You can further customize the image conversion settings as needed, such as image format, resolution, and quality. Refer to the package documentation for more options.


By following these steps, you should be able to display a preview of an uploaded PDF in your Laravel application.