Creating a Dynamic PDF and Saving it in a folder using Loop with MYSQL and Codeigniter - codeigniter

This is the public function with looping (Edited)
public function generate_salary_slip(){
$this->load->helper('file');
$this->load->library('m_pdf');
$data = [];
$slip = $this->Admin_Login_Model->generate_salary_slip();
//$html = array();
$html='';
if(!empty($slip)){
foreach($slip as $slip_list){
$id = $slip_list->emp_id;
$data['attendance'] = $this->Admin_Login_Model->get_slip_attendance($id);
$data['emp_profile'] = $this->Admin_Login_Model->get_emp_details($id);
$data['late_day'] = $this->Admin_Login_Model->get_late_days($id);
$data['half_days'] = $this->Admin_Login_Model->get_half_days($id);
$data['salary'] = $this->Admin_Login_Model->get_salary_slip($id);
$data['second_half'] = $this->Admin_Login_Model->get_half_Second_days($id);
//$html=$this->load->view('admin/payslip',$data);
$pdfFilePath = date("F_Y")."salary_slip.pdf";
$html .= $this->load->view('admin/payslip', $data, true);
}
$htmlval = $html;
//echo $html;exit;
$this->m_pdf->pdf->WriteHTML($htmlval);
$this->m_pdf->pdf->Output('salary_slips/'.$pdfFilePath, "F");
$this->session->set_flashdata('success','Salary slips saved in directory!');
redirect('admin_attendance_list');
}else{
$this->session->set_flashdata('message','Salary slips not available for this month!');
redirect('admin_attendance_list');
}
}
File is getting saved in the folder, but Only with the First Record. Also, Repeated loop is getting generated, but with same record.
How to create a HTML by loop.
PS: Using MPDF to generate PDF File
Any hep will be highly appreciated.

You need to take the render, writeHtml and Output calls outside the forech loop, there is you problem.
You could save all the data in a var and then render the HTML as you are doing now and then generate the PDF.
EDIT: Your code should look something like this (please read comments below):
$htmlData = array();
if(!empty($slip)){
foreach ($slip as $slip_list) {
//
$htmlData[] = $data;
}
$pdfFilePath = date("F_Y")."salary_slip.pdf";
$html = $this->load->view('admin/payslip', $htmlData, true);
$this->m_pdf->pdf->WriteHTML($html);
$this->m_pdf->pdf->Output('salary_slips/'.$pdfFilePath, "F");

Related

How to keep old image if a new one isn't uploaded on update. Laravel

I am hoping someone here will be able to help with this;
When a post is being updated in my project, I'd like for the image file that was uploaded during the initial post creation time, to be the same, if I don't want to upload a new one during an update.
**Also, if I do upload a new one during the update, I'd like for it to replace the old one. So, the old one gets deleted.
Here's what I currently have for the initial creation of posts;
if ($request->hasFile('post_avatar')){
$postimg = $request->file('post_avatar');
$postImgName = Str::slug($request->post_title) . '.' . $postimg->getClientOriginalExtension();
$destinationPath = public_path('/postImages');
$imagePath = $destinationPath. "/". $postImgName;
$postimg->move($destinationPath, $postImgName);
$post->post_avatar = $postImgName;
}
Thanks in advance!
I am assuming that you keep the name saved for the old image,
You can do like this,
$post_image = Str::slug($post->post_title); // taking from your old Post model instance lets say $post = Post::find(%id);
if ($request->hasFile('post_avatar')){
$image_path = public_path("/postImages/".$post_image);
if (File::exists($image_path)) {
File::delete($image_path);
}
$postimg = $request->file('post_avatar');
$postImgName = Str::slug($request->post_title) . '.' . $postimg->getClientOriginalExtension();
$destinationPath = public_path('/postImages');
$imagePath = $destinationPath. "/". $postImgName;
$postimg->move($destinationPath, $postImgName);
$post->post_avatar = $postImgName;
} else{
$post->post_avatar = $post_image;
}
$post->save();
Edit :
$post_image = Str::slug($post->post_title);
to
$post_image = $post->post_title;
Alright, below is the workflow for achieving what you have asked in your question. While, I'm not providing all the code, I believe this will be sufficient enough to guide you.
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
if ($request->hasFile('post_avatar')) {
$postimg = $request->file('post_avatar');
if ($post->post_avatar) {
// delete old image
// save new image
} else {
// save new image
}
}
// save post and redirect
}

