note
snoopy
I've also been digging around in [mod://PDF::API2], following on from [mykl].
<p>
Another angle of attack is to try to solve the problem by subclassing/overriding.
<p>
For example here's the code from [mod://PDF::API2::Content] for outputting centered text.
<code>
sub text_center
{
my ($self,$text,@opts)=@_;
my $width=$self->advancewidth($text);
return $self->text($text,-indent=>-($width/2),@opts);
}
</code>
It seems that the <code>text</code> method is used in all cases to output the text (left, right, centered, justified).
<p>
The following overrides the <code>text</code> method, giving us the ability to disable text output at will, allowing to precompute the height of the paragraph:
<code>
#!/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);
</code>
<b>Update July 2012:</b>
<br/>(1) Added <tt>saveas()</tt>
<br/>(2) Just for correctness, changed <tt>text()</tt> override method to return <tt>advancewidth()</tt> in preflight mode - same as what <tt>PDF::API2::Content::text()</tt> returns.
813011
813011