# Calculate X and Y coordinates inside a loop

Hello,

I am generating barcodes for products stored in MySQL and I am generating a pdf file with all the barcodes on one page. I am using http://www.fpdf.org/ with the Code 128 extension.

Just for reference, this is the pattern I am trying to accomplish http://i.imgur.com/bzIlgda.jpg

Each label has a X and Y coordinate, so based on the current product, I need to calculate them.

Each product information which is on the same row has the same Y.

The example above is done with this code http://pastie.org/9325664

Doing the example manually created a pattern in the values of the YX for each label, but I can’t understand how to calculate them inside a loop.

Basically, after fetching the products from the DB, I will iterate each of them and calculate the coordinates, but I am stuck.

If the question is unclear please reply and I will try to explain the best I can.

Thank you.

You need to know the dimensions of each label (easiest if they are all the same size) and the dimensions of the page (mainly the width). A very basic loop example is below.

``````<?php
\$imgwidth=100;
\$imgheight=25;
\$pagewidth=450;
\$x=0; //Starting point for first image
\$y=0; //Starting point for first image

//Code to Start loop reading from database

//Code to Write out your image

if (\$x >= \$pagewidth) {
\$x=0; //Change 0 to whatever your X coordinate needs to be
}

//Code to End loop reading from database
``````

Thanks for the reply, the problem here is that it automatically creates a pdf file and I have no no control for the styles. The labels are the same size and each one of them has a starting X and Y. My difficulty is finding the X and Y for each of the labels.

Hi dlsmoker, welcome to the forums!

Assuming that you want four barcodes per row, as shown in your example, then you just need to keep track of the row and column position as you add each barcode, incrementing the row counter every time you complete four columns. Something like this should work:

``````
\$row = 1;
\$column = 1;

while (\$product = \$results->fetch()) {
if (\$column == 5) {
\$row++;
\$column = 1;
}

\$column++;
}

{
\$xOffset = 52 * (\$column -1);
\$yOffset = 25 * (\$row -1);

\$pdf->Code128(0 + \$xOffset, 0 + \$yOffset, '123456789', 45, 5);
//
\$pdf->SetXY(0 + \$xOffset, 7 + \$yOffset);
\$pdf->Cell(45,0,'P14 LF 00054651658 AAA',0,1,'C');
// size
\$pdf->SetXY(39 + \$xOffset, 9 + \$yOffset);
\$pdf->Cell(6,3.5,'S',1,0,'C');
//
\$pdf->SetXY(0 + \$xOffset, 6 + \$yOffset);
// category
\$pdf->SetXY(0 + \$xOffset, 13 + \$yOffset);
\$pdf->Cell(10,4,'T-shirts',0,1,'L');
//
\$pdf->SetXY(0 + \$xOffset, 17 + \$yOffset);
\$pdf->Cell(45,5,'DSQUAREED2',0,1,'L');
// price
\$pdf->SetXY(0 + \$xOffset, 17 + \$yOffset);
\$pdf->Cell(45,5,'EUR 89,90',0,1,'R');
}

``````

@fretburner
Thank you for welcoming me and for the help, I will test it out right away.

Edit:
That worked perfectly, can’t thank you enough !