FPDF : Table Cell Line Break after 10 cells - fpdf

hey guys its me again
I am trying to copy this output
but my output in fpdf is like this
and this is my code:
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage('L');
$pdf->SetFont('Arial','',11);
$pdf->Cell(112);
$pdf->Cell(45,10,'Teacher'."'s ".'Table',1,'','C');
$pdf->Ln(20);
while($row = mysql_fetch_array($result)){
$fname = $row['stud_fname'];
$lname = $row['stud_lname'];
$pdf->SetFont('Arial','',11);
$pdf->Cell(35,10,$lname.", ".$fname,1,'','C');
}
$pdf->Output();
the out put should be five cells in the left then (space) and another five cells in the right

make sure you adjust the width of the cell so that could put 11 cell in one line, or if still not have enough space, try to change the font type and size
you should try something like this
$max=50;
$num=1;
while($row = mysql_fetch_array($result)){
$fname = $row['stud_fname'];
$lname = $row['stud_lname'];
$pdf->SetFont('Arial','',11);
if ($num mod 5==0 && $num mod 2 == 1){
$pdf->Cell(5,10,$lname.", ".$fname,1,'','C');
$pdf->Cell(5,10,'',1,'','C');
}else if ($num mod 5==0 && $num mod 2 == 0){
$pdf->Cell(5,10,$lname.", ".$fname,1,1,'C');
}else{
$pdf->Cell(5,10,$lname.", ".$fname,1,'','C');
}
$num++;
}
by that code, we have to set maximum of the cell that we want to create
first looping we need to create the cell with have a data from database, the second looping we need to create the cell without data
if ($num <= $max){
for ($i=$num;$i<=$max;$i++){
if ($num mod 5==0 && $num mod 2 == 1){
$pdf->Cell(5,10,'',1,'','C');
$pdf->Cell(5,10,'',1,'','C');
}else if ($num mod 5==0 && $num mod 2 == 0){
$pdf->Cell(5,10,'',1,1,'C');
}else{
$pdf->Cell(5,10,'',1,'','C');
}
}
}
the code should be work, if you still didn't see the five cells in the right the you should change the cell width, font size or type to fit the view with the paper size
You can make some modification to add the number inside the cell
The things that you should pay attention is that the Cell function will be write an overlap text and will not wrap the text except you made changes the core function or you can using MultiCell function

Related

how to put my box in every row of my looping

I want to put multiple box in every 1st and last column per row in my array of looping. Also the result of my looping is twice as it is
$w = array(82,95); //for XY dimension
for($i=0; $i < 2; $i++) {
$pdf->Row(array(utf8_decode($pdf->Rect($w[$i], 10, 7, 3, 'D')),
utf8_decode($client_code),
utf8_decode($full_name),
utf8_decode($prod_name),
number_format($loan_amount,2),
number_format($total_outstanding_principal + $int_bal,2),
date_format(date_create($start_date),"d F Y"),
$num_paid,
$num_unpaid,
$total_installment,
number_format($repayment - $total_penalty,2),
date_format(date_create($end_date),"d F Y"),
date_format(date_create($last_paid_date),"d F Y"),
number_format($repayment,2),
number_format($overdue,2),""));
}

perl - algorithm to replace multiple if statements using mod

I have a perl script that parses a large files. It works but it is slow and I see a pattern that i'd like to take advantage of, but i don't know how to write it.
there is a section where i count a number of objectIds, and have to return a value Spaces. The mininum number of *objectIds is 3 and increases in odd increments, my output starts at 3 and increases in multiples of three.
So i have a chain of 30 statements like this
if($objectIds == 3)
{
$spaces = 3;
}
if($objectIds == 5)
{
$spaces = 6;
}
if($objectIds == 7)
{
$spaces = 9;
}
I see that the difference is incrementing by a modulo of 1, i.e. (3 % 3 = 0), (6 % 5 = 1), (9 % 7 = 2), but i can't for the life of me figure out how to optimize this.
This formula should calculate and replace your ifs,
# $spaces = $objectIds + ($objectIds-3)/2;
# $spaces = (2*$objectIds + $objectIds-3)/2;
# $spaces = 3*($objectIds -1)/2;
$spaces = ($objectIds -1) * 3/2;
The first optimisation I see is to use elsif :
if($objectIds == 3)
{
$spaces = 3;
}
elsif($objectIds == 5)
{
$spaces = 6;
}
elsif($objectIds == 7)
{
$spaces = 9;
}

