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

首頁 php框架 Laravel 如何使用Laravel snappy生成PDF并集成到Laravel-admin

如何使用Laravel snappy生成PDF并集成到Laravel-admin

Aug 15, 2020 pm 01:54 PM
laravel pdf

下面由Laravel教程欄目給大家介紹使用Laravel snappy生成PDF并集成到Laravel-admin的方法,希望對需要的朋友有所幫助!

如何使用Laravel snappy生成PDF并集成到Laravel-admin

Laravel snappy

之前使用過python wkhtmltopdf來導(dǎo)出PDF,wkhtmltopdf確實是很強大的工具,有很多的頁面定制選項,而且會自動幫你把網(wǎng)上的圖片抓取下來,渲染到PDF上。這次想在Laravel-admin中實現(xiàn)導(dǎo)出PDF的功能,于是找到了Laravel snappy這個擴展包,它是對https://github.com/KnpLabs/snappy這個項目的封裝,好巧的是,它也是通過調(diào)用wkhtmltopdf程序來生成PDF的。

安裝與配置

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

對于homestead開發(fā)環(huán)境,還要執(zhí)行:

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

安裝完后,在app.configalias鍵設(shè)置facade別名(可選):

'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

最后發(fā)布資源文件:

php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"

.env文件中添加:

WKHTML_PDF_BINARY=/usr/local/bin/wkhtmltopdf-amd64
WKHTML_IMG_BINARY=/usr/local/bin/wkhtmltoimage-amd64

然后在snappy.php配置文件中做如下配置:

    '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'     => [],
    ],

使用

通過加載渲染blade模板生成PDF:

$pdf = PDF::loadView('pdf.invoice', $data); //pdf.invoice是你的blade模板
return $pdf->download('invoice.pdf');

通過外部鏈接生成:

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

通過html生成,并做各種設(shè)置,并保存之:

PDF::loadHTML($html)->setPaper('a4')->setOrientation('landscape')->setOption('margin-bottom', 0)->save('myfile.pdf')
// 更多選項可查看wkhtmltopdf的手冊:https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

Laravel-admin導(dǎo)出功能改造

Laravel-admin默認的導(dǎo)出格式是csv,這里將把它改造成想要的PDF格式。

Laravel-admin導(dǎo)出原理簡單分析

查看導(dǎo)出按鈕,可得到這三個導(dǎo)出入口格式大概如下:

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)出選定的行

其有對應(yīng)的控制器方法應(yīng)該是index,從這里追查開去,可以找到/vendor/encore/laravel-admin/src/Grid.php中有:

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();}

如果url中有帶_export=…參數(shù),將會執(zhí)行$this->handleExportRequest(true);這里面的代碼:

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方法
    }}

最關(guān)鍵的是export方法,我們將新建一個繼承AbstractExporter類的類,實現(xiàn)我們自己想要的導(dǎo)出邏輯。另外,看getExporter方法:

protected function getExporter($scope){
    return (new Exporter($this))->resolve($this->exporter)->withScope($scope);}

我們還可以在子類中改寫withScope進行一些參數(shù)設(shè)置、攔截。

開始改造導(dǎo)出功能

了解了基本的原理,再參考下Laravel-admin的文檔,我們就可以著手改下導(dǎo)出功能了。

首先,創(chuàng)建一個擴展,如app/Admin/Extensions/PdfExporter.php,代碼實現(xiàn)如下:

<?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()
    {
        // 具體的導(dǎo)出邏輯,比如:
        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",
        ];

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

        exit;
    }
}

接著,在app/Admin/bootstrap.php中注冊擴展:

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

最后,對應(yīng)的在Grid方法中使用:

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

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

這樣,點擊導(dǎo)出按鈕的時候,就可以下載PDF了。

注意事項

  • blade模板中的css、js地址必須是完整的url地址,所以mix('css/app.css')應(yīng)該改為asset('css/app.css')
  • 圖片地址最好使用http協(xié)議代替https,比較不容易出錯

最后,貼個效果圖吧:

使用 Laravel snappy 生成 PDF 并集成到 Laravel-admin

? ? ? ? ? ? ? ? ? ? ? ? ? ?

以上是如何使用Laravel snappy生成PDF并集成到Laravel-admin的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Laravel的政策是什么,如何使用? Laravel的政策是什么,如何使用? Jun 21, 2025 am 12:21 AM

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

Laravel中的路線是什么?如何定義? Laravel中的路線是什么?如何定義? Jun 12, 2025 pm 08:21 PM

