http://www.perlmonks.org?node_id=813121


in reply to PDF::API2 paragraph vertical align

I've also been digging around in PDF::API2, following on from mykl.

Another angle of attack is to try to solve the problem by subclassing/overriding.

For example here's the code from PDF::API2::Content for outputting centered text.

sub text_center { my ($self,$text,@opts)=@_; my $width=$self->advancewidth($text); return $self->text($text,-indent=>-($width/2),@opts); }
It seems that the text method is used in all cases to output the text (left, right, centered, justified).

The following overrides the text method, giving us the ability to disable text output at will, allowing to precompute the height of the paragraph:

#!/usr/bin/perl package PreflightText; use common::sense; use base 'PDF::API2::Content::Text'; our $PREFLIGHT; sub text { my $self = shift; my $text = shift; return $PREFLIGHT ? $self->advancewidth($text) : $self->SUPER::text($text, @_) } ###################################################################### package main; use common::sense; use PDF::API2; my $para = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, +sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut + enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi + ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe +nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur +. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui o +fficia deserunt mollit anim id est laborum."; my $pdf = PDF::API2->new(); my $page = $pdf->page(0); my $txt = $page->text; bless $txt, 'PreflightText'; $txt->font($pdf->corefont('Times-Roman') => 10); $txt->transform(-translate=>[0, 0]); $txt->lead(12); my $actual_height = do { # # compute, but don't output # local(${PreflightText::PREFLIGHT}) = 1; my (undef, $height_remaining) = $txt->paragraph($para,'500', '1000 +', -align => 'center'); 1000 - $height_remaining; }; # # now do actual output of the vertically centered text # $txt->transform(-translate=>[300, 500 + $actual_height/2]); my ($text_remaining) = $txt->paragraph($para,'500', '1000', -align => +'center'); my $saveas = "/tmp/center.pdf"; warn "saving as: $saveas\n"; $pdf->saveas($saveas);
Update July 2012:
(1) Added saveas()
(2) Just for correctness, changed text() override method to return advancewidth() in preflight mode - same as what PDF::API2::Content::text() returns.