Madhan
Madhan

Reputation: 1321

Insert JPEG image in PDF using perl PDF::Create

I am trying to insert a JPEG image in PDF file using perl program. I am using the PDF::Create module.

I have tried with PDF::Image::JPEG module, which results "Can't call method "image" on an undefined value at ./PDF_IMG.pl"

Could anyone please assist/advise to add the image in PDF using PDF::Create or PDF::Image::JPEG.

The below is the code snippet I am using.

use strict;
use Data::Dumper;
use PDF::Create;
use PDF::Image::JPEG;

print "PDF with Image\n";

#Create
my $pdf = new PDF::Create('filename' => "./image_embed_test.pdf",
                             'Version'  => 1.2,
                             'PageMode' => 'UseNone',
                             'Author'   => 'Madhan',
                             'Title'    => 'My PDF',
                         );

   # Prepare 2 fonts
  my $f1 = $pdf->font('Subtype'  => 'Type1',
                        'Encoding' => 'WinAnsiEncoding',
                        'BaseFont' => 'Helvetica');
  my $f2 = $pdf->font('Subtype'  => 'Type1',
                        'Encoding' => 'WinAnsiEncoding',
                        'BaseFont' => 'Helvetica-Bold');



my $root = $pdf->new_page('MediaBox' => [ 0, 0, 612, 792 ]);

my @page;
$page[1]=$root->new_page;

$page[1]->stringc($f2, 8, 306, 738, "My First Page");

my $image1 = new PDF::Image::JPEG('./logo1.jpg');
$page[2]->image($image1, 100, 100, 1, 2, 1.0, 1.0 ,0, 0, 0);

$pdf->close;

Upvotes: 3

Views: 1144

Answers (1)

xxfelixxx
xxfelixxx

Reputation: 6592

There are 2 issues with your code:

  1. $page[2] is not defined, you need to run $root->new_page() again.
  2. the image method takes key value pairs, not ordered arguments.

Here is an updated version which should work:

use warnings;
use strict;

use PDF::Create;
use PDF::Image::JPEG;

print "PDF with Image\n";

#Create
my $pdf = new PDF::Create(
    'filename' => "./image_embed_test.pdf",
    'Version'  => 1.2,
    'PageMode' => 'UseNone',
    'Author'   => 'Madhan',
    'Title'    => 'My PDF',
);

# Prepare 2 fonts
my $f1 = $pdf->font('Subtype'  => 'Type1',
                    'Encoding' => 'WinAnsiEncoding',
                    'BaseFont' => 'Helvetica');

my $f2 = $pdf->font('Subtype'  => 'Type1',
                    'Encoding' => 'WinAnsiEncoding',
                    'BaseFont' => 'Helvetica-Bold');

my $root = $pdf->new_page('MediaBox' => [ 0, 0, 612, 792 ]);

my @page;
$page[1]=$root->new_page;
$page[1]->stringc($f2, 8, 306, 738, "My First Page");

$page[2]=$root->new_page;
my $jpg1 = $pdf->image('./logo1.jpg');
$page[2]->image( 'image'  => $jpg1, 
                 'xscale' => 0.2, 
                 'yscale' => 0.2, 
                 'xpos'   => 350,
                 'ypos'   => 400 );

$pdf->close;

perldoc PDF::Create::Page image()

Upvotes: 3

Related Questions