How to Use PdfCrowd Api In codeigniter? - codeigniter

Hello Iam Using pdfCrowd Api to convert to pdf. If i use convertfile To specify view it says path is not not valid? How to Pass view to pdfCrowd's Convertfile Function?
function download() { require('pdfcrowd.php'); $user_id=$this->session->userdata('user_id'); $data = array(); $data['result']=$this->user_data_model->getcertificate($user_id); try { // create an API client instance $client = new Pdfcrowd('username','api');
// convert a web page and store the generated PDF into a $pdf variable $pdf = $client->convertFile('certificate_template'); // set HTTP response headers header("Content-Type: application/pdf"); header("Cache-Control: max-age=0"); header("Accept-Ranges:
none"); header("Content-Disposition: attachment; filename=\"google_com.pdf\""); // send the generated PDF echo $pdf; } catch(PdfcrowdException $why) { echo "Pdfcrowd Error: " . $why; } }
function download() {
require('pdfcrowd.php');
$user_id=$this->session->userdata('user_id');
$data = array();
$data['result']=$this->user_data_model->getcertificate($user_id);
try
{
// create an API client instance
$client = new Pdfcrowd('username','api');
// convert a web page and store the generated PDF into a $pdf variable
$pdf = $client->convertFile('certificate_template');
// set HTTP response headers
header("Content-Type: application/pdf");
header("Cache-Control: max-age=0");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"google_com.pdf\"");
// send the generated PDF
echo $pdf;
}
catch(PdfcrowdException $why)
{
echo "Pdfcrowd Error: " . $why;
}
}

convertFile method accepts local HTML file only, it can't be template.
You have 2 options:
use convertURI with your rendered template instead convertFile
or
render your template to temporary local HTML file and use it in convertFile method

Related

The file doesn't exist laravel

public function readPDF($file_id)
{
$file_id = SiteHelpers::encrypt_decrypt($file_id, 'd');
$file_details = $this->model->getFileDetails($file_id);
if($file_details){
$file = Storage::url('app/public/course/'.$file_details->course_id.'/'.$file_details->file_name.'.'.$file_details->file_extension);
print_r($file);
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename=document.pdf');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// #readfile($file);
return response()->file($file);
}
}
I have this function to display uploaded pdf file. I removed the former #readfile($file); as it does nothing and displays nothing. I did troubleshoot on my file path ($file) and the resulted url displayed pdf. But when I used latter function return response()->file($file); it displayed error that file doesn't exist but my $file string is correct. Could someone help me with that?

Displaying a BLOB file(An Image) gotten from a guzzle request

I was successfully able to get an image(which is stored as a BLOB file) from an API endpoint in guzzle, but I am having issues displaying this BLOB file as an image
I have tried several PHP functions for manipulating and converting a BLOB file to an image but all has been abortive.
after sending the request to my guzzle trait, I decided to var_dump the result to be sure that it was successful
$userid = $_COOKIE['id'];
$url = 'users/image/'.$userid;
$requestResult = $this->sendGetWithHeader('users/image/'.$userid);
$result = $requestResult->getBody()->read(1024);
//$res = file_get_contents($result);
// fopen($result, 0);
var_dump($result);
echo "<hr>";
var_dump($requestResult);
// $code = $requestResult->getStatusCode();
// var_dump($code);
My expected result is an image file but the actual is still the raw BLOB file gotten from my Guzzle request
string(1024) "����JFIF���        ��V�"��6 ���UG_ks1��r�[�% ��JMd�CL,��8�Q�B�yoA��g�p�-�a�f� D �)8#�.)ɠ� �yea#4��ԃ(��t��Ew��մPV'J��R��u������Ju��U ��ԥ��zѩaė��ya$�2�C�Sa�R$�4� ���� 2t��$��L�D���R�$�ґ-&RVdm��IDq)Jc�"'9�;/ �sb{��Z�r�̮��Q_MR=5�Gt���ddA�6�Fa�L���JGi�kh�d�FA�%(�$� �����.�� H�)��-BL������h|#���WW)݋r�"V[V2˚:��j��˩�>��-$��I�Y�#%dRL(K�(�-�m�I�t��R�JV#�I&JR��0����O2��d�-e#5�2}�2�D'��,Bע��{��!�k�Uw�2ʶ�]cAD�WPw���$��!�Ғu�X!��(�D%I0i�����Lye XI9) �[Nc����#!�miY,Rkiq(���$����mƬ��y��a����崔͒�t7"����͌ΊJgk Q��Ah�Iq$���ʍA�FmJ���7��AJ�a/�rB�"02A����#�d��J%D� �P�yH���m\ż>�i$��I�(�3jm�542k,��t#��#��#D�F�TJDP" �Z(��7�IZ���h9)$��$�Ԣ�Y� m�D�I�֐4�����Da�%DX�o ���fhh�.�c��aQhcΉ�٠��)��"
Save your blob response to a file as follows
$stream = \GuzzleHttp\Psr7\Utils::streamFor($requestResult->getBody());
file_put_contents('path/to/file.extension',$stream->getContents())
See Convert blog image to file
Look at this example - https://github.com/andriichuk/php-curl-cookbook#download-file
Use 'sink' option to save file from request:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$imageFilePath = __DIR__ . '/resource/image.jpeg';
$imageFileResource = fopen($imageFilePath, 'w+');
$httpClient = new Client();
$response = $httpClient->get(
'https://httpbin.org/image/jpeg',
[
RequestOptions::SINK => $imageFileResource,
]
);
if ($response->getStatusCode() === 200) {
echo 'The image has been successfully downloaded: ' . $imageFilePath;
}

