Attempted to load class "Mpdf" from namespace "Mpdf" - php

I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
So I've done the following :
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
class DevisGenerator
{
public function runDevis()
{
$spreadsheet = $this->loadexcelTemplate();
$uuid = $this->uniqidReal();
$filename = $this->writeName($spreadsheet, $uuid);
$this->convertPdf($spreadsheet, $filename);
}
public function writeName($spreadsheet, $uuid)
{
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('B2')->setValue('Toto');
try {
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$filename = $uuid;
$writer->save($filename.'.xlsx');
}catch (Exception $e)
{
//TODO gestion erreur
}
return $filename;
}
public function convertPdf($spreadsheet, $filename)
{
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
$writer->save($filename.'.pdf');
}
But whan I run the code the following error appear :
Attempted to load class "Mpdf" from namespace "Mpdf".
Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?
I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

I've already got a similar issue with Mpdf.
PHPSpreadsheet supports multiple Librairies to generate PDF.
I'm nut using Mpdf but Tcpdf.
I'm also not sure but you need to install them manually.
composer require tecnickcom/tcpdf
Then in your code :
$writer = new Tcpdf($spreadsheet);
And don't forget the use statement ;)
Hope this help !

After use statement before class, you should use only:
public function convertPdf($spreadsheet, $filename)
{
$writer = new Mpdf($spreadsheet);
$writer->save($filename.'.pdf');
}

Since you use the fully qualified namespace when creating the instance, the use statement is not taken into account (thus the error message).
It seems like you have added a supplementary slash at the beginning of the namespace when creating your Mpdf instance, removing it will solve your issue.
$writer = new PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
But since you have added a use statement, you do not need to use the fully qualified namespace again, you can do
$writer = new Mpdf($spreadsheet);

Related

Unable to extract the content of pdf file in php

Currently working on validating the pdf file. I have used PHP pdfparser in Laravel to extract the file. But some files are unable to extract. I come up with the solution to downgrade the pdf file to resolve the issue but still not working for me.
I tried to downgrade the pdf file from version 1.7 to 1.4 but it's not allowing me to do so.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Smalot\PdfParser\Parser;
use Xthiago\PDFVersionConverter\Guesser\RegexGuesser;
use Symfony\Component\Filesystem\Filesystem;
use Xthiago\PDFVersionConverter\Converter\GhostscriptConverterCommand;
use Xthiago\PDFVersionConverter\Converter\GhostscriptConverter;
class ApiController extends Controller {
public function varifyDocument(Request $request, Parser $parser) {
$request = $request->file();
$file = $request['file'];
//Get the version of the pdf file.
$guesser = new RegexGuesser();
$version = $guesser->guess($file);
//If pdf version is 1.7 then convert it to 1.4.
if($version == "1.7") {
$command = new GhostscriptConverterCommand();
$filesystem = new Filesystem();
$converter = new GhostscriptConverter($command, $filesystem);
$converter->convert($file, '1.4');
}
$pdf = $parser->parseFile($file);
$pages = $pdf->getPages();
foreach ($pages as $page) {
echo $page->getText();
}
}
}
I need to read the content of the pdf file and identify it has any vulnerability or not.

How do i use Php Spreadsheet with Fat free to read and edit an excel file?

I need to edit a excel file in php. I've got a simple PHP Spreadsheet.
I use fat-free and the problem is
public function MakeExcel()
{
require 'vendor/autoload.php';
use \vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet ;
use \vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx ;
$Spreadsheet = new Spreadsheet();
$sheet = $Spreadsheet->getActiveSheet();
$sheet->setCellValue('A3', 'toto');
$writer = new Xlsx($Spreadsheet);
$writer->save("test.xlsx");
$f3->set('CONTENT','views/dashboard/dashboard_liste.html');
$f3->set('CONTENTJS','views/dashboard/dashboard_liste.js');
echo \Template::instance()->render('views/accueil/accueil.html','text/html');
$this->db = null;
}
use doesn't seem to exist in fat-free so i tried:
$f3->use(\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet);
Or
$f3->use("\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet");
and many other it return me the error :
ERROR 500 Call to a member function use() on null
Problem Solved thanks everyone :
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class MakeExcel extends Controller {
public function MakeExcel(){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
}
}
First of all seems you use Fat Free wrong. Because $f3 is null.
Second. Probably you are importing classes with wrong namespaces. You can read documentation of PhpSpreadsheet.
Right way:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
You can phisically find this classes and look on the namespace.
Put your import of composer autoload and use block outside of this function.
Make sure you ran composet install
Make your function work without PhpSpreadsheet. And after that try to add other functionality
You need to declare those files in php top area
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
Then in method create object for spreadsheet
$spreadsheet = new Spreadsheet();
Then you can define the border and alignment for xls file like that
$cell_st =[
'font' =>['bold' => true],
'alignment' =>['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER],
'borders'=>['bottom' =>['style'=> \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN],'top' =>['style'=> \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
];
To Define the Header you can use below code
$spreadsheet->setActiveSheetIndex(0)->mergeCells('A2:D2');
$spreadsheet->setActiveSheetIndex(0)->setCellValue('A2', "<YOUR HEADER>");
$spreadsheet->getActiveSheet()->getStyle('A2:D2')->applyFromArray($cell_st);
And Then define the column names
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A3', 'ID')
->setCellValue('B3', 'NAME')
->setCellValue('C3', 'CITY')
->setCellValue('D3', 'SALARY');
After all above code now you can start your content in loop like that
$rowcount = 4;
foreach($data_array as $key=>$value){
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A'.$rowcount, $value['id'])
->setCellValue('B'.$rowcount, $value['name'])
->setCellValue('C'.$rowcount, $value['city'])
->setCellValue('D'.$rowcount, $value['salary']);
$rowcount++;
}
and in last now make object of the Xlsx class to save the excel file
$writer = new Xlsx($spreadsheet);
$file_name = "report.xls';
$file_root_path = "assets/reports/xls/".$file_name;
$file_site_path = "localhost/xls_generate/assets/reports/xls/".$file_name;
$writer->save($file_root_path);
// final xls file path is here
echo $file_site_path;
That's all, Hope this work for you..

Unable to convert an excel to pdf using php

I have installed PhpSpreadsheet and dompdf successfully using composer.
My requirement is that I need to convert an excel sheet into pdf, I got it working using the default settings, this is the code I have used.
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf;
$spreadsheet = new Spreadsheet();
try {
$sheet = $spreadsheet->getActiveSheet();
// code to fill in the data
$spreadsheet->getActiveSheet()->fromArray(
$data, // The data to set
NULL, // Array values with this value will not be set
'A2' // Top left coordinate of the worksheet range where
);
} catch (Exception $e) {
}
$writer = new Xlsx($spreadsheet);
try {
IOFactory::registerWriter("PDF", Dompdf::class);
$pdfwriter = IOFactory::createWriter($spreadsheet, 'PDF');
$pdfwriter->save($filepath . 'pdf_test.pdf');
} catch (\PhpOffice\PhpSpreadsheet\Writer\Exception $e) {
}
I have skipped out code for brevity, this code works fine and generates a pdf file, I require the pdf to be printed in landscape mode, for that the docs mention a Custom implementation or configuration of the pdf library, so I created a file called PDFBase_DOMPDF that looks like this
use Dompdf\Dompdf;
class PDFBase_DOMPDF extends Dompdf
{
}
And I have created a file called PDFBase_Writer that looks like this.
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf;
class PDFBase_Writer extends Dompdf
{
protected function createExternalWriterInstance()
{
$instance = new PDFBase_DOMPDF();
$instance->setPaper('A4', 'landscape');
return $instance;
}
}
I modified the original code to use the new pdf class so the line changed to this.
IOFactory::registerWriter("PDF", PDFBase_Writer::class);
The problem is I get an exception with the following error
Registered writers must implement PhpOffice\PhpSpreadsheet\Writer\IWriter
How exactly do I fix this?
Reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of \PhpOffice\PhpSpreadsheet\Reader\IReader and \PhpOffice\PhpSpreadsheet\Writer\IWriter.
You must load the Excel file like this:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load("TestRead.xlsx");
Registered writers must implement PhpOffice\PhpSpreadsheet\Writer\IWriter
PHPSpreadsheet Writer classes must implement all the methods defined in the IWriter interface. You're creating a new Writer, so it needs to provide an implementation of all those methods:
interface IWriter
{
/**
* IWriter constructor.
*
* #param Spreadsheet $spreadsheet
*/
public function __construct(Spreadsheet $spreadsheet);
/**
* Save PhpSpreadsheet to file.
*
* #param string $pFilename Name of the file to save
*
* #throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public function save($pFilename);
}
So your Writer needs to implement a constructor that accepts a Spreadsheet object as an argument, and a save() method that accepts a filename (as a string) argument.

Getting users' email - Laravel 5 PHP

I'm attempting to store the email address of any user who uploads a file into an "uploader_name" string variable. I've attempted using the following code whichout success - attempting to upload the file will result in a Class 'App\Http\Controllers\Auth' not found error message being thrown back. I know this is a pretty basic question, but I can't seem to find any answers which specifically work with Laravel 5.
This is what I'm trying to use currently without success.
$filelist->uploader_name = Auth::user()->email;
If it helps, here's the full function which saves some of the automatic information of the file.
public function store()
{
$filelist = new Filelist($this->request->all());
//store file details - thanks to Jason Day on the unit forum for helping with some of this
$filelist->name = $this->request->file('asset')->getClientOriginalName();
$filelist->file_type = $this->request->file('asset')->getClientOriginalExtension();
$filelist->file_size = filesize($this->request->file('asset'));
$filelist->uploader_name = Auth::user()->email;
$filelist->save();
// Save uploaded file
if ($this->request->hasFile('asset') && $this->request->file('asset')->isValid()) {
$destinationPath = public_path() . '/assets/';
$fileName = $filelist->id . '.' . $this->request->file('asset')->guessClientExtension();
$this->request->file('asset')->move($destinationPath, $fileName);
}
return redirect('filelists');
}
You get not found error, because you don't use the right namespace.
You can resolve this if you use the use keyword like this:
use Auth;
public uploadController {
...
}
Or you can use the full namespace:
$filelist->uploader_name = \Auth::user()->email;
You are getting Class 'App\Http\Controllers\Auth' not found error because you are not using the correct namespace:
There are two ways to resolve this:
By including use keyword in your controller
Example:
use Auth;
UploadController{
....
}
or by specifying the full namespace directly like so
$filelist->uploader_name = \Auth::user()->email;

How can I access my class properties from a namespace with php version 5.5.12?

I'm using WAMPSERVER 2.5 and PHP version 5.5.12 on Windows 8 PC. I created a namespace which worked ok when I was running PHP version 5.2.12. After upgrading to php version 5.5.12 I'm getting error message about undefined variables which I think means that the namespace is not being used. Here's what my code looks like:
In my UploadFile.php file I have this:
<?php
namespace myNamespace;
class UploadFile
{
protected $avatarUrl;
public function getUrl()
{
return $this->avatarUrl;
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
echo $file[$key];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$url='http://westcoastchill.com/dc-esports/images/' . $filename;
$this->avatarUrl=$url;
...
}
.....
?>
Then here's the html form that uses the class in the namespace where I get the error messages that states that the variable 'newUrl' is undefined and the index 'displaymax' is undifined.
<?php
require_once 'uploads/src/myNamespace/UploadFile.php';//<------names here
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']); //<------ undifined index
}
$max = 50 * 1024;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploads/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
$newUrl=$upload->getUrl(); //<----------- here's the undifined newUrl;
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
$oldUrl=$newUrl;
...
?>
}
How can I access my class from a namespace with php version 5.5.12?
Thanks for any help with this!
UPDATE: Sorry I had getUrl() outside of superclass but in my actual project is in the correct place. So I tried:
\myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));...
but I still get the same error. I also tried adding use:
myNamespace\UploadFile and \myNamespace\UploadFile...
still getting the same error message. The thing is my code worked with the using statement before I updated PHP so I'm curious why just an update would change things.
UploadFile class is within the namespace myNamespace, so to reference the class from outside of myNamespace, you would need to use \myNamespace\UploadFile.
If you are already in the global namespace, you don't need the leading slash, but I think it's good practice to always use the leading slash, since the leading slash refers to the global namespace.
Ex:
$_SESSION['postmax'] = \myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));
and
$upload = new \myNamespace\UploadFile($destination);
The issue was the configuration of the php.ini file. After researching more I tried turning off 'display_errors=Off in the php.ini file and the code the code ran using the namespace and everything. Conclusion: the php.ini file of the new installation different settings. I'll explore the settings more but my problem was solved by turning off error displaying. Obviously this is not a desired option so I'll toggle on and off as I go forward and read up on other parameters in the file that may help me.

Categories