force_download not working in codeigniter after writing

tried to auto download file after file created but its not working. file creating and appending data perfectly but download functionality not working
public function getexportfile(){
$this->load->dbutil();
// $this->load->database('DB_utility','dbutil');
//$this->load->helper('download_helper','download');
$this->load->helper('download_helper');
$this->load->helper('file');
error_reporting(0);
ini_set('display_errors', 0);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
## Condition Start
$sWhere = " where condition"; // where conditon
$date = date('Y-m-d');
$filename = 'app/logs/othermarketplace_'.$date.'.csv';
$data = $this->PMP->export($sWhere); // calling model
$result = $this->dbutil->csv_from_result($data);
write_file($filename,$result); // file creating write data perfectly
$data = file_get_contents($filename);
//$path = file_get_contents(base_url().$filename);
//$name = "othermarketplace_'.$date.'.csv";
//force_download($nme, $pth);
force_download($filename,$data);
}
anything i missed?
From docs:
// Contents of photo.jpg will be automatically read
force_download('/path/to/photo.jpg', NULL);
//$data = file_get_contents($filename);
//$path = file_get_contents(base_url().$filename);
//$name = "othermarketplace_'.$date.'.csv";
//force_download($nme, $pth);
if (!is_file($filename)) {
exit('No file found.');
}
force_download($filename, NULL);
Note:
These lines might be doing something weird. Perhaps remove them as they aren't being used:
error_reporting(0);
ini_set('display_errors', 0);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

Kohana 3.2 + PHPExcel creates empty document when there are more than 31 rows written.

