Hôm nay, trong bài viết này mình sẽ chia sẻ với các bạn cách dompdf mà header và footer sẽ được hiển thị ở tất cả các trang. Đây cũng là một vấn đề khá phổ biến, khi chúng ta phát triển các tính năng liên quan đến file PDF.

Còn chần chừ gì nữa, các bạn hãy theo chân mình, chúng ta sẽ thực hiện điều đó ngay bây giờ nào.

Cài đặt project Laravel

Trong bước đầu tiên này, nếu bạn chưa có project Laravel, thì bạn hãy chạy lệnh bên dưới, ngược lại thì bạn có thể bỏ qua bước này:

composer create-project --prefer-dist laravel/laravel dompdf

Cài đặt package Dompdf

Trước hết, chúng ta sẽ cài đặt thư viện barryvdh/laravel-dompdf vào project Laravel bằng lệnh sau:

composer require barryvdh/laravel-dompdf

Sau khi cài đặt thư viện thành công, bạn hãy mở file config/app.php và thêm service provideralias như sau:

'providers' => [
    ...
    Barryvdh\DomPDF\ServiceProvider::class,

],

'aliases' => Facade::defaultAliases()->merge([
    ...
    'PDF' => Barryvdh\DomPDF\Facade::class,

])->toArray(),

Cấu hình mặc định được đặt trong config/dompdf.php,sao chép file này vào thư mục cấu hình của Laravel để chúng ta dễ dàng sửa đổi các giá trị bằng lệnh sau:

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

Cấu trúc thư mục và tạo các blade view cần thiết

Tiếp theo, chúng ta vào thư mục resources/views và tạo cấu trúc thư mục như sau:

Trong thư mục prints/css, bạn hãy mở file master.blade.php và chỉnh sửa nội dung như sau:

@page {
    margin: 100px 25px;
}

header {
    position: fixed;
    top: -60px;
    left: 0px;
    right: 0px;
    height: 50px;
    font-size: 20px !important;

    /** Extra personal styles **/
    background-color: #fb925a;
    color: white;
    text-align: center;
    line-height: 35px;
}

footer {
    position: fixed;
    bottom: -60px;
    left: 0px;
    right: 0px;
    height: 50px;
    font-size: 20px !important;

    /** Extra personal styles **/
    background-color: #fb925a;
    color: white;
    text-align: center;
    line-height: 35px;
}

.page-break {
    page-break-after: always;
}

Trong thư mục prints/layouts, bạn hãy mở file master.blade.php và chỉnh sửa nội dung như sau:

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>{{$title ?? ''}}</title>
        <style>
            @include('prints.css.master')
            @yield('css')
        </style>
    </head>
    <body>
        <!-- Define header and footer blocks before your content -->
        <header>
            @yield('header')
        </header>

        <footer>
            @yield('footer')
        </footer>

        <!-- Wrap the content of your PDF inside a main tag -->
        <main>
            @yield('main')
        </main>

        @yield('script')
    </body>
</html>

Trong thư mục prints/templates, bạn hãy mở file example.blade.php và chỉnh sửa nội dung như sau:

@extends('prints.layouts.master', ['title' => $data['title'] ?? ''])

@section('css')
.content {
    color: red;
}
@endsection

@section('header')
    {{$data['title'] ?? ''}}
@endsection

@section('main')
    <p class="content">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    <div class="page-break"></div>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
@endsection

@section('footer')
    Copyright © <?php echo date("Y");?>
@endsection

@section('script')
    <script type="text/php">
        if ( isset($pdf) ) {
            $font = $fontMetrics->get_font("helvetica", "bold");
            $size = 9;
            $y    = $pdf->get_height() - 24;
            $x    = $pdf->get_width() - 24 - $fontMetrics->get_text_width('1/1', $font, $size);
            $pdf->page_text($x, $y, '{PAGE_NUM}/{PAGE_COUNT}', $font, $size);
        }
    </script>
@endsection

Tạo Controller

Trong bước này, chúng ta sẽ tạo một controller. Các bạn hãy sử dụng lệnh dưới đây để tạo controller:

php artisan make:controller PDFController

Tiếp theo, hãy mở file PDFController.php và chỉnh sửa nội dung như sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    /**
     * Write Your Code..
     *
     * @return string
    */
    public function generatePDF()
    {
        $data = [
            'title' => 'Welcome to ManhDan Blogs',
            'date'  => date('m/d/Y'),
        ];
        $pdf = PDF::loadView('prints.templates.example', compact('data'));

        if (request()->stream) {
            return $pdf->stream();
        }

        return $pdf->download('example.pdf');

    }
}

