Could you point how to correctly configurate the PHP's Library tcPDF at Laravel's  composer.json ?

Eduardo Fuerte
Eduardo Fuerte used Ask the Experts™
on
Hi Experts

Could you point how to correctly configurate the PHP's Library tcPDF at Laravel's  composer.json ?

Actually is configured this way:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.6.0",
        "barryvdh/laravel-debugbar": "^3.1",
        "jailtonsc/validador-cpf-laravel": "^2.0",
        "guzzlehttp/guzzle": "~6.0",
        "league/csv": "^8.0",
        "maatwebsite/excel": "~2.1.0",
        "dompdf/dompdf": "~0.6.1",
        "laravelcollective/html": "5.6.*",
        "doctrine/dbal": "^2.5",
        "mpdf/mpdf": "~6.0.0",
*----- HERE
        "tecnickcom/tcpdf": "~6.0.0",
*----
        "laravel/passport": "~5.0.0",
        "intervention/image": "^2.3",
        "league/flysystem": "^1.0",
        "graham-campbell/flysystem": "^5.0",
        "barryvdh/laravel-cors": "^0.11.0",
        "laravel/tinker": "^1.0",
        "graham-campbell/manager": "^4.0",
        "league/flysystem-azure-blob-storage": "^0.1.2",
        "phpoffice/phpspreadsheet": "^1.3",
        "jailtonsc/validador-cnpj-laravel": "^1.0",
        "geekcom/validator-docs": "^1.3",
        "spatie/laravel-analytics": "^3.6"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~6.0",
        "symfony/css-selector": "3.1.*",
        "symfony/dom-crawler": "3.1.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }

Open in new window


 And produces this error:
img009
I had tryed with no success this:

 "tecnickcom/tcpdf": "^6.2.13"

Open in new window


Any suggestions?

Thanks in advance
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David FavorFractional CTO
Distinguished Expert 2018

Commented:
The error above suggests you haven't installed the php-tcpdf module yet, or you haven't enabled the tcpdf module in your PHP config.

Ensure you've installed + correctly configured to address the error above.

There may be other errors after you resolve the install + config problem.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi

After running composer update I had:

img001
What do you exactly means with PHP config?

I guess it's PHP.INI configuration, ok?

If so, no other library used by Laravel   (as script above) is configured there.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
This likely has no relation to composer.

The error above suggests the actual code for this module isn't installed, so nothing you'll ever do with composer will install an OS level software package.

You must install the module code first, as in...

1) ssh into machine/container as root.

2) Install the package, for example, on Debian/Ubuntu...

apt-get install php-tcpdf

Open in new window


3) Now reload PHP, for example, using FPM on Debian/Ubuntu...

service php7.4-fpm reload

Open in new window

Eduardo FuerteDeveloper and Analyst

Author

