Created
October 10, 2020 09:43
-
-
Save enovision/5c547d0d2be1bb4520f72a738d76aba7 to your computer and use it in GitHub Desktop.
ZPL dpi converter for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* author: Tres Finocchiaro transposed to PHP by Johan van de Merwe | |
* date: 2020-08-10 | |
* license: Public Domain; Use as you wish. | |
* source: http://qz.io | |
* | |
* usage: | |
* | |
* $data = '^XA...your zpl data.. XZ'; | |
* $zplconverter = new ZebraDPIConverter(203, 300); | |
* $zplconverter->setSource($data, 'string'); // when a string is used | |
* /* or */ | |
* /* $zplconverter->setSource($path, 'path'); // when a path to your zpl template is used */ | |
* $data = $zplconverter->scale(); | |
* | |
*/ | |
namespace ZebraConverter; | |
class ZebraDPIConverter | |
{ | |
private $baseDPI; | |
private $targetDPI; | |
private $sourceData; | |
private $scaleFactor = 1; | |
private static $cmds = ['FT', 'FO', 'A0', 'A@', 'LL', 'LH', 'GB', 'FB', 'BY', 'B3']; | |
function __construct($baseDPI = 203, $targetDPI = 300, $source = null, $type = null) | |
{ | |
$this->baseDPI = intval($baseDPI); | |
$this->targetDPI = intval($targetDPI); | |
$this->scaleFactor = $this->targetDPI / $this->baseDPI; | |
if ($source !== null) { | |
$this->setSource($source, $type); | |
} | |
return $this; | |
} | |
public function setSource($source, $type = 'string') | |
{ | |
if (in_array(strtolower($type), ['string', 'text', 'data'])) { | |
$this->sourceData = $source; | |
} else if (in_array(strtolower($type), ['file', 'path'])) { | |
$this->loadSourceFromPath($source); | |
} | |
return $this; | |
} | |
public function loadSourceFromPath($path) | |
{ | |
if (file_exists($path)) { | |
$this->sourceData = file_get_contents($path); | |
} else { | |
$this->sourceData = 'File not found in path : ' . $path; | |
} | |
return $this; | |
} | |
/* | |
* Scales text from a raw ZPL label from 203 DPI to 300 DPI | |
*/ | |
function scale() | |
{ | |
$sections = explode('^', $this->sourceData); | |
foreach (self::$cmds as $cmd) { | |
foreach ($sections as $idx => $section) { | |
if (substr($section, 0, strlen($cmd)) === $cmd) { | |
$sections[$idx] = $this->scaleSection($cmd, $section); | |
} | |
} | |
} | |
return implode('^', $sections); | |
} | |
/* | |
* Scales all integers found in a designated section | |
*/ | |
function scaleSection($cmd, $section) | |
{ | |
$section = substr($section, strlen($cmd), strlen($section)); | |
$parts = explode(',', $section); | |
foreach ($parts as $idx => $part) { | |
if (is_numeric($part)) { | |
$parts[$idx] = round($this->scaleFactor * intval($part)); | |
} | |
} | |
return $cmd . implode(',', $parts); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment