Calculate X and Y coordinates inside a loop


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 with the Code 128 extension.

Just for reference, this is the pattern I am trying to accomplish

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

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.

$x=0; //Starting point for first image
$xpad=10; //Padding between images
$y=0; //Starting point for first image
$ypad=10; //Padding between rows

//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) {
		$column = 1;

	add_barcode($product, $pdf, $row, $column);

function add_barcode($product, $pdf, $row, $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->SetXY(0 + $xOffset, 6 + $yOffset);
	// category
	$pdf->SetXY(0 + $xOffset, 13 + $yOffset);
	$pdf->SetXY(0 + $xOffset, 17 + $yOffset);
	// price
	$pdf->SetXY(0 + $xOffset, 17 + $yOffset);
	$pdf->Cell(45,5,'EUR 89,90',0,1,'R');

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

That worked perfectly, can’t thank you enough !