Skip to content

Commit

Permalink
Add round() utility method.
Browse files Browse the repository at this point in the history
  • Loading branch information
deven committed Mar 4, 2022
1 parent 2d81f2f commit c48405f
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions lib/PDF/Data.pm
Original file line number Diff line number Diff line change
Expand Up @@ -380,13 +380,12 @@ sub find_bbox {
return unless $new;

# Update content stream.
my $xy = "%.12g %.12g";
for ($content_stream) {
# Update coordinates in drawing operations.
s/^($n) ($n) ([ml])$/sprintf "$xy %s", $1 - $left, $2 - $bottom, $3/egm;
s/^($n) ($n) ($n) ($n) ([vy])$/sprintf "$xy $xy %s", $1 - $left, $2 - $bottom, $3 - $left, $4 - $bottom, $5/egm;
s/^($n) ($n) ($n) ($n) ($n) ($n) (c)$/sprintf "$xy $xy $xy %s", $1 - $left, $2 - $bottom, $3 - $left, $4 - $bottom, $5 - $left, $6 - $bottom, $7/egm;
s/^($n $n $n $n) ($n) ($n) (cm)$/sprintf "%s $xy %s", $1, $2 - $left, $3 - $bottom, $4/egm;
s/^($n) ($n) ([ml])$/join " ", $self->round($1 - $left, $2 - $bottom), $3/egm;
s/^($n) ($n) ($n) ($n) ([vy])$/join " ", $self->round($1 - $left, $2 - $bottom, $3 - $left, $4 - $bottom), $5/egm;
s/^($n) ($n) ($n) ($n) ($n) ($n) (c)$/join " ", $self->round($1 - $left, $2 - $bottom, $3 - $left, $4 - $bottom, $5 - $left, $6 - $bottom), $7/egm;
s/^($n $n $n $n) ($n) ($n) (cm)$/join " ", $1, $self->round($2 - $left, $3 - $bottom), $4/egm;
}

# Return content stream.
Expand All @@ -411,6 +410,14 @@ sub timestamp {
return sprintf "(D:%s%+03d'%02d)", strftime("%Y%m%d%H%M%S", @time), $tz / 60, abs($tz) % 60;
}

# Round numeric values to 12 significant digits to avoid floating-point rounding error and remove trailing zeroes.
sub round {
my ($self, @numbers) = @_;

@numbers = map { sprintf("%.12f", sprintf("%.12g", $_ || 0)) =~ s/\.?0+$//r; } @numbers;
return wantarray ? @numbers : $numbers[0];
}

# Validate PDF structure.
sub validate {
my ($self) = @_;
Expand Down Expand Up @@ -1399,6 +1406,15 @@ Find bounding box by analyzing a content stream. This is only partially impleme
Generate timestamp in PDF internal format.
=head1 UTILITY METHODS
=head2 round
my @numbers = $pdf->round(@numbers);
Round numeric values to 12 significant digits to avoid floating-point rounding error and
remove trailing zeroes.
=head1 INTERNAL METHODS
=head2 validate
Expand Down

0 comments on commit c48405f

Please sign in to comment.