首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Perl中使用PDF::API2将多个PDF合并为一个?

如何在Perl中使用PDF::API2将多个PDF合并为一个?
EN

Stack Overflow用户
提问于 2012-04-12 22:44:03
回答 3查看 3.7K关注 0票数 2

我有很多pdf文档要合并在一起,所以我写了这个代码来做这件事。它适用于我只有两个pdf文档要合并的情况,但如果我给它两个以上,额外的文档就会乱码。你能帮我找出哪里不对劲吗?

代码语言:javascript
复制
#!/usr/bin/perl

use PDF::API2;
use List::Util qw( reduce );


# Given two pdfs and a page number, appends the given page of the second pdf to the first pdf
sub append_page_to_pdf {
    my ( $pdf1, $pdf2, $pg ) = @_;
    $pdf1->importpage( $pdf2, $pg );
}

# Given two pdfs, appends the second to the first.  Closes pdf2
sub merge_2_pdfs {
    my ($pdf1, $pdf2) = @_;
    map &append_page_to_pdf( $pdf1, $pdf2, $_ ), 1..$pdf2->pages;
    $pdf2->end;
    return $pdf1;
}

# does what it says
sub open_pdf {
    my $file = $_[0];
    my $pdf = PDF::API2->open( $file );
    print "Opened pdf ( $file )\n";
    return $pdf;
}

# reduces merge_2_pdfs over an array of pdfs
sub merge_pdfs {
    my @files = @_;
    my $starting_filename = shift @files;
    my $start_pdf = &open_pdf( $starting_filename );
    my $final_pdf = reduce { &merge_2_pdfs( $a, &open_pdf( $b ) ) } $start_pdf, @files;
    return $final_pdf;
}

# Get the arguments ie save_name, file1, file2, file3, ...
my @files = @ARGV;
my $save_name = shift @files;
my $save = &merge_pdfs( @files );
$save->saveas( $save_name );
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-04-13 09:03:03

代码中的实际问题是因为您在合并文件之前关闭了其中一个文件。

代码语言:javascript
复制
my $save_name = shift @files; 
# which should be 
my $save_name = $files[0];

否则,代码会正常工作,并且我没有发现任何乱码。

以下是一些小贴士:

现在,

  1. use strictuse warnings
  2. The的一般做法是在子例程调用中省略&
  3. 在本例中,子例程使您的代码变得冗长,这使得它更难理解。这里有一些更简洁的东西。

使用严格;使用警告;使用列表::Util ' reduce ';使用PDF::API2 2;my $new =reduce{ $a->importpage($b,$_) foreach 1 ..$b->pages;$new->saveas('new.pdf');

  • A } map {PDF::api2-> $a ($_)} @ARGV;简单循环比使用reduce更易于阅读。

使用PDF::API2;my $new = PDF::API2->new;foreach my $filename (@ARGV) { my $pdf = PDF::API2->open($filename);$new->importpage($pdf,$_) foreach 1 ..$pdf->页面;} $new->saveas('new.pdf');

票数 4
EN

Stack Overflow用户

发布于 2012-04-13 01:24:01

PDF::Reuse

代码语言:javascript
复制
prFile('myFile.pdf');
for my $pdf (@PDFS) {
    prDoc($pdf);
}
prEnd();
票数 1
EN

Stack Overflow用户

发布于 2012-05-05 11:08:28

另一种可能是我的库,CAM::PDF

代码语言:javascript
复制
my $pdf1 = CAM::PDF->new($file1) or die;
my $pdf2 = CAM::PDF->new($file2) or die;
my $pdf3 = CAM::PDF->new($file3) or die;
$pdf1->appendPDF($pdf2);
$pdf1->appendPDF($pdf3);
$pdf1->cleanoutput($outfile);

或者将其封装在@ARGV上的循环中。对于两个PDF,我有一个简单的cmdline包装器来做同样的事情:

appendpdf.pl文件1.pdf文件2.pdf out.pdf

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10125972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档