Return Image as http-response from Listener Symfony2

This listener sends me reports on all kinds of exceptions that occur on the website. Sometimes I get reports of images that have been deleted but are still consulted by search engines and others.
I want to do, instead of displaying an error message " 404 Not Found " return the correct image. To do this I created a database table that stores the old links and new links of the images that have been deleted, moved or changed its name.
then, this listener find in db the links to fallen and gets the new links of images . The goal is to return the image as http-response with header content-type as image.
My code is:
class ExceptionListener
{
private $service_container;
private $router;
function __construct(Container $service_container, $router){
$this->service_container = $service_container;
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event){
$exception = $event->getException();
$request = $this->service_container->get('request');
...
$document_root = $request->server->get('DOCUMENT_ROOT');
$filename = realpath($document_root . '/'. '/path/to/new_image.jpg');
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-type', 'image/jpeg');
$response->headers->set('Content-Disposition', 'inline; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
...
}
}
The following error occurs:
In the browser you can see a small box , it is as if trying to show the image but the image source could not be obtained . But if the same code is testing on controller , its working properly and the image is displayed .
What can I do to return image from a listener ? thanks
There's few things wrong about the code snippet from your question.
Firstly, you should never use the request service. It's deprecated since Symfony 2.4 and was removed in Symfony 3.0. Use the request stack (request_stack) instead.
Secondly, do not send the response yourself, but let the framework do it. Symfony events system is designed for flexibility (see the docs). In your case it's enough to set the response on the event object.
Finally, you don't need the service container to access the request at all, as it's available on the event.
Moreover, instead of the standard Response class you can use the BinaryFileResponse. It's purpose is to serve files (have a look at the docs).
You can greatly simplify your listener:
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ExceptionListener
{
private $router;
function __construct($router)
{
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
// request is avialable on the event
$request = $event->getRequest();
// ...
$file = 'path/to/file.txt';
$response = new BinaryFileResponse($file);
// ... set response parameters ...
// finally, set the response on your event
$event->setResponse($response);
}
}

PHPExcel exporting "corrupted" .xlsx file

I have a function in Laravel that allows the user to export reports from their application. So far exporting .csv is working fine, though when giving them the option to export out to .xlsx it throws an error about the extension not being valid.
Below is the function that is called for exporting.
public function export($fileName, $data, $fileType) {
$xls = new PHPExcel();
$xls->setActiveSheetIndex(0);
if (count($data) > 0) {
$acols = array_keys($data[0]->toArray());
$xls->getActiveSheet()->fromArray($acols, NULL, 'A1');
$xls->getActiveSheet()->fromArray($data->toArray(), NULL, 'A2');
switch ($fileType) {
case 'csv':
$objWriter = new PHPExcel_Writer_CSV($xls);
break;
case 'xlsx':
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->setOffice2003Compatibility(true);
break;
case 'html':
$objWriter = new PHPExcel_Writer_HTML($xls);
return $objWriter->generateSheetData();
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=$fileName");
header("Content-Transfer-Encoding: binary ");
$objWriter->save('php://output');
return;
}
return Redirect::back();
}
This tampering is due to space/ spaces in your code files which corrupt your data passed into excel. you have to debug every corner file by file to identify if there is any space which is not required. It can be at the start of the file i.e. before
If using linux, this command might help to look for right files
find . "*" | xargs grep -il \ \<\?php >> php.txt
The trick: ob_end_clean. It seems that the buffer does not get properly cleaned up, so there is an extra space added. But by doing this, the file was downloaded and was able to be opened.
ob_end_clean();

Codeigniter force download CSV file bug

Here's the problem
I wanted to convert my data into csv format and download it. everything is fine, until the csv file that i had downloaded and there's a little bug on the file which there will be a space at the first line of the file.
for example
Before force download
"name","age",
"brad pit","40",`
After force download
"name","age",
"brad pit","40",
The csv file that i had downloaded and I try to open wit my excel will appear like this
"name" |age
brad pit|40
I believe that is because of the csv file that i had downloaded appeared an external space line in the first line of the data.
Here's the code
//write csv data
$data = $this->dbutil->csv_from_result($query, $delimiter);
//create random file name
$name = rand().'_salesperson_data_'.date('d-m-y').'.csv';
if ( ! write_file('./csv/'.$name, $data))
{
echo 'Unable to write the CSV file';
}
else
{
//perform download
$file = file_get_contents("./csv/".$name); // Read the file's contents
$filename = 'salesperson_data_'.date('d-m-y').'.csv';
force_download($filename, $file);
}
source of force_download()
if ( ! function_exists('force_download'))
{
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
#include(APPPATH.'config/mimes'.EXT);
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}
}
i thought TRIM will be last solution for me and I try to put any where possible but is stil the same. I couldn't found any solution for this problem. Please help. this stuck me for 2days already.
Thanks in advanced.
I don't know if need to use CSV only, but a good plugin/function that I use is this one: http://codeigniter.com/wiki/Excel_Plugin/
It's works with CodeIgniter Query system for exporting stuff to Excel. I use it a lot and never have problems with it.
try to print on the browser, if you see some extra space then remove.
if the extra is still on the csv file when you download, then this extra space is coming from any of your include file.
when you start writing your code try not to leave some space on the top/bottom of the code.
Use ob_clean(); before writing CSV to remove White spaces.

Resources