BarcodeGeneratorSVG.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 BarcodeGeneratorSVG extends BarcodeGenerator
  9. {
  10. /**
  11. * Return a SVG string representation of barcode.
  12. *
  13. * @param $barcode (string) code to print
  14. * @param $type (const) type of barcode
  15. * @param $widthFactor (int) Minimum width of a single bar in user units.
  16. * @param $height (int) Height of barcode in user units.
  17. * @param $foregroundColor (string) Foreground color (in SVG format) for bar elements (background is transparent).
  18. * @return string SVG code.
  19. * @public
  20. */
  21. public function getBarcode($barcode, $type, int $widthFactor = 2, int $height = 30, string $foregroundColor = 'black')
  22. {
  23. $barcodeData = $this->getBarcodeData($barcode, $type);
  24. // replace table for special characters
  25. $repstr = ["\0" => '', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;'];
  26. $width = round(($barcodeData->getWidth() * $widthFactor), 3);
  27. $svg = '<?xml version="1.0" standalone="no" ?>' . PHP_EOL;
  28. $svg .= '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' . PHP_EOL;
  29. $svg .= '<svg width="' . $width . '" height="' . $height . '" viewBox="0 0 ' . $width . ' ' . $height . '" version="1.1" xmlns="http://www.w3.org/2000/svg">' . PHP_EOL;
  30. $svg .= "\t" . '<desc>' . strtr($barcodeData->getBarcode(), $repstr) . '</desc>' . PHP_EOL;
  31. $svg .= "\t" . '<g id="bars" fill="' . $foregroundColor . '" stroke="none">' . PHP_EOL;
  32. // print bars
  33. $positionHorizontal = 0;
  34. /** @var BarcodeBar $bar */
  35. foreach ($barcodeData->getBars() as $bar) {
  36. $barWidth = round(($bar->getWidth() * $widthFactor), 3);
  37. $barHeight = round(($bar->getHeight() * $height / $barcodeData->getHeight()), 3);
  38. if ($bar->isBar() && $barWidth > 0) {
  39. $positionVertical = round(($bar->getPositionVertical() * $height / $barcodeData->getHeight()), 3);
  40. // draw a vertical bar
  41. $svg .= "\t\t" . '<rect x="' . $positionHorizontal . '" y="' . $positionVertical . '" width="' . $barWidth . '" height="' . $barHeight . '" />' . PHP_EOL;
  42. }
  43. $positionHorizontal += $barWidth;
  44. }
  45. $svg .= "\t</g>" . PHP_EOL;
  46. $svg .= '</svg>' . PHP_EOL;
  47. return $svg;
  48. }
  49. }