Tạo route

Trong bước này, bạn mở file routes/web.php và chỉnh sửa nội dung như sau:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PDFController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('generate-pdf', [PDFController::class, 'generatePDF']);

Trải nghiệm Dompdf có Header and Footer on every page

Sau khi thực hiện xong các bước phía trên, chúng ta cùng nhau xem lại thành quả xong một chặng đường không quá dài nào.

Nếu bạn muốn download filde PDF, bạn hãy truy cập vào trang bên dưới:

http://127.0.0.1:8000/generate-pdf

Nếu bạn muốn xem nội dung trước khi download, bạn hãy truy cập vào trang bên dưới:

http://127.0.0.1:8000/generate-pdf?stream=1

Kết quả:

Tới đây, thì chúng ta đã thực xong chức năng dompdf có header và footer được hiển thị ở tất cả các trang, mình hy vọng bài viết sẽ giúp cho công việc của các bạn thuận lợi.

Nếu mọi người muốn góp ý cho bài viết này hoàn thiện hơn, bạn có thể liên lạc với mình qua trang contact.

Hy vọng, chúng ta sẽ gặp lại nhau trong bài viết tiếp theo. Cảm ơn bạn.

CÓ THỂ BẠN QUAN TÂM

Laravel Socialite Login With Linkedin

Laravel Socialite Login With Linkedin

LinkedIn LinkedIn là mạng xã hội tập trung vào mạng lưới nghề nghiệp và phát triển nghề nghiệp và chuyên nghiệp lớn nhất thế giới trên internet. Bạn có thể sử dụng LinkedIn để tìm công việc hoặc...

Laravel  Scout Full Text Search with Algolia

Laravel Scout Full Text Search with Algolia

Laravel Scout cung cấp một giải pháp đơn giản, dựa trên trình điều khiển để thêm tìm kiếm Full Text vào các mô hình Eloquent của bạn. Khi sử dụng Eloquent, Scout sẽ tự động giữ chỉ mục tìm kiếm của bạ...

Laravel Factories, Seeder

Laravel Factories, Seeder

Trong bài viết này, tôi sẽ hướng dẫn các bạn về cách tạo dữ liệu giả trong cơ sở dữ liệu bằng cách sử dụng Laravel Factory và Seed trong Database Seeder. Để tạo model factory, bạn cần chạy lệnh sau...

Laravel Export & Import CSV

Laravel Export & Import CSV

Trong bài viết này, tôi sẽ hướng dẫn các tạo cách Export hoặc Import CSV trong Laravel. Nhưng thay vì chỉ viết hàm đơn thuần trong PHP thì tôi sẽ hướng dẫn các tạo ra một Service trong Laravel bằng cá...

Integrating CKFinder into CKEditor 5 in Laravel 11

Integrating CKFinder into CKEditor 5 in Laravel 11

CKEditor 5 CKEditor 5 là một trình soạn thảo văn bản phong phú JavaScript với nhiều tính năng và khả năng tùy chỉnh. CKEditor 5 có kiến trúc MVC hiện đại, mô hình dữ liệu tùy chỉnh và DOM ảo, mang...

Laravel Custom Eloquent Casts

Laravel Custom Eloquent Casts

Trước đây, chúng ta bị giới hạn cast mặc định do Laravel cung cấp. Mặc dù, có một số gói thư viện có thể  giúp chúng ta custom được nhưng chúng có một nhược điểm lớn. Bởi vì, chúng ghi đề phương thức...

Laravel View

Laravel View

View là gì? Đây là phần giao diện (theme) dành cho người sử dụng. Nơi mà người dùng có thể lấy được thông tin dữ liệu của MVC thông qua các thao tác truy vấn như tìm kiếm hoặc sử dụng thông qua các...

Integrating OpenAI in Laravel

Integrating OpenAI in Laravel

OpenAI OpenAI là một phòng thí nghiệm nghiên cứu trí tuệ nhân tạo (AI) của Mỹ bao gồm tổ chức phi lợi nhuận OpenAI Incorporated (OpenAI Inc.) và công ty con hoạt động vì lợi nhuận OpenAI Limited Par...

Laravel One to Many Eloquent Relationship

Laravel One to Many Eloquent Relationship

One to Many Relationship được sử dụng trong trường hợp một dữ liệu của một bảng được liên kết với một hoặc nhiều dữ liệu ở bảng khác. Ví dụ, một bài post có thể có nhiều comment. Vì vậy, trong hướn...

ManhDanBlogs