Commented:
The purpose of composer.json (inside Laravel's project) is to relate all the packages that need instalation, isn't it?

So, when running composer update  "tecnickcom/tcpdf": "^6.2.13"  would be automatic installed at vendors' folder (with the others).

No needs of external (SO) instalattions...

When I started my Laravel project I had no installed packages, after running that command, everything is installed and running, with the exception of tcPDF.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Reading the tcPDF docs, you're correct this should work. I was thinking about libPDF, which requires a different installation approach.

You should simply be able to do this now...

composer install

composer update

Open in new window


So this suggests your .json file might not be being picked up.

If you're running Linux, you can run the following on your top level directory to see all file accesses, during your install + update command.

inotifywait -mrq /path-to-your-project

Open in new window


Start with this to determine if the correct .json file is being picked up.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Just tested this...

lxd: net14-template-bionic # cat composer.json
{
   "require": {
       "tecnickcom/tcpdf": "^6.2.13"
   }
}

lxd: net14-template-bionic # composer install
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing tecnickcom/tcpdf (6.3.2): Downloading (100%)         
Writing lock file
Generating autoload files

lxd: net14-template-bionic # composer update
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

Open in new window


Seems to work for me.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
lxd: net14-template-bionic # cat test.php
<?php
// Load autoloader (using Composer)
require __DIR__ . '/vendor/autoload.php';
$pdf = new TCPDF();                 // create TCPDF object with default constructor args
$pdf->AddPage();                    // pretty self-explanatory
$pdf->Write(1, 'Hello world');      // 1 is line height

$pdf->Output('hello_world.pdf');    // send the file inline to the browser (default).

?>

lxd: net14-template-bionic # php test.php | wc -c
7001

Open in new window

Eduardo FuerteDeveloper and Analyst

Author

Commented:
I'm using Win10 and trying to convert the commands here. Thank you for your efforts by now!
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Maybe best to reduce your composer.json file down to only using a hello world example for tcPDF, get that working, then start extending your json.

Also post the output from these steps (as text, not images)...

composer install

composer update

Open in new window


Something's certainly wrong + your json looks correct.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hi Eduardo,

When you installed the maatwebsite/excel package, it sets the default path for the tcPDF package to an older location. This path is set in the config/excel.php config file.

First off, if you can't see the excel.php config file in your config folder, you'll need to publish it:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

Once you've done that, open up the config/excel.php config file and scroll down until you see a 'pdf' section. Within that, you get to set the Driver (tcPDF for example). Underneath that you will see a section called 'drivers'. You will see a driver for tcPDF that looks like this:

'tcPDF'  => [
    'path' => base_path('vendor/tecnick.com/tcpdf/')
],

That path is now wrong. If you look in your vendor folder, you'll see that there is no dot in the path, so you need to change that driver setting to the following:

'tcPDF'  => [
    'path' => base_path('vendor/tecnickcom/tcpdf/')
],

Now Laravel will look in the correct place for tcPDF.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Following the configurations you suggested and the error is solved.

But unfortunatelly the generated PDF is empty. The excell sheets with the same data are correctly presented.

Could you suggest anything else?


<?php

//---------------------------------------------
    public function exportArquivo($tipo){
//---------------------------------------------
      /*
      1 - Excel
      2 - Csv
      3 - Pdf
      */
     
      switch ($tipo) {
          case 1:
              $extensao='xls';
              break;
          case 2:
              $extensao='csv';
              break;
          case 3:
              $extensao='pdf';
              break;
      }

 
     
      $users = session('admin_participantes');
   
      // generator.
      $usersArray = [];

      // Define the Excel spreadsheet headers
     
      $usersArray[] = ['ID','Login','Nome','E-mail','E-mail Comercial','CPF','CNPJ','GRUPO CNPJ','RG','Data de Nascimento','CEP','Logradouro','Número','Complemento','Bairro','UF','Cidade','Ponto de Referência','Telefone Residencial','Celular','Telefone Comercial','Perfil','Status','CPF Consultor','Consultor','CPF Gerente','Gerente','Tamanho da Revenda','Tipo da Revenda','Inserido no Sistema em','Atualizado no Sistema Em','Aceitou o regulamento?','Data de Aceite'];

      // Convert each member of the returned collection into an array,
      // and append it to the users array.
      foreach ($users as $user) {
        $usersArray[] = [
          $user->id
        , $user->login
        , $user->name
        , $user->email
        , $user->emailComercial
        , CustomFuncs::formatarCpf($user->cpf)
        , CustomFuncs::formatarCnpj($user->cnpj)
        , CustomFuncs::formatarCnpj($user->cnpj_grupo)
        , $user->rg
        , CustomFuncs::formatarData($user->dataNascimento)
        , $user->cep
        , $user->logradouro
        , $user->numero
        , $user->complemento
        , $user->bairro
        , $user->uf
        , $user->cidade
        , $user->pontoReferencia
        , $user->telefoneResidencial
        , $user->celular
        , $user->telefoneComercial
        , $user->tipoparticipante->nome
        , $user->statusparticipante->nome
        , empty($user->consultor)?"":CustomFuncs::formatarCpf($user->consultor->cpf)
        , empty($user->consultor)?"":$user->consultor->name
        , empty($user->gerente)?"":CustomFuncs::formatarCpf($user->gerente->cpf)
        , empty($user->gerente)?"":$user->gerente->name
        , empty($user->tamanhoRevenda)?"":$user->tamanhoRevenda->identificador."-".$user->tamanhoRevenda->descricao
        , empty($user->hierarquia)?"":$user->hierarquia->nome
        , CustomFuncs::castToDateFormat($user->created_at,'d/m/Y H:i:s')
        , CustomFuncs::castToDateFormat($user->updated_at,'d/m/Y H:i:s')
        , $user->aceiteRegulamento==0 ? "NÃO" : "SIM"
        , CustomFuncs::castToDateFormat($user->dataAceiteRegulamento,'d/m/Y H:i:s')
        ];
      }


      // Generate and return the spreadsheet
      Excel::create('participantes', function($excel) use ($usersArray) {

          // Set the spreadsheet title, creator, and description
          $excel->setTitle('Participantes');
          $excel->setCreator('IPremi')->setCompany('IPremi');
          $excel->setDescription('Lista de Participantes');

          // Build the spreadsheet, passing in the users array
          $excel->sheet('sheet1', function($sheet) use ($usersArray) {
              $sheet->fromArray($usersArray, null, 'A1', false, false);
              $sheet->setOrientation('landscape');
              $sheet->setfitToPage(true);
          });

        })->download($extensao);
    }

 ?>
Eduardo FuerteDeveloper and Analyst

Author

Commented:
And Sorry:

Chris, thank you for your efforts until now.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hi Eduardo,

Just done a quick test and I think your problem now is that your tcPDF is a little old. The version you're using has some bugs in it, so I would suggets you update it.

Edit your composer.json file and change the version of tcPDF from this:

"tecnickcom/tcpdf": "~6.0.0",

to this:

"tecnickcom/tcpdf": "^6.0.0",

Now run composer update and it should fix your problem
Eduardo FuerteDeveloper and Analyst

Author

Commented:
So did I.

 img003
But unfortunatelly  the .PDF is still empty...
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Hmmm. In that case, I'm not sure what's going on. Time to get into some debugging.

First off, make sure you've got debugging and logging turned on in Laravel. Check your log files.

Then I would strip the method back to basics to make sure it's not an issue with your data - something simple like this:

public function exportArquivo($tipo) {
    $users = [
        ['Name'],
        ['Chris'],
        ['Eduardo'],
    ];
    
    Excel::create('Test', function($excel) use ($users) {
        $excel->sheet('sheet1', function($sheet) use ($users) {
            $sheet->fromArray($users, null, 'A1', false, false);
            $sheet->setOrientation('landscape');
            $sheet->setfitToPage(true);
        });
    })->download('pdf');
}

Open in new window

Give that a go and see how you get on.
Hi,

Just to let you know I'm using this repository, this allow to have the script without the need to use Composer
https://php-download.com/search?q=tcpdf

It is usefull if you cannot install or run Composer on your system
In fact Composer just create the folder and add the files for you, so these could be just download...

It is always recommended to use Composer when it is possible.
I'm using Windows too and I have set an old computer with Ubuntu and Install and run Composer copy the result folder into Windows webserver after, it is easier to create package using Linux.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Might be useful to start with a simple "Hello World" script first.

This will tell you your composer files + tcPDF installation is all working correctly.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi

By following Chris suggestion it perfectly runs:

img004
So the problem is not with tcPDF, probably is with the data obtained to be printed...
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Yep - sounds about right.

Now start building up your data piece by piece until it breaks. Start with just writing out your column names. It may be some of the non-latin characters are causing a problem.
Hi,

When generating a PDF keep the less CSS as possible, like the old time.
To have a little bit more option I'm using html2pdf  which is based on TCPDF
https://github.com/spipu/html2pdf 
output method
https://github.com/spipu/html2pdf/blob/master/doc/output.md

Make sure the code is valid and follow the PDF code syntax because it won't generate the PDF at all or not correctly.
Also some other script like Javascript may cause issue too

What I do is on click of a button call the page I want to generate
(I place all code on that page, no include and very few css class directly on the page (no fancy thing, no google fonts ect)
I'm not using any other JS script only PHP and HTML and load the data.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Lenamtl

The use of tcPDF is a company's project need, so I couldn't change it by myself, only to suggest, if really needed.

The content to be presented at this PDF is plain text, Excel sheets, using the same package are correctly generated.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
tcPDF should be fine. You're just outputting an Excel file, so no need to worry about HTML / CSS etc.

And because you're using Laravel Excel, you have to use one of the 3 PDF libraries they specify - tcPDF, domPDF or mPDF
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Thank you for the guidance.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial