【问题标题】:How can I get the width and height of a text string with CAM::PDF?如何使用 CAM::PDF 获取文本字符串的宽度和高度?
【发布时间】:2009-03-06 21:23:10
【问题描述】:

我使用以下方法读取 PDF 文件并获取页面的文本字符串:

my $pdf = CAM::PDF->new($pdf_file);
my $pagetree = $pdf->getPageContentTree($page_no);

# Get all text strings of the page
# MyRenderer is a separate package which implements getTextBlocks and
# renderText methods

my @text = $pagetree->traverse('MyRenderer')->getTextBlocks;

现在,@text 拥有所有文本字符串以及每个文本字符串的起始 x、y。

如何获取每个字符串的宽度(可能还有高度)?

MyRenderer 包如下:

package MyRenderer;
use base 'CAM::PDF::GS';
sub new {
    my ($pkg, @args) = @_;
    my $self = $pkg->SUPER::new(@args);
    $self->{refs}->{text} = [];
    return $self;
}

sub getTextBlocks {
    my ($self) = @_;
    return @{$self->{refs}->{text}};
}

sub renderText {
    my ($self, $string, $width) = @_;
    my ($x, $y) = $self->textToDevice(0,0);
    push @{$self->{refs}->{text}}, {
                                    str => $string,
                                    left => $x,
                                    bottom => $y,
                                    right =>$x + $width,
                                   };
    return;
}

更新 1: 有一个函数 getStringWidth($fontmetrics, $string) 在 CAM::PDF 中。尽管该函数中有一个参数 $fontmetrics,但无论我传递给该参数的内容如何,​​该函数都会为给定的字符串返回相同的值。

另外,我不确定返回值使用的度量单位。

更新 2: 我将 renderText 函数更改为:

sub renderText {
    my ($self, $string, $width) = @_;
    my ($x, $y) = $self->textToDevice(0,0);
    push @{$self->{refs}->{text}}, {
                                str => $string,
                                left => $x,
                                bottom => $y,
                                right =>$x + ($width * $self->{Tfs}),
                                font => $self->{Tf},
                                font_size => $self->{Tfs},
                               };
    return;
}

注意,除了获取font和font_size之外,我还用$width乘以字体大小来得到字符串的真实宽度。

现在,唯一缺少的是高度。

【问题讨论】:

    标签: perl pdf


    【解决方案1】:

    getStringWidth() 很大程度上取决于您提供的字体指标。如果在该数据结构中找不到字符宽度,则回退到以下代码:

       if ($width == 0)
       {
          # HACK!!!                                                                   
          #warn "Using klugy width!\n";                                               
          $width = 0.2 * length $string;
       }
    

    这可能就是您所看到的。当我写这篇文章时,我认为这比返回 0 更好。如果您的字体指标看起来不错,并且您认为 CAM::PDF 中存在错误,请随时post more details,我会看看。

    【讨论】:

    • 感谢克里斯的反馈。检查我在 OP 中的更新 2。希望我所做的得到宽度是正确的。
    猜你喜欢
    • 2015-12-14
    • 1970-01-01
    • 2012-08-21
    • 2020-07-31
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多