


How to use Laravel snappy to generate PDF and integrate into Laravel-admin
Aug 15, 2020 pm 01:54 PMThe following tutorial column will introduce to you how to use Laravel snappy to generate PDF and integrate it into Laravel-admin. I hope it will be helpful to friends in need!
I have used python wkhtmltopdf to export PDF before, wkhtmltopdf is indeed very powerful The tool has many page customization options, and will automatically help you grab images from the Internet and render them into PDF. This time I wanted to implement the function of exporting PDF in Laravel-admin, so I found the extension package Laravel snappy, which is an encapsulation of the project https://github.com/KnpLabs/snappy. Coincidentally, it is also passed Call the wkhtmltopdf program to generate PDF.
Installation and configuration// 安裝擴(kuò)展包
composer require barryvdh/laravel-snappy
// 將wkhtmltopdf作為composer依賴
// 對于64位系統(tǒng),使用:
composer require h4cc/wkhtmltopdf-amd64 0.12.x
composer require h4cc/wkhtmltoimage-amd64 0.12.x
For the homestead development environment, you also need to execute: cp vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64 /usr/local/bin/
cp vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64 /usr/local/bin/
chmod +x /usr/local/bin/wkhtmltoimage-amd64
chmod +x /usr/local/bin/wkhtmltopdf-amd64
After installation, in
In the
alias key set the facade alias (optional): <pre class='brush:php;toolbar:false;'>&#39;PDF&#39; => Barryvdh\Snappy\Facades\SnappyPdf::class,
&#39;SnappyImage&#39; => Barryvdh\Snappy\Facades\SnappyImage::class,</pre>
Finally publish the resource file: <pre class='brush:php;toolbar:false;'>php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"</pre>
in
Add in the file:
WKHTML_PDF_BINARY=/usr/local/bin/wkhtmltopdf-amd64 WKHTML_IMG_BINARY=/usr/local/bin/wkhtmltoimage-amd64
Then make the following configuration in the snappy.php
configuration file:
'pdf' => [ 'enabled' => true, 'binary' => env('WKHTML_PDF_BINARY', 'vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'), 'timeout' => 3600, 'options' => [], 'env' => [], ], 'image' => [ 'enabled' => true, 'binary' => env('WKHTML_IMG_BINARY', 'vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64'), 'timeout' => 3600, 'options' => [], 'env' => [], ],
Use
Generate PDF by loading the rendering blade template: $pdf = PDF::loadView('pdf.invoice', $data); //pdf.invoice是你的blade模板
return $pdf->download('invoice.pdf');
Generate through external link:
return PDF::loadFile('http://www.github.com')->inline('github.pdf');
Generate through html, make various settings, and save it:
PDF::loadHTML($html)->setPaper('a4')->setOrientation('landscape')->setOption('margin-bottom', 0)->save('myfile.pdf') // 更多選項(xiàng)可查看wkhtmltopdf的手冊:https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
Laravel-admin export function transformation
The default export format of Laravel-admin is csv, here we will transform it into the desired PDF format.
Simple analysis of Laravel-admin export principleLook at the export button, you can get the format of the three export entries as follows:http://hostname/posts?_export_=all // 導(dǎo)出全部
http://hostname/posts?_export_=page%3A1 // 導(dǎo)出當(dāng)前頁
http://hostname/posts?_export_=selected%3A1 // 導(dǎo)出選定的行
The corresponding controller method should be
. From here, you can find it in
/vendor/encore/laravel-admin/src/Grid.php :<pre class='brush:php;toolbar:false;'>public function render(){
$this->handleExportRequest(true);
try {
$this->build();
} catch (\Exception $e) {
return Handler::renderException($e);
}
$this->callRenderingCallback();
return view($this->view, $this->variables())->render();}</pre>
If there is _export=... parameter in the url, $this->handleExportRequest(true);
The code inside will be executed:
protected function handleExportRequest($forceExport = false){ if (!$scope = request(Exporter::$queryName)) { return; } // clear output buffer. if (ob_get_length()) { ob_end_clean(); } $this->disablePagination(); if ($forceExport) { $this->getExporter($scope)->export(); // 這里將調(diào)用某個(gè)類的export方法 }}
The most important thing is the export
method. We will create a new class that inherits the
class to implement the export logic we want. In addition, look at the getExporter
method: <pre class='brush:php;toolbar:false;'>protected function getExporter($scope){
return (new Exporter($this))->resolve($this->exporter)->withScope($scope);}</pre>
We can also rewrite withScope
in the subclass to perform some parameter settings and interception.
After understanding the basic principles and referring to the Laravel-admin documentation, we can start changing the export Functional. First, create an extension, such as
app/Admin/Extensions/PdfExporter.php, the code is implemented as follows:
<?php namespace App\Admin\Extensions; use Encore\Admin\Grid\Exporters\AbstractExporter; use Encore\Admin\Grid\Exporter; use PDF; class PdfExporter extends AbstractExporter { protected $lackOfUserId = false; public function withScope($scope){ // 你自己的一些處理邏輯,比如: /*if ($scope == Exporter::SCOPE_ALL) { if(request()->has('user_id')) { $this->grid->model()->where('user_id', request()->user_id); } else { $this->lackOfUserId = true; } return $this; }*/ return parent::withScope($scope); } public function export() { // 具體的導(dǎo)出邏輯,比如: if($this->lackOfUserId) { $headers = [ 'Content-Encoding' => 'UTF-8', 'Content-Type' => 'text/html;charset=UTF-8', ]; response('請先篩選出用戶', 200, $headers)->send(); exit(); } $author = $this->grid->model()->getOriginalModel()->first()->user->user_name; $this->grid->model()->orderBy('add_time', 'desc'); // 按年-月分組數(shù)據(jù) $data = collect($this->getData())->groupBy(function ($post) { return Carbon::parse(date('Y-m-d',$post['add_time']))->format('Y-m'); })->toArray(); // 渲染數(shù)據(jù)到blade模板 $output = PDF::loadView('pdf.weibo', compact('data'))->setOption('footer-center', '[page]')->output(); $headers = [ 'Content-Type' => 'application/pdf', 'Content-Disposition' => "attachment; filename=$author.pdf", ]; // 導(dǎo)出文件, response(rtrim($output, "\n"), 200, $headers)->send(); exit; } }
Then, in app/Admin/ Register the extension in bootstrap.php
:
Exporter::extend('pdf-exporter', PdfExporter::class);
Finally, use it in the Grid
method:
protected function grid(){ // 其他邏輯... // 添加導(dǎo)出PDF的擴(kuò)展 $grid->exporter('pdf-exporter'); return $grid;}
In this way, when you click the export button, you can Download PDF now.
The css and js addresses in the blade template must be the complete url address, so mix( 'css/app.css')
should be changed to- asset('css/app.css')
-
It is best to use the http protocol instead of https for the image address, which is less error-prone
Finally, post a rendering:
The above is the detailed content of How to use Laravel snappy to generate PDF and integrate into Laravel-admin. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

The main role of the controller in Laravel is to process HTTP requests and return responses to keep the code neat and maintainable. By concentrating the relevant request logic into a class, the controller makes the routing file simpler, such as putting user profile display, editing and deletion operations in different methods of UserController. The creation of a controller can be implemented through the Artisan command phpartisanmake:controllerUserController, while the resource controller is generated using the --resource option, covering methods for standard CRUD operations. Then you need to bind the controller in the route, such as Route::get('/user/{id

Laravelprovidesrobusttoolsforvalidatingformdata.1.Basicvalidationcanbedoneusingthevalidate()methodincontrollers,ensuringfieldsmeetcriterialikerequired,maxlength,oruniquevalues.2.Forcomplexscenarios,formrequestsencapsulatevalidationlogicintodedicatedc

CachinginLaravelsignificantlyimprovesapplicationperformancebyreducingdatabasequeriesandminimizingredundantprocessing.Tousecachingeffectively,followthesesteps:1.Useroutecachingforstaticrouteswithphpartisanroute:cache,idealforpublicpageslike/aboutbutno

The .env file is a configuration file used in the Laravel project to store environment variables. It separates sensitive information from code and supports multi-environment switching. Its core functions include: 1. Centrally manage database connections, API keys and other configurations; 2. Call variables through env() or config() functions; 3. After modification, the configuration needs to be refreshed before it takes effect; 4. It should not be submitted to version control to prevent leakage; 5. Multiple .env files can be created for different environments. When using it, you should first define variables and then call them in conjunction with configuration file to avoid direct hard coding.

In Laravel tests, the assert method is used to verify that the application is running as expected. Common assert methods include assertTrue(), assertFalse(), assertEquals(), and assertNull(), which are used to verify that the values ??in the logic meet expectations. For HTTP responses, you can use assertStatus(), assertRedirect(), assertSee(), and assertJson() to verify the response status and content. Database verification can be used through assertDatabaseHas() and assertDatabaseMissing

EloquentORMisLaravel’sbuilt-inobject-relationalmapperthatsimplifiesdatabaseinteractionsusingPHPclassesandobjects.1.Itmapsdatabasetablestomodels,enablingexpressivesyntaxforqueries.2.Modelscorrespondtotablesbypluralizingthemodelname,butcustomtablenames

The way to set environment variables in Laravel is to use the .env file, store the variables in a hidden file at the root of the project, and access them through the env() function; but to ensure compatibility with the configuration cache, you should use env() in the configuration file and use config() in the application code to call the variables. The specific steps are as follows: 1. Define variables such as APP_DEBUG=true in the .env file; 2. Read variables using env('APP_DEBUG'); 3. Create config/app.php file and reference environment variables; 4. Call in the application through config('app.debug_mode'); 5. Use phpartisanco
