Adding Images

PHP provides us with two functions for using images in PDFs : pdf_open_image_file() and pdf_place_image(). The former reads a specified image type (parameter two) of a specified file name (parameter three) and returns an image that can be used in subsequent functions.

The pdf_place_image() function then takes the returned image as its second parameter, and also allows you to specify the X coordinate (parameter three), Y coordinate (parameter four), and any scaling (parameter five) you wish to be applied to the image.

For this next example, you will need to find a JPEG, name it myimage.jpg, and place it in the same directory as the script before you run the script.

    $pdf = pdf_new();
    pdf_open_file($pdf, "/path/to/your.pdf");
    pdf_begin_page($pdf, 595, 842);

    $testimage = pdf_open_image_file($pdf, "jpeg", "myimage.jpg");
    pdf_place_image($pdf, $testimage, 0, 0, 0.5);
    pdf_end_page($pdf);
    pdf_close($pdf);
    pdf_delete($pdf);

In the above example, we set the scale parameter of pdf_place_image() (parameter five) to 0.5, which will show our myimage.jpg picture at half its original size. Note that altering the scale value of pictures will not change the final file size of the PDF that you output, because the file is saved unscaled and then scaled at run-time.

Owing to its saving pictures unscaled, the PDF format allows you to reuse images without having to store multiple copies in the file. So, if we go back to our earlier for loop where we had 10 pages being generated, we get something ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.