国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home PHP Framework Laravel How to use Laravel snappy to generate PDF and integrate into Laravel-admin

How to use Laravel snappy to generate PDF and integrate into Laravel-admin

Aug 15, 2020 pm 01:54 PM
laravel pdf

The 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!

How to use Laravel snappy to generate PDF and integrate into Laravel-admin

Laravel snappy

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

// 安裝擴展包
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

app.config

In the

alias

key set the facade alias (optional): <pre class='brush:php;toolbar:false;'>&amp;#39;PDF&amp;#39; =&gt; Barryvdh\Snappy\Facades\SnappyPdf::class, &amp;#39;SnappyImage&amp;#39; =&gt; Barryvdh\Snappy\Facades\SnappyImage::class,</pre>Finally publish the resource file: <pre class='brush:php;toolbar:false;'>php artisan vendor:publish --provider=&quot;Barryvdh\Snappy\ServiceProvider&quot;</pre> in

.env

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:

    &#39;pdf&#39; => [
        &#39;enabled&#39; => true,
        &#39;binary&#39;  => env(&#39;WKHTML_PDF_BINARY&#39;, &#39;vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64&#39;),
        &#39;timeout&#39; => 3600,
        &#39;options&#39; => [],
        &#39;env&#39;     => [],
    ],

    &#39;image&#39; => [
        &#39;enabled&#39; => true,
        &#39;binary&#39;  => env(&#39;WKHTML_IMG_BINARY&#39;, &#39;vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64&#39;),
        &#39;timeout&#39; => 3600,
        &#39;options&#39; => [],
        &#39;env&#39;     => [],
    ],

Use

Generate PDF by loading the rendering blade template:

$pdf = PDF::loadView(&#39;pdf.invoice&#39;, $data); //pdf.invoice是你的blade模板
return $pdf->download(&#39;invoice.pdf&#39;);
Generate through external link:

return PDF::loadFile(&#39;http://www.github.com&#39;)->inline(&#39;github.pdf&#39;);

Generate through html, make various settings, and save it:

PDF::loadHTML($html)->setPaper(&#39;a4&#39;)->setOrientation(&#39;landscape&#39;)->setOption(&#39;margin-bottom&#39;, 0)->save(&#39;myfile.pdf&#39;)
// 更多選項可查看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 principle

Look at the export button, you can get the format of the three export entries as follows:

http://hostname/posts?_export_=all  // 導出全部
http://hostname/posts?_export_=page%3A1 // 導出當前頁
http://hostname/posts?_export_=selected%3A1 // 導出選定的行
The corresponding controller method should be

index

. From here, you can find it in

/vendor/encore/laravel-admin/src/Grid.php

<pre class='brush:php;toolbar:false;'>public function render(){ $this-&gt;handleExportRequest(true); try { $this-&gt;build(); } catch (\Exception $e) { return Handler::renderException($e); } $this-&gt;callRenderingCallback(); return view($this-&gt;view, $this-&gt;variables())-&gt;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)用某個類的export方法
    }}

The most important thing is the export method. We will create a new class that inherits the

AbstractExporter

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))-&gt;resolve($this-&gt;exporter)-&gt;withScope($scope);}</pre>We can also rewrite withScope in the subclass to perform some parameter settings and interception.

Start modifying the export function

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(&#39;user_id&#39;)) {
                $this->grid->model()->where(&#39;user_id&#39;, request()->user_id);
            } else {
                $this->lackOfUserId = true;
            }
            return $this;
        }*/
        return parent::withScope($scope);
    }

    public function export()
    {
        // 具體的導出邏輯,比如:
        if($this->lackOfUserId) {
            $headers = [
                &#39;Content-Encoding&#39;    => &#39;UTF-8&#39;,
                &#39;Content-Type&#39;        => &#39;text/html;charset=UTF-8&#39;,
            ];
            response(&#39;請先篩選出用戶&#39;, 200, $headers)->send();
            exit();
        }
        $author = $this->grid->model()->getOriginalModel()->first()->user->user_name;

        $this->grid->model()->orderBy(&#39;add_time&#39;, &#39;desc&#39;);

        // 按年-月分組數(shù)據(jù)
        $data = collect($this->getData())->groupBy(function ($post) {
            return Carbon::parse(date(&#39;Y-m-d&#39;,$post[&#39;add_time&#39;]))->format(&#39;Y-m&#39;);
        })->toArray();
        // 渲染數(shù)據(jù)到blade模板
        $output = PDF::loadView(&#39;pdf.weibo&#39;, compact(&#39;data&#39;))->setOption(&#39;footer-center&#39;, &#39;[page]&#39;)->output();

        $headers = [
            &#39;Content-Type&#39;        => &#39;application/pdf&#39;,
            &#39;Content-Disposition&#39; => "attachment; filename=$author.pdf",
        ];

        // 導出文件,
        response(rtrim($output, "\n"), 200, $headers)->send();

        exit;
    }
}

Then, in app/Admin/ Register the extension in bootstrap.php:

Exporter::extend(&#39;pdf-exporter&#39;, PdfExporter::class);

Finally, use it in the Grid method:

protected function grid(){
    // 其他邏輯...

    // 添加導出PDF的擴展
    $grid->exporter(&#39;pdf-exporter&#39;);
    return $grid;}

In this way, when you click the export button, you can Download PDF now.

Notes

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to test Laravel API interface? How to test Laravel API interface? May 22, 2025 pm 09:45 PM

Efficient methods for testing Laravel API interfaces include: 1) using Laravel's own testing framework and third-party tools such as Postman or Insomnia; 2) writing unit tests, functional tests and integration tests; 3) emulating a real request environment and managing database status. Through these steps, the stability and functional integrity of the API can be ensured.

How to customize Laravel's user authentication logic? How to customize Laravel's user authentication logic? May 22, 2025 pm 09:36 PM

Custom Laravel user authentication logic can be implemented through the following steps: 1. Add additional verification conditions when logging in, such as mailbox verification. 2. Create a custom Guard class and expand the authentication process. Custom authentication logic requires a deep understanding of Laravel's authentication system and pay attention to security, performance and maintenance.

How to create Laravel package (Package) development? How to create Laravel package (Package) development? May 29, 2025 pm 09:12 PM

The steps to create a package in Laravel include: 1) Understanding the advantages of packages, such as modularity and reuse; 2) following Laravel naming and structural specifications; 3) creating a service provider using artisan command; 4) publishing configuration files correctly; 5) managing version control and publishing to Packagist; 6) performing rigorous testing; 7) writing detailed documentation; 8) ensuring compatibility with different Laravel versions.

Laravel integration with social media login (OAuth) Laravel integration with social media login (OAuth) May 22, 2025 pm 09:27 PM

Integrating social media login in the Laravel framework can be achieved by using the LaravelSocialite package. 1. Install the Socialite package: use composerrequirelaravel/socialite. 2. Configure the service provider and alias: add relevant configuration in config/app.php. 3. Set API credentials: Configure social media API credentials in .env and config/services.php. 4. Write controller method: Add redirection and callback methods to handle social media login process. 5. Handle FAQs: Ensure user uniqueness, data synchronization, security and error handling. 6. Optimization practice:

How to implement password reset function in Laravel? How to implement password reset function in Laravel? May 22, 2025 pm 09:42 PM

Implementing password reset function in Laravel requires the following steps: 1. Configure the email service and set relevant parameters in the .env file; 2. Define password reset routes in routes/web.php; 3. Customize email templates; 4. Pay attention to email sending problems and the validity period of tokens, and adjust the configuration if necessary; 5. Consider security to prevent brute-force attacks; 6. After the password reset is successful, force the user to log out of other devices.

Common security threats and protection measures for Laravel applications Common security threats and protection measures for Laravel applications May 22, 2025 pm 09:33 PM

Common security threats in Laravel applications include SQL injection, cross-site scripting attacks (XSS), cross-site request forgery (CSRF), and file upload vulnerabilities. Protection measures include: 1. Use EloquentORM and QueryBuilder for parameterized queries to avoid SQL injection. 2. Verify and filter user input to ensure the security of output and prevent XSS attacks. 3. Set CSRF tokens in forms and AJAX requests to protect the application from CSRF attacks. 4. Strictly verify and process file uploads to ensure file security. 5. Regular code audits and security tests are carried out to discover and fix potential security vulnerabilities.

What is Middleware in Laravel? How to use it? What is Middleware in Laravel? How to use it? May 29, 2025 pm 09:27 PM

Middleware is a filtering mechanism in Laravel that is used to intercept and process HTTP requests. Use steps: 1. Create middleware: Use the command "phpartisanmake:middlewareCheckRole". 2. Define processing logic: Write specific logic in the generated file. 3. Register middleware: Add middleware in Kernel.php. 4. Use middleware: Apply middleware in routing definition.

Laravel Page Cache Policy Laravel Page Cache Policy May 29, 2025 pm 09:15 PM

Laravel's page caching strategy can significantly improve website performance. 1) Use cache helper functions to implement page caching, such as the Cache::remember method. 2) Select the appropriate cache backend, such as Redis. 3) Pay attention to data consistency issues, and you can use fine-grained caches or event listeners to clear the cache. 4) Further optimization is combined with routing cache, view cache and cache tags. By rationally applying these strategies, website performance can be effectively improved.

See all articles