我有很多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 );发布于 2012-04-13 09:03:03
代码中的实际问题是因为您在合并文件之前关闭了其中一个文件。
my $save_name = shift @files;
# which should be
my $save_name = $files[0];否则,代码会正常工作,并且我没有发现任何乱码。
以下是一些小贴士:
现在,
use strict和use warnings&。使用严格;使用警告;使用列表::Util ' reduce ';使用PDF::API2 2;my $new =reduce{ $a->importpage($b,$_) foreach 1 ..$b->pages;$new->saveas('new.pdf');
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');
发布于 2012-04-13 01:24:01
PDF::Reuse。
prFile('myFile.pdf');
for my $pdf (@PDFS) {
prDoc($pdf);
}
prEnd();发布于 2012-05-05 11:08:28
另一种可能是我的库,CAM::PDF。
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
https://stackoverflow.com/questions/10125972
复制相似问题