Perl:不仅从jpg制作pdf

时间:2015-12-15 14:56:22

标签: perl pdf

我有以下脚本从jpgs制作pdf。应该很容易修改它来从pngs和tifs创建pdf。嗯,实际上事实并非如此。脚本如下:

#!/usr/bin/perl

use PDF::API2;
use strict;
use warnings;

# assume all just one directory path
my $folder = join(' ', @ARGV);

# deal with dos paths
$folder =~ s|\\|/|g;

$folder =~ s|/$||;

my $pdf_file = $folder . '.pdf';

die "Not a folder!\n" unless -d $folder;
die "There's already a pdf of that name!\n" if -f $pdf_file;

my $pdf = PDF::API2->new;

#indepedently works OK - JPG
foreach my $file ( glob "$folder/*.jpg" ) {
    my $jpg = $file;
    my $image = $pdf->image_jpeg($jpg);
    my $page = $pdf->page();
    $page->mediabox(0,0,$image->width, $image->height);
    $page->trimbox(0,0,$image->width, $image->height);
    my $gfx = $page->gfx;
    $gfx->image($image, 0, 0);
}

$pdf->saveas($pdf_file);

indepedently works OK - PNG
foreach my $file ( glob "$folder/*.png" ) {
    my $png = $file;
    my $image = $pdf->image_png($png);
    my $page = $pdf->page();
    $page->mediabox(0,0,$image->width, $image->height);
    $page->trimbox(0,0,$image->width, $image->height);
    my $gfx = $page->gfx;
    $gfx->image($image, 0, 0);
}

$pdf->saveas($pdf_file);

#indepedently works OK - TIF
foreach my $file ( glob "$folder/*.tif" ) {
    my $tif = $file;
    my $image = $pdf->image_tiff($tif);
    my $page = $pdf->page();
    $page->mediabox(0,0,$image->width, $image->height);
    $page->trimbox(0,0,$image->width, $image->height);
    my $gfx = $page->gfx;
    $gfx->image($image, 0, 0);
}

$pdf->saveas($pdf_file);

当我评论JPG部分时,它适用于PNG,当我评论JPG和PNG部分时,它适用于TIF。但是,它无法适用于所有扩展:JPG,PNG和TIF。

1 个答案:

答案 0 :(得分:2)

您的错误会告诉您问题所在:

  

(可能是从第40行开始的失控的多行''字符串)

next unless $file =~ /\.tif$;

应该是

next unless $file =~ /\.tif$/;

虽然我们正在努力:

  • 添加use warnings;
  • opendir / closedir通常会更好地使用glob。 E.g:

    foreach my $file ( glob "$folder/*.jpg" ) {
    
    }
    
  • 你实际上并没有终止第二个循环 - 你可能需要某个} - 大概是在close语句之前。

  • 您可能需要再次opendir,因为您closedir然后尝试readdir