在Laravel中,路由是應(yīng)用程序的入口點,用于定義客戶端請求特定URI時的響應(yīng)邏輯。路由將URL映射到對應(yīng)的處理代碼,通常包含HTTP方法、URI和動作(閉包或控制器方法)。1.路由定義基本結(jié)構(gòu):使用Route::verb('/uri',action)的方式綁定請求;2.支持多種HTTP動詞如GET、POST、PUT等;3.可通過{param}定義動態(tài)參數(shù)并傳遞數(shù)據(jù);4.路由可命名以便生成URL或重定向;5.使用分組功能統(tǒng)一添加前綴、中間件等共享設(shè)置;6.路由文件按用途分為web.php、ap

我如何在Laravel運行播種機? (PHP Artisan DB:種子) 我如何在Laravel運行播種機? (PHP Artisan DB:種子) Jun 12, 2025 pm 06:01 PM

Thephpartisandb:seedcommandinLaravelisusedtopopulatethedatabasewithtestordefaultdata.1.Itexecutestherun()methodinseederclasseslocatedin/database/seeders.2.Developerscanrunallseeders,aspecificseederusing--class,ortruncatetablesbeforeseedingwith--trunc

Laravel中工匠命令行工具的目的是什么? Laravel中工匠命令行工具的目的是什么? Jun 13, 2025 am 11:17 AM

Artisan是Laravel的命令行工具,用于提升開發(fā)效率。其核心作用包括:1.生成代碼結(jié)構(gòu),如控制器、模型等,通過make:controller等命令自動創(chuàng)建文件;2.管理數(shù)據(jù)庫遷移與填充,使用migrate運行遷移,db:seed填充數(shù)據(jù);3.支持自定義命令,如make:command創(chuàng)建命令類實現(xiàn)業(yè)務(wù)邏輯封裝;4.提供調(diào)試與環(huán)境管理功能,如key:generate生成密鑰,serve啟動開發(fā)服務(wù)器。熟練使用Artisan可顯著提高Laravel開發(fā)效率。

我如何在Laravel進行測試? (PHP手工測試) 我如何在Laravel進行測試? (PHP手工測試) Jun 13, 2025 am 12:02 AM

ToruntestsinLaraveleffectively,usethephpartisantestcommandwhichsimplifiesPHPUnitusage.1.Setupa.env.testingfileandconfigurephpunit.xmltouseatestdatabaselikeSQLite.2.Generatetestfilesusingphpartisanmake:test,using--unitforunittests.3.Writetestswithmeth

Laravel MVC解釋了:構(gòu)建結(jié)構(gòu)化應(yīng)用程序的初學(xué)者指南 Laravel MVC解釋了:構(gòu)建結(jié)構(gòu)化應(yīng)用程序的初學(xué)者指南 Jun 12, 2025 am 10:25 AM

MVCinLaravelisadesignpatternthatseparatesapplicationlogicintothreecomponents:Model,View,andController.1)Modelshandledataandbusinesslogic,usingEloquentORMforefficientdatamanagement.2)Viewspresentdatatousers,usingBladefordynamiccontent,andshouldfocusso

Laravel中的控制器是什么,他們的目的是什么? Laravel中的控制器是什么,他們的目的是什么? Jun 20, 2025 am 12:31 AM

控制器在Laravel中的主要作用是處理HTTP請求并返回響應(yīng),以保持代碼的整潔和可維護性。通過將相關(guān)請求邏輯集中到一個類中,控制器使路由文件更簡潔,例如將用戶資料展示、編輯和刪除等操作分別放在UserController的不同方法中。創(chuàng)建控制器可通過Artisan命令phpartisanmake:controllerUserController實現(xiàn),而資源控制器則使用--resource選項生成,涵蓋標(biāo)準(zhǔn)CRUD操作的方法。接著需在路由中綁定控制器,如Route::get('/user/{id

如何啟動Laravel開發(fā)服務(wù)器? (PHP手工藝品) 如何啟動Laravel開發(fā)服務(wù)器? (PHP手工藝品) Jun 12, 2025 pm 07:33 PM

要啟動Laravel開發(fā)服務(wù)器,請使用命令phpartisanserve,默認在http://127.0.0.1:8000提供服務(wù)。1.確保終端位于包含artisan文件的項目根目錄,若不在正確路徑則使用cdyour-project-folder切換;2.運行命令并檢查錯誤,如PHP未安裝、端口被占用或文件權(quán)限問題,可指定不同端口如phpartisanserve--port=8080;3.在瀏覽器訪問http://127.0.0.1:8000查看應(yīng)用首頁,若無法加載請確認端口號、防火墻設(shè)置或嘗試

See all articles