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 TinyMCE 6 Image Upload

Laravel TinyMCE 6 Image Upload

TinyMCE TinyMCE là một trình soạn thảo  WYSIWYG  được xây dựng trên nền tảng Javascript, được phát triển dưới dạng mã nguồn mở theo giấy phép  MIT  bởi Tiny Technologies Inc. TinyMCE cho phép ngư...

Laravel customize your API Versioning Route File

Laravel customize your API Versioning Route File

Trong khuôn khổ của Laravel, các route của api được tách thành một file duy nhất, đó là file api.php nằm trong thư mục routes . Nếu chúng ta muốn thêm version vào route api thì chúng ta sẽ làm như...

Integrating CKFinder with Amazon S3 in Laravel

Integrating CKFinder with Amazon S3 in Laravel

CKFinder 3 CKFinder 3 là trình quản lý tập tin được tích hợp với CKEditor 4 và CKEditor 5. Nó giúp bạn dễ dàng đưa các tập tin và hình ảnh vào nội dung của Editor một cách an toàn. Đây là một tín...

Document Laravel API With OpenAPI (Swagger)

Document Laravel API With OpenAPI (Swagger)

Swagger là gì? Swagger là một Ngôn ngữ mô tả giao diện để mô tả các API RESTful được thể hiện bằng JSON. Swagger được sử dụng cùng với một bộ công cụ phần mềm mã nguồn mở để thiết kế, xây dựng, l...

Export CSV from AWS RDS - Import into MySQL with Laravel

Export CSV from AWS RDS - Import into MySQL with Laravel

Transfer Database Trong quá trình phát triển và bảo trì dự án, nhiệm vụ di chuyển cơ sở dữ liệu từ hệ thống này sang hệ thống khác là một nhiệm vụ khá là phổ biến. Chúng ta thường sẽ sử dụng câu...

Laravel Logging Of Database Queries

Laravel Logging Of Database Queries

Laravel là một Framework PHP mạnh mẽ và linh hoạt, giúp cho việc phát triển ứng dụng trở nên đơn giản và dễ dàng hơn. Một trong những tính năng hữu ích của Laravel là khả năng ghi nhật ký truy vấn...

Cloudflare's Turnstile CAPTCHA in Laravel

Cloudflare's Turnstile CAPTCHA in Laravel

Ngày 28/09/2022, Cloudflare đã thông báo về phiên bản beta mở của Turnstile, một giải pháp thay thế vô hình cho CAPTCHA. Bất kỳ ai, ở bất kỳ đâu trên Internet muốn thay thế CAPTCHA trên trang web 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 UI Custom Email Password Reset Template

Laravel UI Custom Email Password Reset Template

Nếu bạn đang dùng thư viện laravel/ui để làm các chức năng liên quan đến authentication, và trong dự án của bạn, bạn cần thay đổi template email password reset thay vì sử dụng template email password...

ManhDanBlogs