BarcodeGeneratorHTML.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\librarys\Picqer\Barcode;
  8. class BarcodeGeneratorHTML extends BarcodeGenerator
  9. {
  10. /**
  11. * Return an HTML representation of barcode.
  12. * This original version uses pixel based widths and heights. Use Dynamic HTML version for better quality representation.
  13. *
  14. * @param string $barcode code to print
  15. * @param string $type type of barcode
  16. * @param int $widthFactor Width of a single bar element in pixels.
  17. * @param int $height Height of a single bar element in pixels.
  18. * @param string $foregroundColor Foreground color for bar elements as '#333' or 'orange' for example (background is transparent).
  19. * @return string HTML code.
  20. */
  21. public function getBarcode($barcode, $type, int $widthFactor = 2, int $height = 30, string $foregroundColor = 'black')
  22. {
  23. $barcodeData = $this->getBarcodeData($barcode, $type);
  24. $html = '<div style="font-size:0;position:relative;width:' . ($barcodeData->getWidth() * $widthFactor) . 'px;height:' . ($height) . 'px;">' . PHP_EOL;
  25. $positionHorizontal = 0;
  26. /** @var BarcodeBar $bar */
  27. foreach ($barcodeData->getBars() as $bar) {
  28. $barWidth = round(($bar->getWidth() * $widthFactor), 3);
  29. $barHeight = round(($bar->getHeight() * $height / $barcodeData->getHeight()), 3);
  30. if ($bar->isBar() && $barWidth > 0) {
  31. $positionVertical = round(($bar->getPositionVertical() * $height / $barcodeData->getHeight()), 3);
  32. // draw a vertical bar
  33. $html .= '<div style="background-color:' . $foregroundColor . ';width:' . $barWidth . 'px;height:' . $barHeight . 'px;position:absolute;left:' . $positionHorizontal . 'px;top:' . $positionVertical . (($positionVertical > 0) ? 'px' : '') . '">&nbsp;</div>' . PHP_EOL;
  34. }
  35. $positionHorizontal += $barWidth;
  36. }
  37. $html .= '</div>' . PHP_EOL;
  38. return $html;
  39. }
  40. }