Perl 如何使用CAM::PDF获取文本字符串的宽度和高度?
我使用以下方法读取PDF文件并获取页面的文本字符串:Perl 如何使用CAM::PDF获取文本字符串的宽度和高度?,perl,pdf,Perl,Pdf,我使用以下方法读取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
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;
}
请注意,除了获取字体和字体大小外,我还将$width与字体大小相乘,以获得字符串的实际宽度
现在,唯一缺少的是高度。getStringWidth()很大程度上取决于您提供的字体度量。如果在该数据结构中找不到字符宽度,则返回到以下代码:
if ($width == 0)
{
# HACK!!!
#warn "Using klugy width!\n";
$width = 0.2 * length $string;
}
这可能就是你所看到的。当我写这篇文章时,我认为这比返回0要好。如果您的字体度量看起来不错,并且您认为CAM::PDF中存在错误,请随意查看,我会查看。getStringWidth()很大程度上取决于您提供的字体度量。如果在该数据结构中找不到字符宽度,则返回到以下代码:
if ($width == 0)
{
# HACK!!!
#warn "Using klugy width!\n";
$width = 0.2 * length $string;
}
这可能就是你所看到的。当我写这篇文章时,我认为这比返回0要好。如果您的字体指标看起来不错,并且您认为CAM::PDF中存在缺陷,请随时查看,我会查看。谢谢您的反馈。检查我的更新2在OP。希望我所做的是正确的得到宽度。感谢克里斯的反馈。检查我的更新2在OP。希望我所做的是正确的得到宽度。