I'm trying to create a simple excel document that contains a 3-column list. (First Name, Last Name, Email Address)
When I output more than 31 rows, a blank excel file is created. Does anyone know how to fix it?
My code below:
$guests = ORM::factory('guest')
->order_by('last_name', 'ASC')
->find_all()
->as_array();
$columns = array('first_name', 'last_name', 'email');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator('Me')
->setLastModifiedBy('Me)
->setTitle('Guest List')
->setSubject('Guest List')
->setDescription('Title of Report, run on ' . date('m/d/Y H:i:s'));
$objPHPExcel->createSheet(0);
$objPHPExcel->setActiveSheetIndex(0);
foreach($guests as $row => $guest) {
$source = array();
$column = 0;
$next_row = $objPHPExcel->getActiveSheet()->getHighestRow();
foreach($guest->as_array() as $column_name => $data) {
if(in_array($column_name, $columns)) {
$objPHPExcel->getActiveSheet()
->setCellValueByColumnAndRow($column, $next_row+1, $data);
$column++;
// unset($data);
}
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$this->response->body($objWriter->save('php://output'));
$this->response->send_file(TRUE, 'GuestList.xls');
Kohana has a hard time handling the rendered file using the send_file() method, so write the file to disk using the built-in method from PHPExcel. Then use Kohana to deliver the saved file as a download.
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($filename, 'EXCEL2007');
$this->response->send_file( DOCROOT.$filename );

codeigniter export csv in windows platform

function export_csv(){
$this->load->helper('csv');
if(isset($_POST['term_val'])&&$_POST['term_val']<>'0'){
$term = $this->Search_model->get_term($_POST['term_val']);
$term = json_decode($term);
}else{
$term=array();
}
$orders = $this->Order_model->get_orders_export($term,'place_order');
if(count($orders)>0){
foreach($orders as $order){
$sublist['order_id']= $order->order_number;
$sublist['ship_to']= $order->ship_firstname.' '.$order->ship_lastname;
$sublist['order_date']= date('d-m-Y H:i:s',strtotime($order->ordered_on));
$sublist['email_to']= $order->ship_email;
$sublist['city']= $order->ship_city;
$sublist['pincode']= $order->ship_zip;
$sublist['ship_address']= $order->ship_address1.' , '.$order->ship_address2;
$sublist['phone']= $order->ship_phone;
$sublist['product_name']= $order->name;
$sublist['product_id']= $order->product_id;
$sublist['status']= $order->status;
$sublist1[]= $sublist;
}
$delimiter = ";";
$newline = "\r\n";
$heading[]=array('order_id'=>'Order Id','ship_to'=>'Ship To','order_date'=>'Order Date','email_to'=>'Email To',
'city'=>'City','pincode'=>'Pincode','ship_address'=>'Ship Address','phone'=>'Phone','product_name'=>'Product Name','product_id'=>'Product ID','status'=>'status');
$get_csv=array_to_csv1($sublist1,$heading,$delimiter, $newline);
ob_start();
$filename = "orders_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
// header("Content-type: text/x-csv");
//header("Content-type: text/csv");
// header("Content-type: application/csv");
// header("Content-Disposition: attachment; filename=orders".date('d-M-Y').".csv");
print_r($get_csv);
}else{
redirect($this->config->item('admin_folder').'/orders');
}
}
The above code is the controller function for export CSV and the image is the action taking place when exporting.
Problem : Actually if we export csv using codeigniter it is showing that image as shown above. If we press export csv using codeigniter it it should not show that image , it should directly export csv into excel .
if you want to generate reports in csv format it is very easy with codeigniter. Your model function
function index(){
return $query = $this->db->get('my_table');
//Here you should note i am returning
//the query object instead of
//$query->result() or $query->result_array()
}
Now in controller
function get_report(){
$this->load->model('my_model');
$this->load->dbutil();
$this->load->helper('file');
// get the object
$report = $this->my_model->index();
//pass it to db utility function
$new_report = $this->dbutil->csv_from_result($report);
//Now use it to write file. write_file helper function will do it
write_file('csv_file.csv',$new_report);
//Done
}
No externals are required everything is available in Codeigntier.
The above method will force the file to be downloaded instead of
being opening. Cheers! If you want to write xml file it is easy too.
Just use xml_from_result() method of dbutil and use write_file('xml_file.xml,$new_report)
Visit these links they will help.
Database Utility Class
And
File Helper
***> if you are trying to generate reports in csv format then it will quite
> easy with codeigniter.***
Place this code in your Controller
function get_report()
{
$this->load->model('Main_Model');
$this->load->dbutil();
$this->load->helper('file');
/* get the object */
$report = $this->Main_Model->print_report();
$delimiter = ",";
$newline = "\r\n";
$new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
write_file( 'application/third_party/file.csv', $new_report);
$this->load->view('report_success.php');
}
Put this code into Model
public function print_report()
{
return $query = $this->db->query("SELECT * FROM Table_name");
}
report_success.php is just Successful Notification.
Your Report is being Exported. Thank you
Finally Your "file.csv" is generated.
its basically stored at physical storage.
In CodeIgniter/application/third-party/file.csv
it works.
it will help you.

Save formatted xml

Hi Can someone please tell me why this inst saving to my XML file? it doesn't return any errors but doesn't write to the file either? It might be silly so I apologize in advance
<?php
$pastor = $_POST["Speaker"];
$title = $_POST["Title"];
$link = $_POST["podcasturl"];
$download = $_POST["Download"];
$podcastid = $_POST["Podcastid"];
$pubdate = $_POST ["Date"];
$filename = 'podcast.xml';
$xml = simplexml_load_file($filename);
$xml->addChild('title');
$xml->addChild('pastor', $pastor);
$xml->addChild('title', $title);
function saveXMLFormatted($xml, $filename) {
$savexml = new DOMDocument('1.0');
$savexml->preserveWhiteSpace = FALSE;
$savexml->loadXML($xml->asXML());
$savexml->formatOutput = TRUE;
file_put_contents($filename, $savexml->saveXML());
}

Resources