如何使用PDF API2创建多个PDF文件?

时间:2013-09-06 15:31:07

标签: perl pdf

以下是使用Perl模块PDF :: API2创建单个PDF文件所需的完整最小代码。第一个PDF创建得很好。在尝试创建第二个PDF时,该过程在第二个实例行失败:

  $page = $pdf->page(0);

错误Can't call method "new_obj" on an undefined value at C:/Perl64/site/lib/PDF/API2/Basic/PDF/Pages.pm line 92.

为什么呢?更重要的是,我需要做些什么来创建第二个pdf?

  #!/usr/bin/perl
  use strict;
  use warnings;
  use PDF::API2;

  my $pdf1 = 'hello_world.pdf';
  my $pdf2 = 'hi_mom.pdf';
  my $text1 = "Hello World";
  my $text2 = "Hi Mom";
  my $pdf = PDF::API2->new();       #dynamic pdf file name
  my $font = $pdf->corefont( 'Times-Roman',   -encoding => 'latin1' );

  my $page = $pdf->page(0);
  $page->mediabox( 612.0, 792.0 ); #8.5" x 11.0" in PostScript points
  my $msg_text = $page->text;
  $msg_text->transform(-translate =>[72, 144]); #x,y position in points
  $msg_text->fillcolor('black');
  $msg_text->font($font, 100);
  $msg_text->text($text1);
  $pdf->saveas($pdf1);

  print "Make 2nd pdf.\n";
  $page = $pdf->page(0); #FAILS!
  {..}
  $msg_text->text($text2);
  $pdf->saveas($pdf2);
  print "2nd pdf created\n";

  $pdf->end();

  1;

2 个答案:

答案 0 :(得分:1)

首次创建Data::Dumper后使用$pdf会显示大量数据:

$VAR1 = bless( {
             'catalog' => bless( { } )
             # Lot lots more, including:
             'pdf' => $VAR1->{'catalog'}{'Pages'}{' outto'}[0],
             # Which is referenced several times, e.g. $self->{pdf}->new_obj(...)
           }, 'PDF::API2' );

调用saveas后,这一切都被移除,导致undefined value错误:

$VAR1 = bless( {}, 'PDF::API2' );

您可以重新创建$pdf

$pdf = PDF::API2->new();

但是您还需要添加所有其他方法调用(corefontsmediaboxtext)。更容易将PDF创建代码放入子:

sub create_pdf {
    my $name = shift;
    my $text = shift;

    my $pdf = PDF::API2->new();
    ....
    $pdf->saveas($name); # also calls end()
}

然后用相关参数调用它两次。

create_pdf($pdf1, $text1);
create_pdf($pdf2, $text2);

完整的工作示例:

#!/usr/bin/perl
use strict;
use warnings;
use PDF::API2;

my $pdf1 = 'hello_world.pdf';
my $pdf2 = 'hi_mom.pdf';
my $text1 = "Hello World";
my $text2 = "Hi Mom";

create_pdf( $pdf1, $text1 );
create_pdf( $pdf2, $text2 );

sub create_pdf {
    my $name = shift;
    my $text = shift;

    my $pdf = PDF::API2->new();       #dynamic pdf file name
    my $font = $pdf->corefont( 'Times-Roman',   -encoding => 'latin1' );

    my $page = $pdf->page(0);
    $page->mediabox( 612.0, 792.0 ); #8.5" x 11.0" in PostScript points
    my $msg_text = $page->text;
    $msg_text->transform(-translate =>[72, 144]); #x,y position in points
    $msg_text->fillcolor('black');
    $msg_text->font($font, 100);
    $msg_text->text($text);
    $pdf->saveas($name);
}

答案 1 :(得分:-2)

if($lineas_pag == 160){  
    $page2 = $pdf->importpage($old, 2);
    $page2->mediabox('Letter');  
    my $msg_text = $page2->text;
    my $font = $pdf->corefont( 'Arial-Bold',   -encoding => 'latin1' );                
    $msg_text->font($font, 8);    
    $txt=  $msg_text;
} 
$txt->translate(96 ,$lineas_pag); $txt->text( " HOLA " );