Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display PDF Documents on the browser using a View in Laravel 5.8

Tags:

laravel

I'm working on a web application using Laravel 5.8, I'm new to Laravel framework. I would like to display PDF documents on the browser when users click on some buttons. I will allow authenticated users to "View" and "Download" the PDF documents.

I have created a Controller and a Route to allow displaying of the documents. I'm however stuck because I have a lot of documents and I don't know how to use a Laravel VIEW to display and download each document individually.

/* PDFController*/

public function view($id)
{
    $file = storage_path('app/pdfs/') . $id . '.pdf';

    if (file_exists($file)) {

        $headers = [
            'Content-Type' => 'application/pdf'
        ];

        return response()->download($file, 'Test File', $headers, 'inline');
    } else {
        abort(404, 'File not found!');
    }
}

}

/The Route/ Route::get('/preview-pdf/{id}', 'PDFController@view');

like image 745
Amos Avatar asked Nov 01 '25 05:11

Amos


1 Answers

Mateus' answer does a good job describing how to setup your controller function to return the PDF file. I would do something like this in your /routes/web.php file:

Route::get('/show-pdf/{id}', function($id) {
    $file = YourFileModel::find($id);
    return response()->file(storage_path($file->path));
})->name('show-pdf');

The other part of your question is how to embed the PDF in your *.blade.php view template. For this, I recommend using PDFObject. This is a dead simple PDF viewer JavaScript package that makes embedding PDFs easy.

If you are using npm, you can run npm install pdfobject -S to install this package. Otherwise, you can serve it from a CDN, or host the script yourself. After including the script, you set it up like this:

HTML:

<div id="pdf-viewer"></div>

JS:

<script>
PDFObject.embed("{{ route('show-pdf', ['id' => 1]) }}", "#pdf-viewer");
</script>

And that's it — super simple! And, in my opinion, it provides a nicer UX for your users than navigating to a page that shows the PDF all by itself. I hope you find this helpful!


UPDATE: After reading your comments on the other answer, I thought you might find this example particularly useful for what you are trying to do.

like image 186
Vince Avatar answered Nov 03 '25 11:11

Vince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!