我有很多 pdf 文档要合并在一起,所以我编写了这段代码来完成它。它适用于我只有两个要合并的 pdf 文档的情况,但如果我给它两个以上,额外的文档就会出现乱码。你能帮我找出问题所在吗?
#!/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 );