【发布时间】: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乘以字体大小来得到字符串的真实宽度。
现在,唯一缺少的是高度。
【问题讨论】: