Print (generate) a code128 barcode (or any image) in millimeters (php)

Gringo picture Gringo · Feb 8, 2013 · Viewed 10.8k times · Source

I need to generate labels with code128 barcodes in PHP. These will be printed by users with almost any printer.

I have some specific sets of requirements:

  • narrow bar width should be between 0.375mm and 0.5mm

  • maximum overall barcode width: 115mm

  • first 8 digits must use subset B
  • remaining 20 digits must use subset C
  • code must be readable at high speeds

I tried several barcode libraries but most of them don't allow stating the minimum bar width in millimeters. You are just able to scale the narrow bar width in fixed integer increments, and 1 is too small and 2 is too big :)

I also tried resampling the image using the gd lib, but the code becomes unreadable at high speeds.

Should I build my own code generator? If so, how would I generate the bars in millimeters?

Thanks in advance

Answer

Gringo picture Gringo · Feb 22, 2013

Ok, I believe I found a solution that applies not to every browser and printer combination, but it suits me nicely.

I am using the barodegen php library found at barcodegen because it is the only one allowing me to specify a subset for some characters and another one for others.

In my specific problem, I can do this:

$setB = '%'.substr($vars->code, 0, 7);
$setC = substr($vars->code, 7);

$code_array = array(array(CODE128_B, $setB), array(CODE128_C, $setC));

And then parse $code_array into a barcode.

Now, the other problem is also simply solved by setting the point per inch of the generated barcode image. This is called, wrongly I think, DPI. Correct me if I'm mistaken, but DPI is a harware characteristic of a printer. You can't change that. PPI on the other hand, you can change.

In my problem I had a 244px wide image, and I needed it to print in more than 95mm. barcodegen allows you to do this by calling

$drawing->setDPI(64);
// I do think they should rename this to setPPI

Now, after you have a 224px image with 64ppi, all you need to do is show it in an img tag like this:

<img style="width: 96.8375mm;" src="interlink_code128_barcode.php?code='.$code128.'" border="0">

the 96.8375mm is obtained by solving the simple equation, if the image contains 64 pixels in one inch, how much inches will occupy 244 pixels? And then you transform inches to mm

I haven't got confirmation that the barcodes can be read at high speeds, but I do see the printouts looking sharp! :D