tcpdf_barcodes_2d.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. //============================================================+
  3. // File name : tcpdf_barcodes_2d.php
  4. // Version : 1.0.015
  5. // Begin : 2009-04-07
  6. // Last Update : 2014-05-20
  7. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  8. // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2009-2014 Nicola Asuni - Tecnick.com LTD
  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.015
  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.015
  46. * @author Nicola Asuni
  47. */
  48. class TCPDF2DBarcode {
  49. /**
  50. * Array representation of barcode.
  51. * @protected
  52. */
  53. protected $barcode_array = array();
  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 string $code code to print
  62. * @param string $type 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 parameters 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 int $w Width of a single rectangle element in user units.
  77. * @param int $h Height of a single rectangle element in user units.
  78. * @param string $color 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 int $w Width of a single rectangle element in user units.
  96. * @param int $h Height of a single rectangle element in user units.
  97. * @param string $color 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 int $w Width of a single rectangle element in pixels.
  131. * @param int $h Height of a single rectangle element in pixels.
  132. * @param string $color 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. $html = '<div style="font-size:0;position:relative;width:'.($w * $this->barcode_array['num_cols']).'px;height:'.($h * $this->barcode_array['num_rows']).'px;">'."\n";
  138. // print barcode elements
  139. $y = 0;
  140. // for each row
  141. for ($r = 0; $r < $this->barcode_array['num_rows']; ++$r) {
  142. $x = 0;
  143. // for each column
  144. for ($c = 0; $c < $this->barcode_array['num_cols']; ++$c) {
  145. if ($this->barcode_array['bcode'][$r][$c] == 1) {
  146. // draw a single barcode cell
  147. $html .= '<div style="background-color:'.$color.';width:'.$w.'px;height:'.$h.'px;position:absolute;left:'.$x.'px;top:'.$y.'px;">&nbsp;</div>'."\n";
  148. }
  149. $x += $w;
  150. }
  151. $y += $h;
  152. }
  153. $html .= '</div>'."\n";
  154. return $html;
  155. }
  156. /**
  157. * Send a PNG image representation of barcode (requires GD or Imagick library).
  158. * @param int $w Width of a single rectangle element in pixels.
  159. * @param int $h Height of a single rectangle element in pixels.
  160. * @param array $color RGB (0-255) foreground color for bar elements (background is transparent).
  161. * @public
  162. */
  163. public function getBarcodePNG($w=3, $h=3, $color=array(0,0,0)) {
  164. $data = $this->getBarcodePngData($w, $h, $color);
  165. // send headers
  166. header('Content-Type: image/png');
  167. header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  168. header('Pragma: public');
  169. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  170. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  171. //header('Content-Length: '.strlen($data));
  172. echo $data;
  173. }
  174. /**
  175. * Return a PNG image representation of barcode (requires GD or Imagick library).
  176. * @param int $w Width of a single rectangle element in pixels.
  177. * @param int $h Height of a single rectangle element in pixels.
  178. * @param array $color RGB (0-255) foreground color for bar elements (background is transparent).
  179. * @return string|Imagick|false image or false in case of error.
  180. * @public
  181. */
  182. public function getBarcodePngData($w=3, $h=3, $color=array(0,0,0)) {
  183. // calculate image size
  184. $width = ($this->barcode_array['num_cols'] * $w);
  185. $height = ($this->barcode_array['num_rows'] * $h);
  186. if (function_exists('imagecreate')) {
  187. // GD library
  188. $imagick = false;
  189. $png = imagecreate($width, $height);
  190. $bgcol = imagecolorallocate($png, 255, 255, 255);
  191. imagecolortransparent($png, $bgcol);
  192. $fgcol = imagecolorallocate($png, $color[0], $color[1], $color[2]);
  193. } elseif (extension_loaded('imagick')) {
  194. $imagick = true;
  195. $bgcol = new imagickpixel('rgb(255,255,255');
  196. $fgcol = new imagickpixel('rgb('.$color[0].','.$color[1].','.$color[2].')');
  197. $png = new Imagick();
  198. $png->newImage($width, $height, 'none', 'png');
  199. $bar = new imagickdraw();
  200. $bar->setfillcolor($fgcol);
  201. } else {
  202. return false;
  203. }
  204. // print barcode elements
  205. $y = 0;
  206. // for each row
  207. for ($r = 0; $r < $this->barcode_array['num_rows']; ++$r) {
  208. $x = 0;
  209. // for each column
  210. for ($c = 0; $c < $this->barcode_array['num_cols']; ++$c) {
  211. if ($this->barcode_array['bcode'][$r][$c] == 1) {
  212. // draw a single barcode cell
  213. if ($imagick) {
  214. $bar->rectangle($x, $y, ($x + $w - 1), ($y + $h - 1));
  215. } else {
  216. imagefilledrectangle($png, $x, $y, ($x + $w - 1), ($y + $h - 1), $fgcol);
  217. }
  218. }
  219. $x += $w;
  220. }
  221. $y += $h;
  222. }
  223. if ($imagick) {
  224. $png->drawimage($bar);
  225. return $png;
  226. } else {
  227. ob_start();
  228. imagepng($png);
  229. $imagedata = ob_get_clean();
  230. imagedestroy($png);
  231. return $imagedata;
  232. }
  233. }
  234. /**
  235. * Set the barcode.
  236. * @param string $code code to print
  237. * @param string $type 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 parameters 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>
  238. * @return void
  239. */
  240. public function setBarcode($code, $type) {
  241. $mode = explode(',', $type);
  242. $qrtype = strtoupper($mode[0]);
  243. switch ($qrtype) {
  244. case 'DATAMATRIX': { // DATAMATRIX (ISO/IEC 16022)
  245. require_once(dirname(__FILE__).'/include/barcodes/datamatrix.php');
  246. $qrcode = new Datamatrix($code);
  247. $this->barcode_array = $qrcode->getBarcodeArray();
  248. $this->barcode_array['code'] = $code;
  249. break;
  250. }
  251. case 'PDF417': { // PDF417 (ISO/IEC 15438:2006)
  252. require_once(dirname(__FILE__).'/include/barcodes/pdf417.php');
  253. if (!isset($mode[1]) OR ($mode[1] === '')) {
  254. $aspectratio = 2; // default aspect ratio (width / height)
  255. } else {
  256. $aspectratio = floatval($mode[1]);
  257. }
  258. if (!isset($mode[2]) OR ($mode[2] === '')) {
  259. $ecl = -1; // default error correction level (auto)
  260. } else {
  261. $ecl = intval($mode[2]);
  262. }
  263. // set macro block
  264. $macro = array();
  265. if (isset($mode[3]) AND ($mode[3] !== '') AND isset($mode[4]) AND ($mode[4] !== '') AND isset($mode[5]) AND ($mode[5] !== '')) {
  266. $macro['segment_total'] = intval($mode[3]);
  267. $macro['segment_index'] = intval($mode[4]);
  268. $macro['file_id'] = strtr($mode[5], "\xff", ',');
  269. for ($i = 0; $i < 7; ++$i) {
  270. $o = $i + 6;
  271. if (isset($mode[$o]) AND ($mode[$o] !== '')) {
  272. // add option
  273. $macro['option_'.$i] = strtr($mode[$o], "\xff", ',');
  274. }
  275. }
  276. }
  277. $qrcode = new PDF417($code, $ecl, $aspectratio, $macro);
  278. $this->barcode_array = $qrcode->getBarcodeArray();
  279. $this->barcode_array['code'] = $code;
  280. break;
  281. }
  282. case 'QRCODE': { // QR-CODE
  283. require_once(dirname(__FILE__).'/include/barcodes/qrcode.php');
  284. if (!isset($mode[1]) OR (!in_array($mode[1],array('L','M','Q','H')))) {
  285. $mode[1] = 'L'; // Ddefault: Low error correction
  286. }
  287. $qrcode = new QRcode($code, strtoupper($mode[1]));
  288. $this->barcode_array = $qrcode->getBarcodeArray();
  289. $this->barcode_array['code'] = $code;
  290. break;
  291. }
  292. case 'RAW':
  293. case 'RAW2': { // RAW MODE
  294. // remove spaces
  295. $code = preg_replace('/[\s]*/si', '', $code);
  296. if (strlen($code) < 3) {
  297. break;
  298. }
  299. if ($qrtype == 'RAW') {
  300. // comma-separated rows
  301. $rows = explode(',', $code);
  302. } else { // RAW2
  303. // rows enclosed in square parentheses
  304. $code = substr($code, 1, -1);
  305. $rows = explode('][', $code);
  306. }
  307. $this->barcode_array['num_rows'] = count($rows);
  308. $this->barcode_array['num_cols'] = strlen($rows[0]);
  309. $this->barcode_array['bcode'] = array();
  310. foreach ($rows as $r) {
  311. $this->barcode_array['bcode'][] = str_split($r, 1);
  312. }
  313. $this->barcode_array['code'] = $code;
  314. break;
  315. }
  316. case 'TEST': { // TEST MODE
  317. $this->barcode_array['num_rows'] = 5;
  318. $this->barcode_array['num_cols'] = 15;
  319. $this->barcode_array['bcode'] = array(
  320. array(1,1,1,0,1,1,1,0,1,1,1,0,1,1,1),
  321. array(0,1,0,0,1,0,0,0,1,0,0,0,0,1,0),
  322. array(0,1,0,0,1,1,0,0,1,1,1,0,0,1,0),
  323. array(0,1,0,0,1,0,0,0,0,0,1,0,0,1,0),
  324. array(0,1,0,0,1,1,1,0,1,1,1,0,0,1,0));
  325. $this->barcode_array['code'] = $code;
  326. break;
  327. }
  328. default: {
  329. $this->barcode_array = array();
  330. }
  331. }
  332. }
  333. } // end of class
  334. //============================================================+
  335. // END OF FILE
  336. //============================================================+