Download a PDF file instead of displaying it with CodeIgniter - php

I am generating PDF file using CodeIgniter and R&OS pdf class.
But now the problem is that the pdf is displayed to the browser.
I instead want it to be downloaded.
Here is my code :
$this->load->library('cezpdf');
$data['users'] = $this->user->get_all_ayant_droits();
foreach($data['users'] as $user) {
$db_data[] = array('name' => $user->nom, 'department' => $user->Department, 'status' => $user->Status);
}
$col_names = array(
'name' => 'Noms et Prenoms',
'department' => 'Département',
'status' => 'Status'
);
$this->cezpdf->ezTable($db_data, $col_names, 'Ayant droit Base Loisirs de Kribi', array('width'=>550));
$this->cezpdf->ezStream();
What is missing for this controller to send the file to download ?

You can pass the argument to the function ezStream
$this->cezpdf->ezStream(array $options);
$options 'compress' => 0/1 to enable compression. For compression level please use $this->options['compression'] = at the very first point. Default: 1
'download' => 0/1 to display inline (in browser) or as download. Default: 0

You can use Download Helper https://ellislab.com/codeigniter/user-guide/helpers/download_helper.html?
$this->load->helper('download');
$data = $this->cezpdf->ezStream();
force_download("PDF_filename.pdf", $data);
You can also use ouput variable by setting proper header value.
$this->output->set_header('Content-Disposition: attachment; filename="PDF_filename.pdf"');
$this->output->set_content_type('application/pdf')
->set_output($this->cezpdf->ezStream());
here by setting content type to appication/pdf so browser identify content is pdf and Content-Disposition: attachment force to download the file.
Hope this helps. Sorry for poor English.

Related

How to open the PDF generated in new tab

I have a Leave application project that generates a PDF file.
this is the code that generates the pdf after I click submit.
$id = DB::table('leave')->where('user_id', auth()->user()->id)->max('id');
$data = leave::where('id', $id)->select('*')->get();
$filename = auth()->user()->name." - S - ". "LEAVE - ".$randomString->randomString(8)."-".$request->filing_date.".pdf";
$path = storage_path('app/leave_file/'.$filename);
PDF::loadView('pdf_views.leave_pdf', $data[0])->setPaper('legal')->save($path);
if(file_exists($path)){
DB::table('leave_files')->insert([
'filename' => $filename,
'leave_id' => DB::table('leave')->where('user_id', auth()->user()->id)->max('id'),
]);
}
return redirect()->route('leave')->with('success', "success");
I wonder if I can make the newly generated pdf open in the new tab after I click submit on my leave application. thank you to anyone who can help
According to the Laravel docs this is what you need: https://laravel.com/docs/9.x/responses#file-responses
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Use the Cache Facade, to store the generated pdf temporary.
$uuid = Str::uuid();
return response()->stream(function () use ($uuid) {
echo Cache::remember($uuid, 300, function() {
return 'genertated pdf content'
});
}, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename=%s;', $uuid),
]);
Create a route to access to cached file. Name the route.
Now you can open it in a new tab from you frontend e.g. Generate the route with route('routename', ['param' => 123]) and pass it to your FE with a REST endpoint for example.
window.open(url,'_blank');

Pdf export freeze when i try to export it

So i'm trying to implement a PDF export. I installed dompdf with composer, i put "'PDF' => Barryvdh\DomPDF\Facade::class" in aliases and "Barryvdh\DomPDF\ServiceProvider::class" in providers in config/app.php. On my route i have this code:
\Illuminate\Support\Facades\Route::get('/users/{userId}/details/{forReport}/exportPDF', function($userId) {
$user = UserHelper::getUser($userId);
$internal_devices = UserHelper::getUsersAssignedInternalDevices($userId);
$external_devices = UserHelper::getUsersAssignedExternalDevices($userId);
$licenses = UserHelper::getUsersAssignedLicenses($userId);
$delegation_devices = UserHelper::getUsersDevicesOnDelegation($userId);
$pdf = PDF::loadView(URLHelper::userReportView(),
[
'user' => $user,
'internal_devices' => $internal_devices,
'external_devices' => $external_devices,
'licenses' => $licenses,
'delegation_devices' => $delegation_devices,
]);
return $pdf->download('My.pdf');
})->name('admin.exportPDF');
When i call this route, i get execution time-out and i have 300 seconds. In conclusion, PDF is not generated. Is something wrong with my code?
PS: i did a var_damp and everything looks alright

Maps image download error, routes are not coming in the image

