- Perl ›
- Form creation ›
- here
Insert image - PDF::Create form with API2
I will explain how to insert PNG, GIF, JPEG images with PDF::API2.
The PDF can contain images. PDF::API2 allows you to insert PNG, GIF, JPEG images into PDF.
Insert image file
To insert an image file, you must first read the image file and create a resource object to represent the image.
Reading image files
Let's read the image file and generate a resource object to represent the image.
Reading JPEG files
To read a JPEG file with PDF::API2, use the image_jpeg method. Returns a resource object that represents the JPEG image.
# Generate a resource object that represents a JPEG image my $image_file = '/path/image.jpeg'; my $image_object = $pdf->image_jpeg($image_file);
Reading PNG files
To read a PNG file in PDF::API2, use the image_png method. Returns a resource object that represents the PNG image.
# Create a resource object that represents a PNG image my $image_file = '/path/image.png'; my $image_object = $pdf->image_png($image_file);
If you get the error "Unsupported Interlace", you need to turn off the PNG interlacing feature.
Reading GIF files
In PDF::API2, use the image_gif method to read a GIF file. Returns a resource object that represents the GIF image.
# Create a resource object that represents a GIF image my $image_file = '/path/image.gif'; my $image_object = $pdf->image_gif($image_file);
Generation of image content object
Create a content object to insert the image. This is a PDF::API2::Content object.
# Content object needed to insert an image my $gfx = $page->gfx;
Insert image file
In PDF::API2, use the image method of the content object to insert an image file.
# Insert image at specified position $gfx->image($image_object, $x, $y); # Insert image at the specified position. Specify width and height $gfx->image($image_object, $x, $y, $width, $height); # Insert image at the specified position. Specify scale (1.5x, etc.) $gfx->image($image_object, $x, $y, $scale);
The image will be inserted at the specified position.
Note that the width and height are in PDF units. Note that the coordinates move toward the upper right, so they are drawn in the upper right when viewed from the specified point.
As an example, if you want to display a 600x600 image at 600dpi resolution, specify 72.
Example to insert PNG image
Let's write an example to insert a PNG image.
use PDF::API2; my $pdf = PDF::API2->new; my $page = $pdf->page; # Create a resource object that represents a PNG image my $image_file = "$FindBin::Bin/rokkaku.png"; my $image_object = $pdf->image_png($image_file); # Content object needed to insert an image my $gfx = $page->gfx; # Insert image at specified position my $x = 50; my $y = 500; $gfx->image($image_object, $x, $y); my $pdf_file = 'image_png.pdf'; $pdf->saveas($pdf_file);