user3224907
user3224907

Reputation: 768

perl calculating length of array elements with prStrWidth

I am not sure if we can calculate the length of array element by summing one up with the other using prStrWidth but this was my try:

my @field = split //, $case_field;

for $cnt (0 .. $#field) {
$field_str .= $field[$cnt];

if($cnt != (scalar @field - 1)) {
$line_pos = (rindex($field_str, "\n") > 0) ? rindex($field_str, "\n") : 0;

my ( $strwidth1 ) = prstrwidth(substr($field_str, $line_pos),'Courier New',5);
my ( $strwidth2 ) = prstrwidth($field[$cnt+1],'Courier New',5);
my ( $totalwidth ) = $strwidth1 + $strwidth2;

$field_str .= ($totalwidth < 70) ? '' : "\n";

That didn't work. Basically I need to calculate the width of the two strings using prStrWidth instead of using the length function.

Any ideas?

Upvotes: 0

Views: 87

Answers (1)

xxfelixxx
xxfelixxx

Reputation: 6592

From PDF::Reuse prStrWidth()

prStrWidth - calculate the string width

prStrWidth($string, $font, $fontSize)
    Returns string width in points. Should be used in conjunction with
    one of these predefined fonts of Acrobat/Reader: Times-Roman,
    Times-Bold, Times-Italic, Times-BoldItalic, Courier, Courier-Bold,
    Courier-Oblique, Courier-BoldOblique, Helvetica, Helvetica-Bold,
    Helvetica-Oblique, Helvetica-BoldOblique or with a TrueType font
    embedded with prTTFont. If some other font is given, Helvetica is
    used, and the returned value will at the best be approximate.

The following works:

#!/usr/bin/env perl                                                                         

use strict;
use PDF::Reuse;

my $field_str;
# ( "w_0\n", "w_1", "w_2", ... )
my @field = map { "w$_ " . ($_ % 10 ? '' : "\n") } ( 0 .. 50);

for my $cnt (0 .. $#field) {
    $field_str .= $field[$cnt];

    if( $cnt != (scalar @field - 1) ) {
        my $line_pos = (rindex($field_str, "\n") > 0) ?   rindex($field_str, "\n") : 0;

        my ( $strwidth1 ) = prStrWidth(substr($field_str, $line_pos),'Courier New',5);
        my ( $strwidth2 ) = prStrWidth($field[$cnt+1],'Courier New',5);
        my ( $totalwidth ) = $strwidth1 + $strwidth2;

        $field_str .= ($totalwidth < 70) ? '' : "\n";
    }
}

print $field_str;

Which produces the following:

w0
w1 w2 w3 w4 w5 w6 w7 w8
w9 w10
w11 w12 w13 w14 w15 w16
w17 w18 w19 w20
w21 w22 w23 w24 w25 w26
w27 w28 w29 w30
w31 w32 w33 w34 w35 w36
w37 w38 w39 w40
w41 w42 w43 w44 w45 w46
w47 w48 w49 w50

Upvotes: 1

Related Questions