sub text_center { my ($self,$text,@opts)=@_; my $width=$self->advancewidth($text); return $self->text($text,-indent=>-($width/2),@opts); } #### #!/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 reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia 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);