How can I improve Perl compare performance

I have an array ref of about 50,000 users. I want to go through all those users and compare each one to all the others in order to build a weighted list of matches (if the name is an exact match it's worth x, a partial match is worth y etc).
After going through the list and doing all the checks, I then want to go get the 10 highest weighted matches. Here is sort of a example of what I'm doing to help explain:
#!/usr/bin/perl
######################################################################
# Libraries
# ---------
use strict;
use warnings;
my $users = [];
$users->[0]{'Name'} = 'xxx';
$users->[0]{'Address'} = 'yyyy';
$users->[0]{'Phone'} = 'xxx';
$users->[1]{'Name'} = 'xxx';
$users->[1]{'Address'} = 'yyyy';
$users->[1]{'Phone'} = 'xxx';
$users->[2]{'Name'} = 'xxx';
$users->[3]{'Address'} = 'yyyy';
$users->[4]{'Phone'} = 'xxx';
foreach my $user_to_check (#$users) {
my $matched_users = [];
foreach my $user (#$users) {
$user_to_check->{'Weight'} = 0;
if (lc($user_to_check->{'Name'}) eq lc($user->{'Name'})) {
$user_to_check->{'Weight'} = ($user_to_check->{'Weight'} + 10);
} elsif ((length($user_to_check->{'Name'}) > 2) && (length($user->{'Name'}) > 2) && ($user_to_check->{'Name'} =~ /\Q$user->{'Name'}\E/i)) {
$user_to_check->{'Weight'} = ($user_to_check->{'Weight'} + 5);
}
if (lc($user_to_check->{'Address'}) eq lc($user->{'Address'})) {
.....
}
if ($user_to_check->{'Weight'} > 0) {
# We have matches, add to matched users
push (#$matched_users,$user);
}
}
# Now we want to get just the top 10 highest matching users
foreach my $m_user (sort { $b->{'Weight'} <=> $a->{'Weight'} } #$matched_users ) {
last if $counter == 10;
.... # Do stuff with the 10 we want
}
}
The problem is, it's sooo slow. It takes more than a day to run (and I've tried it on multiple machines). I know that the "sort" is a killer but I did also try inserting the results into a tmp mysql table and then at the end instead of doing the Perl sort, I just did an order by select, but the difference in time was very minor.
As I'm just going through a existing data structure and comparing it I'm not sure what I could do (if anything) to speed it up. I'd appreciate any advise.
O(n²)
You compare each element in #$users against every element in there. That is 5E4² = 2.5E9 comparisions. For example, you wouldn't need to compare an element against itself. You also don't need to compare an element against one you have already compared. I.e. in this comparision table
X Y Z
X - + +
Y - - +
Z - - -
there only have to be three comparision to have compared each element against all others. The nine comparisions you are doing are 66% unneccessary (asymptotically: 50% unneccessary).
You can implement this by looping over indices:
for my $i (0 .. $#$users) {
my $userA = $users->[$i];
for my $j ($i+1 .. $#$users) {
my $userB = $users->[$j];
...;
}
}
But this means that upon match, you have to increment the weight of both matching users.
Do things once, not 100,000 times
You lowercase the name of each user 1E5 times. This is 1E5 - 1 times to much! Just do it once for each element, possibly at data input.
As a side note, you shouldn't perform lowercasing, you should do case folding. This is available since at least v16 via the fc feature. Just lowercasing will be buggy when you have non-english data.
use feature 'fc'; # needs v16
$user->[NAME] = fc $name;
or
use Unicode::CaseFold;
$user->[NAME] = fc $name;
When hashes are not fast enough
Hashes are fast, in that a lookup takes constant time. But a single hash lookup is more expensive than an array access. As you only have a small, predefined set of fields, you can use the following trick to use hash-like arrays:
Declare some constants with the names of your fields that map to indices, e.g.
use constant {
WEIGHT => 0,
NAME => 1,
ADDRESS => 2,
...;
};
And then put your data into arrays:
$users->[0][NAME] = $name; ...;
You can access the fields like
$userA->[WEIGHT] += 10;
While this looks like a hash, this is actually a safe method to access only certain fields of an array with minimal overhead.
Regexes are slow
Well, they are quite fast, but there is a better way to determine if a string is a substring of another string: use index. I.e.
$user_to_check->{'Name'} =~ /\Q$user->{'Name'}\E/i
Can be written as
(-1 != index $user_to_check->{Name}, $user->{Name})
assuming both are already lowercased case folded.
Alternative implementation
Edit: this appears to be invalidated by your edit to your question. This assumed you were trying to find some global similarities, not to obtain a set of good matches for each user
Implementing these ideas would make your loops look somewhat like
for my $i (0 .. $#$users) {
my $userA = $users->[$i];
for my $j ($i+1 .. $#$users) {
my $userB = $users->[$j];
if ($userA->[NAME] eq $userB->[NAME]) {
$userA->[WEIGHT] += 10;
$userB->[WEIGHT] += 10;
} elsif ((length($userA->[NAME]) > 2) && (length($userB->[NAME]) > 2))
$userA->[WEIGHT] += 5 if -1 != index $userA->[NAME], $userB->[NAME];
$userB->[WEIGHT] += 5 if -1 != index $userB->[NAME], $userA->[NAME];
}
if ($userA->[ADDRESS] eq $userB->[ADDRESS]) {
..... # More checks
}
}
}
my (#top_ten) = (sort { $b->[WEIGHT] <=> $a->[WEIGHT] } #$users)[0 .. 9];
Divide and conquer
The task you show is highly parallelizable. If you have the memory, using threads is easy here:
my $top10 = Thread::Queue->new;
my $users = ...; # each thread gets a copy of this data
my #threads = map threads->create(\&worker, $_), [0, int($#$users/2)], [int($#$users/2)+1, $#users];
# process output from the threads
while (defined(my $ret = $top10->dequeue)) {
my ($user, #top10) = #$ret;
...;
}
$_->join for #threads;
sub worker {
my ($from, $to) = #_;
for my $i ($from .. $to) {
my $userA = $users->[$i];
for $userB (#$users) {
...;
}
my #top10 = ...;
$top10->enqueue([ $userA, #top10 ]); # yield data to the main thread
}
}
You should probably return your output via a queue (as shown here), but do as much processing as possible inside the threads. With more advanced partitioning of the workload, should spawn as many threads as you have processors available.
But if any kind of pipelining, filtering or caching can decrease the number of iterations needed in the nested loops, you should do such optimizations (think map-reduce-style programming).
Edit: Elegantly reducing complexity through hashes for deduplication
What we are essentially doing is calculating a matrix of how good our records match, e.g.
X Y Z
X 9 4 5
Y 3 9 2
Z 5 2 9
If we assume that X is similar to Y implies Y is similar to X, then the matrix is symmetric, and we only need half of it:
X Y Z
X \ 4 5
Y \ 2
Z \
Such a matrix is equivalent to a weighted, undirected graph:
4 X 5 | X – Y: 4
/ \ | X – Z: 5
Y---Z | Y – Z: 2
2 |
Therefore, we can represent it elegantly as a hash of hashes:
my %graph;
$graph{X}{Y} = 4;
$graph{X}{Z} = 5;
$graph{Y}{Z} = 2;
However, such a hash structure implies a direction (from node X to node Y). To make querying the data easier, we might as well include the other direction too (due to the implementation of hashes, this won't lead to a large memory increase).
$graph{$x}{$y} = $graph{$y}{$x} += 2;
Because each node is now only connected to those nodes it is similar to, we don't have to sort through 50,000 records. For the 100th record, we can get the ten most similar nodes like
my $node = 100;
my #top10 = (sort { $graph{$node}{$b} <=> $graph{$node}{$a} } keys %{ $graph{$node} })[0 .. 9];
This would change the implementation to
my %graph;
# build the graph, using the array indices as node ID
for my $i (0 .. $#$users) {
my $userA = $users->[$i];
for my $j ($i+1 .. $#$users) {
my $userB = $users->[$j];
if ($userA->[NAME] eq $userB->[NAME]) {
$graph{$j}{$i} = $graph{$i}{$j} += 10;
} elsif ((length($userA->[NAME]) > 2) && (length($userB->[NAME]) > 2))
$graph{$j}{$i} = $graph{$i}{$j} += 5
if -1 != index $userA->[NAME], $userB->[NAME]
or -1 != index $userB->[NAME], $userA->[NAME];
}
if ($userA->[ADDRESS] eq $userB->[ADDRESS]) {
..... # More checks
}
}
}
# the graph is now fully populated.
# do somethething with each top10
while (my ($node_id, $similar) = each %graph) {
my #most_similar_ids = (sort { $similar->{$b} <=> $similar->{$a} } keys %$similar)[0 .. 9];
my ($user, #top10) = #$users[ $node_id, #most_similar_ids ];
...;
}
Building the graph this way should take half the time of naive iteration, and if the average number of edges for each node is low enough, going through similar nodes should be considerably faster.
Parallelizing this is a bit harder, as the graph each thread produces has to be combined before the data can be queried. For this, it would be best for each thread to perform the above code with the exception that the iteration bounds are given as parameters, and that only one edge should produced. The pair of edges will be completed in the combination phase:
THREAD A [0 .. 2/3] partial
\ graph
=====> COMBINE -> full graph -> QUERY
/ partial
THREAD B [2/3 .. 1] graph
# note bounds recognizing the triangular distribution of workload
However, this is only beneficial if there are only very few similar nodes for a given node, as combination is expensive.

Consistent random colour highlights

In a table I have columns with to and from dates, I highlight overlaps between rows taking into account the periods, this is done exhaustively in nested loops. This is not the issue.
I need the same colour for the rows that overlap.
sub highlight_overlaps {
my $date_from1;
my $date_to1;
my $date_from2;
my $date_to2;
my $i = 0;
my $j = 0;
for ($i; $i < $#DATE_HOLDER; $i++) {
$date_from1 = $DATE_HOLDER[$i][0];
$date_to1 = $DATE_HOLDER[$i][1];
my $red = int(rand(65)) + 190;
my $green = int(rand(290)) - 55;
my $blue = int(rand(290)) - 55;
for ($j=$i+1; $j<=$#DATE_HOLDER; $j++) {
$date_from2 = $DATE_HOLDER[$j][0];
$date_to2 = $DATE_HOLDER[$j][1];
if (($date_from1 le $date_to2 && $date_to1 ge $date_to2) ||
($date_from1 le $date_from2 && $date_to1 le $date_to2) ||
($date_from1 gt $date_from2 && $date_from1 lt $date_to2)) {
$tb->setCellStyle($i+2, 6, "background-color:rgb($red,$green,$blue);font-size:9pt");
$tb->setCellStyle($i+2, 7, "background-color:rgb($red,$green,$blue);font-size:9pt");
$tb->setCellStyle($j+2, 6, "background-color:rgb($red,$green,$blue);font-size:9pt");
$tb->setCellStyle($j+2, 7, "background-color:rgb($red,$green,$blue);font-size:9pt");
}
}
}
}
This works fine if it's just a pair of dates; say:
1) 25-06-2012 27-06-2012
2) 18-06-2012 29-06-2012
Will get the same colour
If though I have
0) 26-06-2012 28-06-2012
1) 25-06-2012 27-06-2012
2) 18-06-2012 29-06-2012
0 will get a different colour while 1 & 2 are paired as intended.
When and how to pick colours so that different colours are only applied to different overlaps?
Following up on the first answer; how may I represent overlaps in order to store them in a data structure, so that I can colour them after their detection?
You'll have to compare each interval against each other interval, and put them in 'buckets' when they are equal. Now when you compare an interval to a third interval, you put the third in the same bucket as the interval.
Then you print the buckets.
Perl's hash would make for fine buckets.
About your overlap detection
There is no overlap if
date1_to < date2_from OR
date2_to < date1_from
Or, in Perl:
if ($date_to1 lt $date_from2 || $date_to2 lt $date_from1) {
#overlap
}
Invert that either using Perl's unless, or using de Morgan:
if ($date_to1 ge $date_from2 && $date_to2 ge $date_from1) {
#overlap
}

