|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Picqer\Barcode\Renderers; |
| 4 | + |
| 5 | +use Picqer\Barcode\Barcode; |
| 6 | +use Picqer\Barcode\BarcodeBar; |
| 7 | + |
| 8 | +class SvgRenderer |
| 9 | +{ |
| 10 | + protected string $foregroundColor = 'black'; |
| 11 | + |
| 12 | + public function render(Barcode $barcode, float $width = 200, float $height = 30): string |
| 13 | + { |
| 14 | + // replace table for special characters |
| 15 | + $repstr = [ |
| 16 | + "\0" => '', |
| 17 | + '&' => '&', |
| 18 | + '<' => '<', |
| 19 | + '>' => '>', |
| 20 | + ]; |
| 21 | + |
| 22 | +// $width = round(($barcode->getWidth() * $widthFactor), 3); |
| 23 | + $widthFactor = $width / $barcode->getWidth(); |
| 24 | + |
| 25 | + $svg = '<?xml version="1.0" standalone="no" ?>' . PHP_EOL; |
| 26 | + $svg .= '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' . PHP_EOL; |
| 27 | + $svg .= '<svg width="' . $width . '" height="' . $height . '" viewBox="0 0 ' . $width . ' ' . $height . '" version="1.1" xmlns="http://www.w3.org/2000/svg">' . PHP_EOL; |
| 28 | + $svg .= "\t" . '<desc>' . strtr($barcode->getBarcode(), $repstr) . '</desc>' . PHP_EOL; |
| 29 | + $svg .= "\t" . '<g id="bars" fill="' . $this->foregroundColor . '" stroke="none">' . PHP_EOL; |
| 30 | + |
| 31 | + // print bars |
| 32 | + $positionHorizontal = 0; |
| 33 | + /** @var BarcodeBar $bar */ |
| 34 | + foreach ($barcode->getBars() as $bar) { |
| 35 | + $barWidth = round(($bar->getWidth() * $widthFactor), 3); |
| 36 | + $barHeight = round(($bar->getHeight() * $height / $barcode->getHeight()), 3); |
| 37 | + |
| 38 | + if ($bar->isBar() && $barWidth > 0) { |
| 39 | + $positionVertical = round(($bar->getPositionVertical() * $height / $barcode->getHeight()), 3); |
| 40 | + // draw a vertical bar |
| 41 | + $svg .= "\t\t" . '<rect x="' . $positionHorizontal . '" y="' . $positionVertical . '" width="' . $barWidth . '" height="' . $barHeight . '" />' . PHP_EOL; |
| 42 | + } |
| 43 | + |
| 44 | + $positionHorizontal += $barWidth; |
| 45 | + } |
| 46 | + |
| 47 | + $svg .= "\t</g>" . PHP_EOL; |
| 48 | + $svg .= '</svg>' . PHP_EOL; |
| 49 | + |
| 50 | + return $svg; |
| 51 | + } |
| 52 | + |
| 53 | + public function setForegroundColor(string $color) |
| 54 | + { |
| 55 | + $this->foregroundColor = $color; |
| 56 | + } |
| 57 | +} |
0 commit comments