Skip to content
Advertisement

PDFlib PHP place images next to each other

I have multiple Images coming from an array (could be 3, could be 10) and I want to place them next to each other and if they don’t fit anymore, place them in a new line.

I have written a foreach statement and I got it to work, so that they place into a new line if they don’t fit in the current one and they also place next to each other.

But my problem is the spacing between the images, because as of now it’s different for each image. Some have really wide space between them while others are overlapping.

Here’s the function I wrote:

function createAwardsTable(pdflib $p, int $textStartLeft, array $arrInput) {
    $awardImages = $arrInput['awards'];

    $boxHeight = 50;
    $x = $textStartLeft;
    $y = 275;

    foreach($awardImages as $awardImage) {
        $image = $p->load_image("auto", $awardImage, "");
        if ($image == 0) {
            echo("Couldn't load $image: " . $p->get_errmsg());
            exit(1);
        }

        $imagewidth = $p->info_image($image, "imagewidth", "");

        if ($x > (565 - 20)) {
            $y = 215;
            $x = $textStartLeft;
        }

        $buf =  "boxsize={" . $imagewidth . " " . $boxHeight . "} fitmethod=auto matchbox={name=awardimage}";
        // $buf = "scale=1 matchbox={name=awardimage}";
        $p->fit_image($image, $x, $y, $buf);

        $awardWidth = $p->info_matchbox("awardimage", 1, "x2");
        $x = ($x - 20) + $awardWidth;
    }
}

And here’s a picture of the result I get in my pdf: outcome in pdf

Advertisement

Answer

I think your logic is fine so far.

    $awardWidth = $p->info_matchbox("awardimage", 1, "x2");
    $x = ($x - 20) + $awardWidth;

i think the new calculation of $x is just not quite right. If I understand your description correctly, then you simply want to output the next award image 20 pixels next to the previously placed image. If that’s the case, then it’s enough to use the matchbox to get the position of the placed image and then just add 20 px on top of it.

    $awardX2 = $p->info_matchbox("awardimage", 1, "x2");
    $x = $awardX2 + 20;

Maybe the problem also comes from the wrong name of $awardWidth. Info_matchbox() Returns you the X-position and not the width. If you want the width, then you should also get the x1 position and then calculate the difference. $width = $x2-$x1)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement