2dbarcodes.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. //============================================================+
  3. // File name : 2dbarcodes.php
  4. // Version : 1.0.012
  5. // Begin : 2009-04-07
  6. // Last Update : 2011-09-15
  7. // Author : Nicola Asuni - Tecnick.com S.r.l - Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
  8. // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2009-2011 Nicola Asuni - Tecnick.com S.r.l.
  11. //
  12. // This file is part of TCPDF software library.
  13. //
  14. // TCPDF is free software: you can redistribute it and/or modify it
  15. // under the terms of the GNU Lesser General Public License as
  16. // published by the Free Software Foundation, either version 3 of the
  17. // License, or (at your option) any later version.
  18. //
  19. // TCPDF is distributed in the hope that it will be useful, but
  20. // WITHOUT ANY WARRANTY; without even the implied warranty of
  21. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  22. // See the GNU Lesser General Public License for more details.
  23. //
  24. // You should have received a copy of the GNU Lesser General Public License
  25. // along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
  26. //
  27. // See LICENSE.TXT file for more information.
  28. // -------------------------------------------------------------------
  29. //
  30. // Description : PHP class to creates array representations for
  31. // 2D barcodes to be used with TCPDF.
  32. //
  33. //============================================================+
  34. /**
  35. * @file
  36. * PHP class to creates array representations for 2D barcodes to be used with TCPDF.
  37. * @package com.tecnick.tcpdf
  38. * @author Nicola Asuni
  39. * @version 1.0.012
  40. */
  41. /**
  42. * @class TCPDF2DBarcode
  43. * PHP class to creates array representations for 2D barcodes to be used with TCPDF (http://www.tcpdf.org).
  44. * @package com.tecnick.tcpdf
  45. * @version 1.0.012
  46. * @author Nicola Asuni
  47. */
  48. class TCPDF2DBarcode {
  49. /**
  50. * Array representation of barcode.
  51. * @protected
  52. */
  53. protected $barcode_array = false;
  54. /**
  55. * This is the class constructor.
  56. * Return an array representations for 2D barcodes:<ul>
  57. * <li>$arrcode['code'] code to be printed on text label</li>
  58. * <li>$arrcode['num_rows'] required number of rows</li>
  59. * <li>$arrcode['num_cols'] required number of columns</li>
  60. * <li>$arrcode['bcode'][$r][$c] value of the cell is $r row and $c column (0 = transparent, 1 = black)</li></ul>
  61. * @param $code (string) code to print
  62. * @param $type (string) type of barcode: <ul><li>DATAMATRIX : Datamatrix (ISO/IEC 16022)</li><li>PDF417 : PDF417 (ISO/IEC 15438:2006)</li><li>PDF417,a,e,t,s,f,o0,o1,o2,o3,o4,o5,o6 : PDF417 with parameters: a = aspect ratio (width/height); e = error correction level (0-8); t = total number of macro segments; s = macro segment index (0-99998); f = file ID; o0 = File Name (text); o1 = Segment Count (numeric); o2 = Time Stamp (numeric); o3 = Sender (text); o4 = Addressee (text); o5 = File Size (numeric); o6 = Checksum (numeric). NOTES: Parameters t, s and f are required for a Macro Control Block, all other parametrs are optional. To use a comma character ',' on text options, replace it with the character 255: "\xff".</li><li>QRCODE : QRcode Low error correction</li><li>QRCODE,L : QRcode Low error correction</li><li>QRCODE,M : QRcode Medium error correction</li><li>QRCODE,Q : QRcode Better error correction</li><li>QRCODE,H : QR-CODE Best error correction</li><li>RAW: raw mode - comma-separad list of array rows</li><li>RAW2: raw mode - array rows are surrounded by square parenthesis.</li><li>TEST : Test matrix</li></ul>
  63. */
  64. public function __construct($code, $type) {
  65. $this->setBarcode($code, $type);
  66. }
  67. /**
  68. * Return an array representations of barcode.
  69. * @return array
  70. */
  71. public function getBarcodeArray() {
  72. return $this->barcode_array;
  73. }
  74. /**
  75. * Send barcode as SVG image object to the standard output.
  76. * @param $w (int) Width of a single rectangle element in user units.
  77. * @param $h (int) Height of a single rectangle element in user units.
  78. * @param $color (string) Foreground color (in SVG format) for bar elements (background is transparent).
  79. * @public
  80. */
  81. public function getBarcodeSVG($w=3, $h=3, $color='black') {
  82. // send headers
  83. $code = $this->getBarcodeSVGcode($w, $h, $color);
  84. header('Content-Type: application/svg+xml');
  85. header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  86. header('Pragma: public');
  87. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  88. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  89. header('Content-Disposition: inline; filename="'.md5($code).'.svg";');
  90. //header('Content-Length: '.strlen($code));
  91. echo $code;
  92. }
  93. /**
  94. * Return a SVG string representation of barcode.
  95. * @param $w (int) Width of a single rectangle element in user units.
  96. * @param $h (int) Height of a single rectangle element in user units.
  97. * @param $color (string) Foreground color (in SVG format) for bar elements (background is transparent).
  98. * @return string SVG code.
  99. * @public
  100. */
  101. public function getBarcodeSVGcode($w=3, $h=3, $color='black') {
  102. // replace table for special characters
  103. $repstr = array("\0" => '', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;');
  104. $svg = '<'.'?'.'xml version="1.0" standalone="no"'.'?'.'>'."\n";
  105. $svg .= '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'."\n";
  106. $svg .= '<svg width="'.round(($this->barcode_array['num_cols'] * $w), 3).'" height="'.round(($this->barcode_array['num_rows'] * $h), 3).'" version="1.1" xmlns="http://www.w3.org/2000/svg">'."\n";
  107. $svg .= "\t".'<desc>'.strtr($this->barcode_array['code'], $repstr).'</desc>'."\n";
  108. $svg .= "\t".'<g id="elements" fill="'.$color.'" stroke="none">'."\n";
  109. // print barcode elements
  110. $y = 0;
  111. // for each row
  112. for ($r = 0; $r < $this->barcode_array['num_rows']; ++$r) {
  113. $x = 0;
  114. // for each column
  115. for ($c = 0; $c < $this->barcode_array['num_cols']; ++$c) {
  116. if ($this->barcode_array['bcode'][$r][$c] == 1) {
  117. // draw a single barcode cell
  118. $svg .= "\t\t".'<rect x="'.$x.'" y="'.$y.'" width="'.$w.'" height="'.$h.'" />'."\n";
  119. }
  120. $x += $w;
  121. }
  122. $y += $h;
  123. }
  124. $svg .= "\t".'</g>'."\n";
  125. $svg .= '</svg>'."\n";
  126. return $svg;
  127. }
  128. /**
  129. * Return an HTML representation of barcode.
  130. * @param $w (int) Width of a single rectangle element in pixels.
  131. * @param $h (int) Height of a single rectangle element in pixels.
  132. * @param $color (string) Foreground color for bar elements (background is transparent).
  133. * @return string HTML code.
  134. * @public
  135. */
  136. public function getBarcodeHTML($w=10, $h=10, $color='black') {
  137. // replace table for special characters
  138. $html = '<div style="font-size:0;position:relative;">'."\n";
  139. // print barcode elements
  140. $y = 0;
  141. // for each row
  142. for ($r = 0; $r < $this->barcode_array['num_rows']; ++$r) {
  143. $x = 0;
  144. // for each column
  145. for ($c = 0; $c < $this->barcode_array['num_cols']; ++$c) {
  146. if ($this->barcode_array['bcode'][$r][$c] == 1) {
  147. // draw a single barcode cell
  148. $html .= '<div style="background-color:'.$color.';width:'.$w.'px;height:'.$h.'px;position:absolute;left:'.$x.'px;top:'.$y.'px;">&nbsp;</div>'."\n";
  149. }
  150. $x += $w;
  151. }
  152. $y += $h;
  153. }
  154. $html .= '</div>'."\n";
  155. return $html;
  156. }
  157. /**
  158. * Return a PNG image representation of barcode (requires GD or Imagick library).
  159. * @param $w (int) Width of a single rectangle element in pixels.
  160. * @param $h (int) Height of a single rectangle element in pixels.
  161. * @param $color (array) RGB (0-255) foreground color for bar elements (background is transparent).
  162. * @return image or false in case of error.
  163. * @public
  164. */
  165. public function getBarcodePNG($w=3, $h=3, $color=array(0,0,0)) {
  166. // calculate image size
  167. $width = ($this->barcode_array['num_cols'] * $w);
  168. $height = ($this->barcode_array['num_rows'] * $h);
  169. if (function_exists('imagecreate')) {
  170. // GD library
  171. $imagick = false;
  172. $png = imagecreate($width, $height);
  173. $bgcol = imagecolorallocate($png, 255, 255, 255);
  174. imagecolortransparent($png, $bgcol);
  175. $fgcol = imagecolorallocate($png, $color[0], $color[1], $color[2]);
  176. } elseif (extension_loaded('imagick')) {
  177. $imagick = true;
  178. $bgcol = new imagickpixel('rgb(255,255,255');
  179. $fgcol = new imagickpixel('rgb('.$color[0].','.$color[1].','.$color[2].')');
  180. $png = new Imagick();
  181. $png->newImage($width, $height, 'none', 'png');
  182. $bar = new imagickdraw();
  183. $bar->setfillcolor($fgcol);
  184. } else {
  185. return false;
  186. }
  187. // print barcode elements
  188. $y = 0;
  189. // for each row
  190. for ($r = 0; $r < $this->barcode_array['num_rows']; ++$r) {
  191. $x = 0;
  192. // for each column
  193. for ($c = 0; $c < $this->barcode_array['num_cols']; ++$c) {
  194. if ($this->barcode_array['bcode'][$r][$c] == 1) {
  195. // draw a single barcode cell
  196. if ($imagick) {
  197. $bar->rectangle($x, $y, ($x + $w), ($y + $h));
  198. } else {
  199. imagefilledrectangle($png, $x, $y, ($x + $w), ($y + $h), $fgcol);
  200. }
  201. }
  202. $x += $w;
  203. }
  204. $y += $h;
  205. }
  206. // send headers
  207. header('Content-Type: image/png');
  208. header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  209. header('Pragma: public');
  210. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  211. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  212. if ($imagick) {
  213. $png->drawimage($bar);
  214. echo $png;
  215. } else {
  216. imagepng($png);
  217. imagedestroy($png);
  218. }
  219. }
  220. /**
  221. * Set the barcode.
  222. * @param $code (string) code to print
  223. * @param $type (string) type of barcode: <ul><li>DATAMATRIX : Datamatrix (ISO/IEC 16022)</li><li>PDF417 : PDF417 (ISO/IEC 15438:2006)</li><li>PDF417,a,e,t,s,f,o0,o1,o2,o3,o4,o5,o6 : PDF417 with parameters: a = aspect ratio (width/height); e = error correction level (0-8); t = total number of macro segments; s = macro segment index (0-99998); f = file ID; o0 = File Name (text); o1 = Segment Count (numeric); o2 = Time Stamp (numeric); o3 = Sender (text); o4 = Addressee (text); o5 = File Size (numeric); o6 = Checksum (numeric). NOTES: Parameters t, s and f are required for a Macro Control Block, all other parametrs are optional. To use a comma character ',' on text options, replace it with the character 255: "\xff".</li><li>QRCODE : QRcode Low error correction</li><li>QRCODE,L : QRcode Low error correction</li><li>QRCODE,M : QRcode Medium error correction</li><li>QRCODE,Q : QRcode Better error correction</li><li>QRCODE,H : QR-CODE Best error correction</li><li>RAW: raw mode - comma-separad list of array rows</li><li>RAW2: raw mode - array rows are surrounded by square parenthesis.</li><li>TEST : Test matrix</li></ul>
  224. * @return array
  225. */
  226. public function setBarcode($code, $type) {
  227. $mode = explode(',', $type);
  228. $qrtype = strtoupper($mode[0]);
  229. switch ($qrtype) {
  230. case 'DATAMATRIX': { // DATAMATRIX (ISO/IEC 16022)
  231. require_once(dirname(__FILE__).'/datamatrix.php');
  232. $qrcode = new Datamatrix($code);
  233. $this->barcode_array = $qrcode->getBarcodeArray();
  234. $this->barcode_array['code'] = $code;
  235. break;
  236. }
  237. case 'PDF417': { // PDF417 (ISO/IEC 15438:2006)
  238. require_once(dirname(__FILE__).'/pdf417.php');
  239. if (!isset($mode[1]) OR ($mode[1] === '')) {
  240. $aspectratio = 2; // default aspect ratio (width / height)
  241. } else {
  242. $aspectratio = floatval($mode[1]);
  243. }
  244. if (!isset($mode[2]) OR ($mode[2] === '')) {
  245. $ecl = -1; // default error correction level (auto)
  246. } else {
  247. $ecl = intval($mode[2]);
  248. }
  249. // set macro block
  250. $macro = array();
  251. if (isset($mode[3]) AND ($mode[3] !== '') AND isset($mode[4]) AND ($mode[4] !== '') AND isset($mode[5]) AND ($mode[5] !== '')) {
  252. $macro['segment_total'] = intval($mode[3]);
  253. $macro['segment_index'] = intval($mode[4]);
  254. $macro['file_id'] = strtr($mode[5], "\xff", ',');
  255. for ($i = 0; $i < 7; ++$i) {
  256. $o = $i + 6;
  257. if (isset($mode[$o]) AND ($mode[$o] !== '')) {
  258. // add option
  259. $macro['option_'.$i] = strtr($mode[$o], "\xff", ',');
  260. }
  261. }
  262. }
  263. $qrcode = new PDF417($code, $ecl, $aspectratio, $macro);
  264. $this->barcode_array = $qrcode->getBarcodeArray();
  265. $this->barcode_array['code'] = $code;
  266. break;
  267. }
  268. case 'QRCODE': { // QR-CODE
  269. require_once(dirname(__FILE__).'/qrcode.php');
  270. if (!isset($mode[1]) OR (!in_array($mode[1],array('L','M','Q','H')))) {
  271. $mode[1] = 'L'; // Ddefault: Low error correction
  272. }
  273. $qrcode = new QRcode($code, strtoupper($mode[1]));
  274. $this->barcode_array = $qrcode->getBarcodeArray();
  275. $this->barcode_array['code'] = $code;
  276. break;
  277. }
  278. case 'RAW':
  279. case 'RAW2': { // RAW MODE
  280. // remove spaces
  281. $code = preg_replace('/[\s]*/si', '', $code);
  282. if (strlen($code) < 3) {
  283. break;
  284. }
  285. if ($qrtype == 'RAW') {
  286. // comma-separated rows
  287. $rows = explode(',', $code);
  288. } else { // RAW2
  289. // rows enclosed in square parentheses
  290. $code = substr($code, 1, -1);
  291. $rows = explode('][', $code);
  292. }
  293. $this->barcode_array['num_rows'] = count($rows);
  294. $this->barcode_array['num_cols'] = strlen($rows[0]);
  295. $this->barcode_array['bcode'] = array();
  296. foreach ($rows as $r) {
  297. $this->barcode_array['bcode'][] = str_split($r, 1);
  298. }
  299. $this->barcode_array['code'] = $code;
  300. break;
  301. }
  302. case 'TEST': { // TEST MODE
  303. $this->barcode_array['num_rows'] = 5;
  304. $this->barcode_array['num_cols'] = 15;
  305. $this->barcode_array['bcode'] = array(
  306. array(1,1,1,0,1,1,1,0,1,1,1,0,1,1,1),
  307. array(0,1,0,0,1,0,0,0,1,0,0,0,0,1,0),
  308. array(0,1,0,0,1,1,0,0,1,1,1,0,0,1,0),
  309. array(0,1,0,0,1,0,0,0,0,0,1,0,0,1,0),
  310. array(0,1,0,0,1,1,1,0,1,1,1,0,0,1,0));
  311. $this->barcode_array['code'] = $code;
  312. break;
  313. }
  314. default: {
  315. $this->barcode_array = false;
  316. }
  317. }
  318. }
  319. } // end of class
  320. //============================================================+
  321. // END OF FILE
  322. //============================================================+