I created a function in PHP that downloads a map created in google maps, I am able to download, however, the route is not coming when I am saving.
How the picture is coming:
How it should come:
Code:
function download_remote_file_with_curl($file_url, $save_to) {
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$response = file_get_contents($file_url, false, stream_context_create($arrContextOptions));
//echo $response;
//file_put_contents($save_to, $response);
$downloaded_file = fopen($save_to, 'wb');
fwrite($downloaded_file, $response);
fclose($downloaded_file);
}
$urlDownload = "https://maps.googleapis.com/maps/api/staticmap?size=1000x1000&maptype=roadmap&path=enc:zklaAbqcyJzCmF~#b#fBdAzCiEnKyQlFpCnMdH~_#nU~JlFlCNrw#oL~IcApEZxd#nQpgBhq#tRtStgA``Aty#`o#ll#pa#tNhFzMvJfG~D|Y~Hxd#rMll#`Rtb#jLjNzExWtFz`#bJvM|ItG`LdF|V`GvD|CL|JiBv]aGld#cHrk#cLdU_Fpb#wGdMg#vaAqAti#g#z_#Cj~A{#raAfDlp#xAfYa#tyAuDtVEbTdApO`#rGk#dP`#vgEo#baCuA`|AaArHGIzAwCtHqDlNf#rl#lA~bAnAphAMj`#hBlj#\hd#s#tL\pHnCff#~A`|#lMnmEnBbKrFbDn`#jP~RtQ~k#hVhNtGb#xFgPheAsAnOuIlaBpj#|qCtDzGb`A~`AzDvGd#vI{Af_#x#~GxItHzLvGp\fLxc#t\pe#d`#h|AnmA`WvQnEDnF}Bd\uUjGeB~Gb#nEvB~KnMri#ni#fjCbfCpmArkAv|#pz#bjAjhApcEt}Ddx#pv#r_#lZzyB|hBtoHneGzZvVh|#xq#fb#jZh^fZjD~E`FlOzMbc#|L|`#hQrS~H`MhQ~w#hEdzB~B~hAbAbk#Ux^kNx~BeGriAaCbe#|#zSt#`ChDnBnZlAlFtCl`#`AzMpBpRvJlKvFbKlLxd#pcAdk#~oAjbAbiAnPxLfq#b^ndDpkBbdDfjBbqAdt#hFjAtNhCfMbD|g#tYhxDfxBrqFx~C|CpCzA|EE~E}i#raDsOb}#uO~{#{f#zvCr#hG~CdDf`Bly#hL|Lt#bClD|Brx#naAvAnAzb#lg#zj#veDjMbI|rBhdAlJzFdAjCbBpgBpMlsQdIhhO]p^?hb#z#dsAp#jo#l#pWffDp`FzyB~eDxdEhlGpNrSvv#hn#duEvuDnsJp~HtpLvvJ~bBtvAjw#hp#hDnFnHvpBlSh}FrFd_BvAno#tu#buTtPxwEnXvhJbRddGbQ~nGlNjqFlJv~BvC~rAdFppBvNhvEhShsGw#nQ}i#htBsq#lgCcJd]}BjPkG|y#gPptBu]byE_H~gArB`EfG|FxXnYfv#nv#nWhX`RjRjHj`#bfBdgKlCrKzGhQp`#lbAtdBnjEr_#z`A`~#n}Bth#fuAdpDzdJ|W`o#`ClAxIj#beA~A~p#bAx|F~I`lEzGvwAbCdMx#neDjlAbp#hUrE}#prB_qCzBaAjJAxOKhWfAfP?tm#}Q~{Bkr#r{EeyAxPoApfB~WzK|AHTdBDrO}A~RmBrXsCzZuA~NJx#bD|#dAfX`#{#nG&markers=color:green|label:A|-10.8819552,-61.95483539999998&markers=color:red|label:B|-12.457280801085,-64.2310285267651&key=yourkey";
download_remote_file_with_curl($urlDownload, realpath('C:/test') . '/' . 'test' . '.jpg');
?>
Thank you!
I don't know if what I'm about to write makes sense, but the route that you want to download is an item that appears once it's selected.
For example when the "SKIP" buttom in Youtube appears to quit an advertisement, it creates an instance of that box in HTML, and then it dissappears when Add is over.
I think that the route is this kind of instance and you must add a line of code to also take that piece of html

Zend File Transfer: Problem when uploading a single image

