src/Service/BarcodeGenerator.php line 33

Open in your IDE?
  1. <?php
  2. namespace FMS\eLibreria\CmsBundle\Service;
  3. use Com\Tecnick\Barcode\Barcode;
  4. class BarcodeGenerator {
  5. const CODE_TYPE = "C128";
  6. const FOREGROUND_COLOR = "black";
  7. const BACKGROUND_COLOR = "white";
  8. const PREFIX_BASE64 = "data:image/png;base64, ";
  9. /**
  10. * A QR Code with error correction level M, which the Orden asks the invoice QR for (art. 21.1). The library
  11. * silently turns any level it does not know into L, so `BarcodeGeneratorQrTest` reads the level back from the
  12. * symbol instead of trusting this string (change verifactu-11, design decision 3).
  13. */
  14. const QR_CODE_TYPE = "QRCODE,M";
  15. /**
  16. * Pixels per module of the QR image: enough for 300 dpi at the 35 mm of the A4 block for every URL an invoice
  17. * prints. The printed size is set in millimetres by the print stylesheets, never by these pixels.
  18. */
  19. const QR_MODULE_UNITS = 12;
  20. /** The PNG carries no quiet zone of its own: the stylesheets give it in millimetres. */
  21. const QR_PADDING = array(0, 0, 0, 0);
  22. /** @var Barcode */
  23. private $barcode;
  24. public function __construct() {
  25. $this->barcode = new Barcode();
  26. }
  27. public function getC128Binary($code, $width = -1, $height = -30){
  28. // generate a barcode
  29. $bobj = $this->barcode->getBarcodeObj(
  30. self::CODE_TYPE, // barcode type and additional comma-separated parameters
  31. $code, // data string to encode
  32. $width, // bar width (use absolute or negative value as multiplication factor)
  33. $height, // bar height (use absolute or negative value as multiplication factor)
  34. self::FOREGROUND_COLOR, // foreground color
  35. array(0,0,0,0) // padding (use absolute or negative values as multiplication factors)
  36. )->setBackgroundColor(self::BACKGROUND_COLOR); // background color
  37. return $bobj->getPngData();
  38. }
  39. public function getC128Base64($code, $width = -1, $height = -30){
  40. return base64_encode($this->getC128Binary($code, $width, $height));
  41. }
  42. public function getC128Base64ForImageTag($code, $width = -1, $height = -30){
  43. return self::PREFIX_BASE64 . $this->getC128Base64($code, $width, $height);
  44. }
  45. /**
  46. * The PNG of the QR of a verification URL, base64-encoded (change verifactu-11, design decision 3). A
  47. * negative size is the size of each module, so every module is the same whole number of pixels.
  48. */
  49. public function getQrPngBase64(string $url): string {
  50. $qr = $this->barcode->getBarcodeObj(
  51. self::QR_CODE_TYPE,
  52. $url,
  53. -self::QR_MODULE_UNITS,
  54. -self::QR_MODULE_UNITS,
  55. self::FOREGROUND_COLOR,
  56. self::QR_PADDING
  57. )->setBackgroundColor(self::BACKGROUND_COLOR);
  58. return base64_encode($qr->getPngData());
  59. }
  60. }