Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

insight's avatar

How to implement pdf validation for maximum number of pages in upload ?

Dear Friends, I have a form in Laravel 10 with one field as PDF , I need to restrict the number of pages in uploaded pdf . I am using DOM PDF for pdf generation. I tried to use in validator as

'quali_upload.*' => 'required|file|mimes:pdf|max:2048|max_pages:3',

but got exception as

{
    "message": "Method Illuminate\Validation\Validator::validateMaxPages does not exist.",
    "exception": "BadMethodCallException",

I tried many solution with app/rules (added max_pages.php)

<?php

namespace App\Rules;

use Illuminate\Validation\Rule;
use Barryvdh\DomPDF\Facade as Dompdf;
use PDF;

class MaxPages extends Rule
{
    public function __construct(protected int $max)
    {
    }

    public function passes($attribute, $value, array $parameters, $validator)
    {
        if (!$value instanceof \Illuminate\Http\UploadedFile) {
            // If the value is not an UploadedFile instance, the validation fails.
            return false;
        }
    
        // Get the temporary path of the uploaded file.
        $filePath = $value->getRealPath();
    
        // Make sure you have installed Dompdf via Composer before using this code.
        // composer require dompdf/dompdf
    
        // Create a new Dompdf instance
        $dompdf = PDF::loadHtml(file_get_contents($filePath));
    
        // Load the PDF file
       // $dompdf->loadHtml(file_get_contents($filePath));
    
        // Set the paper size and rendering options (adjust these as needed)
        $dompdf->setPaper('A4', 'portrait');
    
        // Render the PDF to count the number of pages
        $dompdf->render();
    
        // Get the number of pages in the PDF
        $pageCount = $dompdf->getCanvas()->get_page_count();
    
        // Return true if the page count is less than or equal to the allowed maximum pages.
        return $pageCount <= $parameters[0];
    }
    
    

    public function message()
    {
        return 'The maximum number of pages is :max';
    }
}


in config/app.php added line as

 'customValidationRules' => [
        'max_pages' => 'App\Rules\MaxPages',
    ],

But still the above exception.

Please advise a solution which work ..

Thanks

Anes P A

0 likes
4 replies
insight's avatar

Dear Friends, I tried many ways . But now get Exception as


    "message": "Object of class App\Rules\MaxPages could not be converted to string",
    "exception": "Error",
    "file": "C:\xampp\htdocs\ksit_mission\vendor\laravel\framework\src\Illuminate\Validation\ValidationRuleParser.php",
    "line": 134,

my AppServiceProvider class is

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use Smalot\PdfParser\Parser;
use App\Rules\MaxPages;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // $this->app['validator']->extend('max_pages', function ($attribute, $value, $parameters, $validator) {
        //     $maxPages = $parameters[0];
        //     $rule = new MaxPages($maxPages);
        //     return $rule->passes($attribute, $value);
        // });
        Validator::extend('max_pages', function ($attribute, $value, $parameters, $validator) {
            if (!is_array($value)) {
                return false;
            }

            $maxPages = $parameters[0];

            foreach ($value as $file) {
                if (!$file->isValid()) {
                    return false;
                }

                $pdf = (new Parser())->parseFile($file->path());
                $numPages = count($pdf->getPages());
                if ($numPages > $maxPages) {
                    return false;
                }
            }

            return true;
        });

    }
}

  1. MaxPages.php in app/Rules
<?php

namespace App\Rules;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Smalot\PdfParser\Parser;

class MaxPages extends Rule
{
    protected $maxPages;
    

    public function __construct($maxPages)
    {
        $this->maxPages = $maxPages;
    }


   
    public function passes($attribute, $value)
    {
        if (!is_array($value)) {
            return false;
            
        }

        foreach ($value as $file) {
            if (!$file->isValid()) {
                return false;
                
            }

            $pdf = (new Parser())->parseFile($file->path());
            $numPages = count($pdf->getPages());

            if ($numPages > $this->maxPages) {
                return false;
            }
        }

        return true;
    }

    public function message()
    {
        return "The :attribute must have a maximum of {$this->maxPages} pages.";
    }

    
}

call it in 6 places in controller as

'quali_upload.*' => ['required', 'file', 'mimes:pdf', 'max:2048', new MaxPages(3)],  // 2 times called
'upload_additional.*' => ['nullable','file','mimes:pdf','max:2048',new MaxPages(2)], // 2 times called
'uploadworkexperience.*' => ['nullable','mimes:pdf','max:2048',new MaxPages(1)],  // 2 times clalled 

with included in controller

use App\Rules\MaxPages;

Please help

Thanks

Anes P A

Please or to participate in this conversation.