fpdf multicell issue

how we display fpdf multicell in equal heights having different amount of content
Great question.
I solved it by going through each cell of data in your row that will be multicelled and determine the largest height of all these cells. This happens before you create your first cell in the row and it becomes the new height of your row when you actually go to render it.
Here's some steps to achieve this for just one cell, but you'll need to do it for every multicell:
This assumes a $row of data with a String attribute called description.
First, get cell content and set the column width for the cell.
$description = $row['desciption']; // MultiCell (multi-line) content.
$column_width = 50;
Get the width of the description String by using the GetStringWidth() function in FPDF:
$total_string_width = $pdf->GetStringWidth($description);
Determine the number of lines this cell will be:
$number_of_lines = $total_string_width / ($column_width - 1);
$number_of_lines = ceil( $number_of_lines ); // Round it up.
I subtracted 1 from the $column_width as a kind of cell padding. It produced better results.
Determine the height of the resulting multi-line cell:
$line_height = 5; // Whatever your line height is.
$height_of_cell = $number_of_lines * $line_height;
$height_of_cell = ceil( $height_of_cell ); // Round it up.
Repeat this methodology for any other MultiCell cells, setting the $row_height to the largest $height_of_cell.
Finally, render your row using the $row_height for your row's height.
Dance.
I was also getting same issue when i have to put height equal to three lines evenif i have content of half or 1 and half line, i solved this by checking if in a string no of elements are less than no of possible letters in a line it is 60. If no of letters are less or equal to one line then ln() is called for two empty lines and if no of words are equal to or less than 2 line letters then one ln() is called.
My code is here:
$line_width = 60; // Line width (approx) in mm
if($pdf->GetStringWidth($msg1) < $line_width)
{
$pdf->MultiCell(75, 8, $msg1,' ', 'L');
$pdf->ln(3);
$pdf->ln(3.1);
}
else{
$pdf->MultiCell(76, 4, $msg1,' ', 'L');
$pdf->ln(3.1);
}
Ok I've done the recursive version. Hope this helps even more to the cause!
Take in account these variables:
$columnLabels: Labels for each column, so you'll store data behind each column)
$alturasFilas: Array in which you store the max height for each row.
//Calculate max height for each column for each row and store the value in //////an array
$height_of_cell = 0;
$alturasFilas = array();
foreach ( $data as $dataRow ) {
for ( $i=0; $i<count($columnLabels); $i++ ) {
$variable = $dataRow[$i];
$total_string_width = $pdf->GetStringWidth($variable);
$number_of_lines = $total_string_width / ($columnSizeWidth[$i] - 1);
$number_of_lines = ceil( $number_of_lines ); // Redondeo.
$line_height = 8; // Altura de fuente.
$height_of_cellAux = $number_of_lines * $line_height;
$height_of_cellAux = ceil( $height_of_cellAux );
if($height_of_cellAux > $height_of_cell){
$height_of_cell = $height_of_cellAux;
}
}
array_push($alturasFilas, $height_of_cell);
$height_of_cell = 0;
}
//--END--
Enjoy!
First, it's not the question to get height of Multicell. (to #Matias, #Josh Pinter)
I modified answer of #Balram Singh to use this code for more than 2 lines.
and I added new lines (\n) to lock up height of Multicell.
like..
$cell_width = 92; // Multicell width in mm
$max_line_number = 4; // Maximum line number of Multicell as your wish
$string_width = $pdf->GetStringWidth($data);
$line_number = ceil($string_width / $cell_width);
for($i=0; $i<$max_line_number-$line_number; $i++){
$data.="\n ";
}
Of course you have to assign SetFont() before use GetStringWidth().
My approach was pretty simple. You already need to override the header() and footer() in the fpdf class.
So i just added a function MultiCellLines($w, $h, $txt, $border=0, $align='J', $fill=false).
That's a very simple copy of the original MultiCell. But it won't output anything, just return the number of lines.
Multiply the lines with your line-height and you're safe ;)
Download for my code is here.
Just rename it back to ".php" or whatever you like. Have fun. It works definitely.
Mac
My personal solution to reduce the font size and line spacing according to a preset box:
// set box size and default font size
$textWidth = 100;
$textHeight = 100;
$fontsize = 12;
// if you get text from html div (using jquery and ajax) you must replace every <br> in a new line
$desc = utf8_decode(str_replace('<br>',chr(10),strip_tags($_POST['textarea'],'<br>')));
// count newline set in $desc variable
$countnl = substr_count($desc, "\n");
// Create a loop to reduce the font according to the contents
while($pdf->GetStringWidth($desc) > ($textWidth * (($textHeight-$fontsize*0.5*$countnl) / ($fontsize*0.5)))){
$fontsize--;
$pdf->SetFont('Arial','', $fontsize);
}
// print multicell and set line spacing
$pdf->MultiCell($textWidth, ($fontsize*0.5), "$desc", 0, 'L');
That's all!
A better solution would be to use your own word wrap function, as FPDF will not cut words, so you do not have to rely on the MultiCell line break.
I have wrote a method that checks for every substring of the text if the getStringWidth of FPDF is bigger than the column width, and splits accordingly.
This is great if you care more about a good looking PDF layout, than performance.
public function wordWrapMultiCell($text, $cellWidth = 80) {
$explode = explode("\n", $text);
array_walk($explode, 'trim');
$lines = [];
foreach($explode as $split) {
$sub = $split;
$char = 1;
while($char <= strlen($sub)) {
$substr = substr($sub, 0, $char);
if($this->pdf->getStringWidth($substr) >= $cellWidth - 1) { // -1 for better getStringWidth calculating
$pos = strrpos($substr, " ");
$lines[] = substr($sub, 0, ($pos !== FALSE ? $pos : $char)).($pos === FALSE ? '-' : '');
if($pos !== FALSE) { //if $pos returns FALSE, substr has no whitespace, so split word on current position
$char = $pos + 1;
$len = $char;
}
$sub = ltrim(substr($sub, $char));
$char = 0;
}
$char++;
}
if(!empty($sub)) {
$lines[] = $sub;
}
}
return $lines;
}
This returns an array of text lines, which you could merge by using implode/join:
join("\r\n", $lines);
And what it was used for in the first place, get the line height:
$lineHeight = count($lines) * $multiCellLineHeight;
This only works for strings with a space character, no white spacing like tabs. You could replace strpos with a regexp function then.