使用Perl解析PDF文件

4
我正在尝试从PDF中提取一些信息。我正在尝试使用CAM::PDF模块中的getpdftext.pl。当我运行$~ getpdftext.pl sample.pdf时,它会将pdf的文本输出到标准输出流。
但是我想将其写入文本文件并在perl中解析所需字段。请问有人能指导我如何做吗?
但是当我尝试在我的perl脚本中调用pdftotext.pl时,我收到了一个没有这样的文件错误。 #从pdf中提取文本并将其保存到文本文件的程序
use PDF;

use CAM::PDF;

use CAM::PDF::PageText;

use warnings;

use IPC::System::Simple qw(system capture);

$filein = 'sample.pdf';                                                                   
$fileout = 'output1.txt';  

open OUT, ">$fileout" or die "error: $!";

open IN, "getpdftext.pl $filein" or die "error :$!" ;

while(<IN>)
{
    print OUT $fileout;
}
2个回答

3

也许让 getpdftext.pl 做你想要的事情会更容易一些。

从 getpdftext.pl 的代码中操作,以下代码(未经测试)应该会将 PDF 输出到文本文件。

my $filein = 'sample.pdf';                                                                   
my $fileout = 'output1.txt';  

my $doc = CAM::PDF->new($filein) || die "$CAM::PDF::errstr\n";
open my $fo, '>', $fileout or die "error: $!";

foreach my $p ( 1 .. $doc->numPages() ) {
    my $str = $doc->getPageText($p);
    if (defined $str) {
       CAM::PDF->asciify(\$str);
       print $fo $str;
    }
}

close $fo;

不用客气。如果您愿意的话,您也可以直接使用文本而非将其打印到文件中。 可以通过更改 open my $fo ...my $docstr = '';并将 print $fo $str; 更改为 $docstr .= $str; 来与之一起使用,无需使用 close $fo; - AFresh1

0

请见perldoc -f open。您想要获取外部命令的输出流并将其用作 Perl 脚本内部的输入流。这就是 -| 模式的作用:

open my $IN, '-|', "getpdftext.pl $filein" or die $!;
while (<$IN>) {
   ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接