I cannot understand how ->isuploaded() works. I am suppose to upload six images to display on my index page. Now the problem is, in my update function, if I upload only one or two image $upload->isUploaded() returns a false value, but if I decide to update all six of them it returns a true value. How do I deal with this problem? Am i missing out something here?
Here is my zend file transfer upload
$upload = new Zend_File_Transfer();
$upload->addValidator('Count', false, array('min' =>1, 'max' => 6))
->addValidator('Size', false, array('max' => '1Mb'))
->addValidator('ImageSize', false, array('minwidth' => 50,
'maxwidth' => 1000,
'minheight' => 50,
'maxheight' => 1000));
if ($upload->isUploaded()) $hasImage = true;
By default Zend guess all uploaded files are invalid even if just one of submitted form file fields was empty.
Zend docs are suggest to override this behavior by calling isValid() method before receive().
So I'm not sure if suggest best solution, but it works for me:
$upload = new Zend_File_Transfer();
$upload->setDestination( 'some your destination' );
if( $adapter->isValid( 'your form file field name' ) ){
$adapter->receive( 'your form file field name' );
}
And so on with every file field name. Wrap in foreach if needed.
Use isValid() instead.
if ($upload->isValid()) {
// success!
} else {
// failure!
}
Once you know your upload passed the validators, then start processing the images.

Uploaded docx files turning into zip

I am currently using symfony 1.4 and would like to allow users to upload Microsoft Word docx files. Using the sfWidgetFormInputFile widget and sfValidatorFile below users are able to select and successfully upload their docx files using a simple web form.
$this->widgetSchema['file_name'] = new sfWidgetFormInputFile(array('label' => 'File'));
$this->validatorSchema['file_name'] = new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_dir_file_sharing').DIRECTORY_SEPARATOR,
'mime_types' => array('application/msword',
'application/vnd.ms-word',
'application/msword',
'application/msword; charset=binary')
), array(
'invalid' => 'Invalid file.',
'required' => 'Select a file to upload.',
'mime_types' => 'The file must be a supported type.'
));
The problem is that after the file is uploaded, the extension is changed to .zip and the file contains a file tree of xml files. My understanding is that this is because Office 2007 are now using Open xml file formats. Is there any way to prevent this from happening using symfony or PHP?
The problem is Content-Sniffing. The new Office formats ARE .zip files, and if on upload, the content is sniffed, the browser will identify this as a ZIP file and set the Content-Type header as such. Similarly, on download unless your server sets the proper Content-Type HTTP response header, the browser will assume that this is a ZIP file.
Symfony 1.3+ has an option mime_type_guessers for sfValidatorFile which allows you to define your own mime type guesser PHP callable or use a build in guesser. Calling any of the 3 built-in mime type guessers finds the correct file type for docx and keeps the the docx file extension.
Here is the updated code using guessFromFileinfo:
$this->validatorSchema['file_name'] = new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_dir_file_sharing').DIRECTORY_SEPARATOR,
'mime_type_guessers' => array('guessFromFileinfo'),
'mime_types' => array('application/msword',
'application/vnd.ms-word',
'application/msword',
'application/msword; charset=binary')
), array(
'invalid' => 'Invalid file.',
'required' => 'Select a file to upload.',
'mime_types' => 'The file must be a supported type.'
));
It seems to be a bug in Symfony's file type detection. A workaround is described.
The suggested use of mime_type_guessers uses a non-existing function.
If you want to use the sfValidatorFile method, you should write array(array('sfValidatorFile', 'guessFromFileinfo')).
The suggested solution uses no mime-type detection at all and results in problems with the classic excel format on my system.
I fixed the problem by extending the sfValidatorFile class and changing the getMimeType method.
Create a new msValidatorFile.class.php file in your lib folder :
<?php
class msValidatorFile extends sfValidatorFile
{
protected function getMimeType($file, $fallback)
{
$arrayZips = array( "application/zip",
"application/x-zip",
"application/x-zip-compressed");
$officeTypes = array(
"application/vnd.ms-word.document.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"application/vnd.ms-powerpoint.template.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.template",
"application/vnd.ms-powerpoint.addin.macroEnabled.12",
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"application/vnd.ms-powerpoint.presentation.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.ms-excel.addin.macroEnabled.12",
"application/vnd.ms-excel.sheet.binary.macroEnabled.12",
"application/vnd.ms-excel.sheet.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel.template.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.spreadsheetml.template");
foreach ($this->getOption('mime_type_guessers') as $method)
{
$type = call_user_func($method, $file);
if (null !== $type && $type !== false)
{
if (in_array($type, $arrayZips) && in_array($fallback, $officeTypes))
{
return $fallback;
}
return strtolower($type);
}
}
return strtolower($fallback);
}
}
Use this new validator in your form code :
$this->validatorSchema['file'] =
new msValidatorFile(array('required' => false,
'path' => sfConfig::get('sf_upload_dir')
));

Categories