BarcodeGeneratorDynamicHTML.php 1.9 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 BarcodeGeneratorDynamicHTML extends BarcodeGenerator
  9. {
  10. private const WIDTH_PRECISION = 6;
  11. /**
  12. * Return an HTML representation of barcode.
  13. * This 'dynamic' version uses percentage based widths and heights, resulting in a vector-y qualitative result.
  14. *
  15. * @param string $barcode code to print
  16. * @param string $type type of barcode
  17. * @param string $foregroundColor Foreground color for bar elements as '#333' or 'orange' for example (background is transparent).
  18. * @return string HTML code.
  19. */
  20. public function getBarcode($barcode, $type, string $foregroundColor = 'black')
  21. {
  22. $barcodeData = $this->getBarcodeData($barcode, $type);
  23. $html = '<div style="font-size:0;position:relative;width:100%;height:100%">' . PHP_EOL;
  24. $positionHorizontal = 0;
  25. /** @var BarcodeBar $bar */
  26. foreach ($barcodeData->getBars() as $bar) {
  27. $barWidth = $bar->getWidth() / $barcodeData->getWidth() * 100;
  28. $barHeight = round(($bar->getHeight() / $barcodeData->getHeight() * 100), 3);
  29. if ($bar->isBar() && $barWidth > 0) {
  30. $positionVertical = round(($bar->getPositionVertical() / $barcodeData->getHeight() * 100), 3);
  31. // draw a vertical bar
  32. $html .= '<div style="background-color:' . $foregroundColor . ';width:' . round($barWidth, self::WIDTH_PRECISION) . '%;height:' . $barHeight . '%;position:absolute;left:' . round($positionHorizontal, self::WIDTH_PRECISION) . '%;top:' . $positionVertical . (($positionVertical > 0) ? '%' : '') . '">&nbsp;</div>' . PHP_EOL;
  33. }
  34. $positionHorizontal += $barWidth;
  35. }
  36. $html .= '</div>' . PHP_EOL;
  37. return $html;
  38. }
  39. }