如何使用Laravel 5.8中的视图在浏览器中显示PDF文档 [英] How to display PDF Documents on the browser using a View in Laravel 5.8
问题描述
我正在使用Laravel 5.8开发Web应用程序,我是Laravel框架的新手.当用户单击某些按钮时,我想在浏览器中显示PDF文档.我将允许经过身份验证的用户查看"和下载" PDF文档.
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.
我创建了一个Controller和一个Route来显示文档.但是,我很困,因为我有很多文档,而且我不知道如何使用Laravel VIEW分别显示和下载每个文档.
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 */
/* 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!');
}
}
}
/路线/ 路线:: get('/preview-pdf/{id}','PDFController @ view');
/The Route/ Route::get('/preview-pdf/{id}', 'PDFController@view');
推荐答案
Mateus的答案很好地描述了如何设置控制器功能以返回PDF文件.我会在您的/routes/web.php
文件中做类似的事情:
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');
问题的另一部分是如何将PDF嵌入到*.blade.php
视图模板中.为此,我建议使用 PDFObject .这是一个非常简单的PDF查看器JavaScript程序包,可简化嵌入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.
如果使用的是npm
,则可以运行npm install pdfobject -S
来安装此软件包.否则,您可以从 CDN 进行投放,也可以自己托管脚本.包含脚本后,您可以按以下步骤进行设置:
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>
就这样-超级简单!而且,我认为,与导航到单独显示PDF的页面相比,它为您的用户提供了更好的UX.希望对您有所帮助!
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.
这篇关于如何使用Laravel 5.8中的视图在浏览器中显示PDF文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!