DOMPDF Multiple Documents Generated In One PDF - dompdf

I am using DOMPDF to generate invoices.
1 invoice at time is perfect.
But i want to print (from a while) all invoices between date
all is perfect
But Dompdf print only the last invoice.
The dompdf code
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$sql=mysql_query("SELECT * FROM invoices WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql))
{
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];
// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2))
{
$name = $rows2[name];
//ETC...
// Now we generate the html invoice
$html =
'<html><body>'.
//the invoice html
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
}
}
$dompdf->stream("Invoice.pdf");
I want to get all invoices ( sometimes 5, sometimes 50 ) in 1 pdf file.
How to ?
I close my whiles at end of files, but don't help.
Hope you can help.

The way your code is written right now you render your first document then don't do anything with it. So the second pass through the while loop will overwrite the first pass. There are a few ways to achieve what you want, but the easiest would be to compile all your HTML into a single document then render that.
Using your code as a start:
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$invoices = array();
$sql=mysql_query("SELECT * FROM invoices WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql)) {
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];
// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2)) {
$name = $rows2[name];
//ETC...
// Force page break between invoices
if ( strlen( $html ) > 0 ) { $html .= '<div style="page-break-before: always;"></div>'; }
// Now we generate the html invoice
$invoices[] = '<!-- the html invoice -->';
}
}
$html = '<html><body>' . implode( '<div style="page-break-before: always;"></div>' , $invoices ) . '</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("Invoice.pdf");

Related

email when images change, woocommerce product

I am attempting to send out an email anytime a woocommerce product has its images changed in any way.
I started off by attempting to get the $_POST of the image gallery, but I think I am calling it the wrong thing… I have tried the following:
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
Then I am comparing that value to the current image ids:
$oldImages = $product->get_gallery_image_ids();
If they do not match I am using wp_mail to send an email to various people.
I am doing all this inside a custom php function using:
add_action(‘pre_post_update’, ‘content_change_email’, 10, 2);
function content_change_email($post_ID, $data)
{
}
I assume the problem is originating with the
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
part of the code.
Can someone let me know what the correct meta field name for the gallery images is?
I solved my own problem…
I used a custom meta field to record the IDs for all the images, including the featured image then compared that to the current gallery images to see if they had changed, if they did then update the custom meta value with the new numbers and send an email to let people know the pictures changed.
code is as follows:
// send email when images change for a product
add_action( 'woocommerce_update_product', 'imagecheck_on_product_save', 10, 1 );
function imagecheck_on_product_save( $product_id ) {
$product = wc_get_product( $product_id );
// do something with this product
$metaImages = get_post_meta( $product_id, '_gallery_image_ids', true );
$currentImages = $product->get_gallery_image_ids();
$imageIDs = get_post_thumbnail_id( $product_id );
if ($imagesIDs != "" )
{
$imageIDs = $imageIDs . ", ";
foreach($currentImages as $value){
$imageIDs = $imageIDs . $value . ", ";
}
if ( $metaImages != $imageIDs ) {
update_post_meta( $product_id, '_gallery_image_ids', esc_attr( $imageIDs ) );
global $current_user;
wp_get_current_user();
$email = $current_user->user_email;
$lastuser = $current_user->user_firstname;
if ( $product->get_sku() != "" )
{
$memail = "<pre>USER: " . $lastuser . " made the following changes:</br>
Meta gallery images: " . $metaImages . "</br>
</br>
Actual gallery images: " . $imageIDs . "
" . $memail . "</pre>";
$headers = array('Content-Type: text/html; charset=UTF-8');
$subject = "PICTURES CHANGED - SKU: " . $product->get_sku();
$to = "(insert who you want to send to here)";
wp_mail( $to, $subject, $memail, $headers );
}
}
}
}

Creating a Dynamic PDF and Saving it in a folder using Loop with MYSQL and 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");

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 );

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

How to display Serial Numbers in a table that has been created using table library in codeigniter?

I know how to create pagination and generate a table containing information from database in codeigniter, but I don't how to display the serial numbers for each row in the table. Example:
SL. Name Email
1. Srijon example#yahoo.com
2. Jake jake#yahoo.com
Would you please kindly show me how to do that? Thanks in advance
Here is the controller for how I create pagination and generate table (without serial numbers)
function index(){
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('Student ID','Student Name','Batch','Edit','Delete');
$config['base_url'] = 'http://localhost/coaching/index.php/student_list/index';
$config['total_rows'] = $this->db->get('student')->num_rows();
$config['per_page'] = 15;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div id="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['tab'] = "Student List";
$this->load->model('mod_studentlist');
$data['records']= $this->mod_studentlist->student_list();
$data['main_content']='studentlist';
$this->load->view('includes/template',$data);
}
Here's my model
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
foreach ($rows as $count => $row)
{
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
Here's my view file
<?php echo $this->table->generate($records);?>
<?php echo $this->pagination->create_links();?>
<script type="text/javascript" charset="utf-8">
$('tr:odd').css('background','#EAEAEA');
</script>
You should create a variable inside your model function:
<?php
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
$sl = $this->uri->segment(3) + 1; // so that it begins from 1 not 0
foreach ($rows as $count => $row)
{
array_unshift($rows[$count], $sl.'.');
$sl = $sl + 1;
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
and modify your controller:
<?php
function index() {
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('SL.', 'Student ID','Student Name','Batch','Edit','Delete');
....
Codeigniter has a great Table library to display data in html table format. Adding a Serial No is sometime required to a table, but Row num is not easily provided by MySQL hence while using Table library this function is added to do the job.
Here goes the code:
/**
* Set the serial no
*
* Add serial no to left of table
*
* #access public
* #param mixed
* #return mixed
*/
function add_sr_no(&$arr)
{ if (!is_array($arr)) return $arr;
$i=1;
foreach ($arr as &$values) {
if (!is_array($values))
break;
else
array_unshift($values, $i++);
}
return $arr;
}
Just add these lines to table.php in library.
Usage:
$rows = $query->result_array();
$this->table->add_sr_no($rows);
Don't forget to add first column 'Sr No' in set_heading.
Read the post here.
Hope this helps.
Have you thought about doing this on the client? the javascript library datatables is brilliant. it can handle the sorting for you at the user side, and can be made to dynamically retrieve information using ajax, so load times are fast on large tables. for under < 100 rows or so there probably isn't a need though. i have it sorting/filtering tables with >100 000 rows with no problems at all (using ajax)
unless the serial numbers have semantic meaning don't show them to the client. it just more stuff for them to filter. if they are required for your code, but not for the user to see, just hide them away in a data attribute or something.

Resources