in reply to Re^8: Making PDF Tables
in thread Making PDF Tables
Now it's getting complicated !... To align the tables you need to make use of the 2nd argument returned from the table method, the number of pages that the table spans. Use this with some logic to determine which of the 2 tables is the longest and therefore where to start the next pair.
The difficult bit with table B is deciding if the carry over is onto another page already created by table A or a completely new page. This requires some more logic in the new page function. I have done this by keeping track of the 'target page number' and comparing with the total number of pages in the document. Hopefully this example will give you some ideas.
#!/usr/bin/perl use strict; use warnings; use PDF::API2; use PDF::Table; # #A4 Landscape my $width = 842; my $height = 595; my $pdftable = new PDF::Table; my $pdf = new PDF::API2(-file => "tables_side_by_side_test.pdf"); $pdf->mediabox($width, $height); my $page = $pdf->page(); my $start_page_no = 1; my $target_page_no; my $y = 500; # table A and B horiz my $xA = 10; my $xB = 500; my $table_no = 1; # create 10 table pairs for my $t (1..10){ $target_page_no = $start_page_no; my $caption = $page->text(); $caption->font($pdf->corefont('Helvetica-Bold'), 10); $caption->translate($xA,$y+1); $caption->text("Table A $t"); my ($pageA,$spanA,$yA) = _table_a($page,$xA,$y); $target_page_no = $start_page_no; $caption->translate($xB,$y+1); $caption->text("Table B $t"); my ($pageB,$spanB,$yB) = _table_a($page,$xB,$y); # determine which tables spans the most pages # to determine start of next table pair if ($spanA > $spanB) { $y = $yA; $page = $pageA; } elsif ($spanB > $spanA){ $y = $yB; $page = $pageB; } else { $y = ($yA > $yB) ? $yB : $yA; $page = $pageA; } # move down but avoid starting too close # to bottom $y = $y-30; if ($y < 10){ $y = 500; $page = _new_page() unless $t == 10; } $start_page_no = $pdf->pages; } $pdf->saveas(); # create new page for only if target page # exceed number of existing pages sub _new_page { ++$target_page_no; if ($target_page_no > $pdf->pages){ return $pdf->page; # create new } else { return $pdf->openpage($target_page_no); } } sub _table_a { my ($page,$x,$y) = @_; my $pdftable = new PDF::Table; my ($next_page, $span, $new_y) = $pdftable->table( $pdf, $page, _data($table_no++), x => $x, # center main table on the page w => 200, start_y => $y, next_y => 500, start_h => $y, next_h => 500, new_page_func => \&_new_page, padding => 2, padding_right => 10, border => 0, background_color_odd => "#E0E0E0", background_color_even => "#FFFFFF", ); return ($next_page,$span,$new_y); }; sub _data { my $t = shift; my @rows=(['A','B','C']); my $n = 5+int rand(50); push @rows,[$t,$_,$n] for 1..$n; return \@rows; }
|
|---|