Example #1
1
 public function testNoFontWithOrientation()
 {
     $this->setExpectedException('\\Zend\\Barcode\\Renderer\\Exception\\ExceptionInterface');
     Barcode\Barcode::setBarcodeFont(null);
     $barcode = new Object\Code39(array('text' => '0123456789'));
     $barcode->setOrientation(1);
     $this->renderer->setBarcode($barcode);
     $this->renderer->draw();
 }
Example #2
0
 public function tearDown()
 {
     Barcode\Barcode::setBarcodeFont(null);
     if (!empty($this->originaltimezone)) {
         date_default_timezone_set($this->originaltimezone);
     }
 }
Example #3
0
 /**
  * @return Boolean Sucesso na criação da imagem
  */
 public function create($value, $options = array(), $barcodeType = 'code25interleaved', $type = 'image')
 {
     $bol_ret = true;
     $value = trim($value);
     try {
         /* Junta a configuração padrão com $options informado */
         $barcodeOptions = array_merge(array('text' => $value, 'drawText' => false), $options);
         /*  Não há opções necessárias */
         $rendererOptions = array();
         // Desenha o código de barras em uma nova imagem,
         // enviar os cabeçalhos e a imagem
         $imageResource = Barcode::factory($barcodeType, $type, $barcodeOptions, $rendererOptions)->draw();
         // Enable output buffering
         ob_start();
         imagepng($imageResource);
         imagedestroy($imageResource);
         // Capture the output
         $imagedata = ob_get_contents();
         // Clear the output buffer
         ob_end_clean();
         return base64_encode($imagedata);
     } catch (Exception $e) {
         $bol_ret = false;
         echo 'Erro: na geraçãod e código de barra!';
         echo 'Código: ' . $e->getCode();
         echo 'Mensagem: ' . $e->getMessage();
         echo 'Trace: ' . $e->getTraceAsString();
     }
     return $bol_ret;
 }
Example #4
0
 public function prepare()
 {
     $nummoeda = "9";
     $fixo = "9";
     // Numero fixo para a posição 05-05
     $ios = "0";
     /**
      * adicionando dados das instruções e demonstrativo no boleto
      */
     (new ClassMethods())->hydrate($this->config['php-zf2-boleto']['instrucoes'], $this->getBoleto());
     /**
      * Compondo o Nosso Número e seu dígito verificador
      */
     $nossoNumeroProcessado = \str_pad($this->getBoleto()->getNossoNumero(), 13, '0', STR_PAD_LEFT);
     $nossoNumeroDV = Util::digitoVerificadorNossoNumero($nossoNumeroProcessado);
     /**
      * Calcula o fator do vencimento (número inteiro que representa a data de vencimento na linha digitavel)
      */
     $fatorVencimento = Util::fatorVencimento($this->getBoleto()->getDataVencimento()->format("d/m/Y"));
     /**
      * Processando o valor para aplicação na linha digitável e no código de barras
      */
     $valor = preg_replace("/[^0-9]/", "", $this->getBoleto()->getValor());
     // removendo formatação do número
     $valorProcessado = \str_pad($valor, 10, '0', STR_PAD_LEFT);
     /**
      * Calcula o dígito verificador do código de barras
      */
     //        $barra = "$codigobanco$nummoeda$fator_vencimento$valor$fixo$codigocliente$nossonumero$ios$carteira";
     $DV = Util::digitoVerificadorBarra($this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $fixo . $this->getCedente()->getCodigocliente() . $nossoNumeroProcessado . $ios . $this->getCedente()->getCarteira());
     $barra = $this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $fixo . $this->getCedente()->getCodigocliente() . $nossoNumeroProcessado . $ios . $this->getCedente()->getCarteira();
     /**
      * Compondo a linha base para formação da Linha Digitável e do Código de Barras
      */
     $strLinha = substr($barra, 0, 4) . $DV . substr($barra, 4);
     /**
      * Formatando o Nosso Número para impressão
      */
     $nossoNumeroFormatado = $nossoNumeroProcessado;
     /**
      * Formatando os dados bancários do cedente para impressão
      */
     $this->getCedente()->setAgenciaCodigo($this->getCedente()->getAgencia() . '-' . $this->getCedente()->getAgenciaDv() . ' / ' . $this->getCedente()->getContaCedente() . '-' . $this->getCedente()->getContaCedenteDv());
     /**
      * Iniciando opções para criação do Código de Barras
      */
     $barcodeOptions = array('text' => $strLinha);
     /**
      * Criando o código de barras em uma imagem e retornando seu base64
      */
     $codigoDeBarras = Barcode::factory('Code25interleaved', 'PhpBoletoZf2\\Lib\\Barcode\\Renderer\\Base64', $barcodeOptions, array());
     /**
      * Termina de hidratar o objetodo boleto
      */
     $this->getBoleto()->setCodigoDeBarras($codigoDeBarras)->setLinhaDigitavel(Util::montaLinhaDigitavel($strLinha))->setNossoNumeroFormatado($nossoNumeroFormatado);
     return $this;
 }
Example #5
0
 public function testStaticFontAsNumber()
 {
     for ($i = 1; $i < 5; $i++) {
         Barcode\Barcode::setBarcodeFont($i);
         $this->assertEquals('', $this->_object->getFont());
         $object = $this->_getBarcodeObject();
         $this->assertEquals($i, $object->getFont());
         Barcode\Barcode::setBarcodeFont('');
     }
 }
Example #6
0
 public function testDrawWithExistantResourceReturnResource()
 {
     Barcode\Barcode::setBarcodeFont(__DIR__ . '/../Object/_fonts/Vera.ttf');
     $barcode = new Object\Code39(array('text' => '0123456789'));
     $this->renderer->setBarcode($barcode);
     $pdfResource = new Pdf\PdfDocument();
     $this->renderer->setResource($pdfResource);
     $resource = $this->renderer->draw();
     $this->assertTrue($resource instanceof Pdf\PdfDocument);
     $this->assertSame($resource, $pdfResource);
     Barcode\Barcode::setBarcodeFont('');
 }
 public function barcode($code, $type = 'code128')
 {
     if (!in_array($type, ['code128', 'code25', 'code25interleaved', 'code39', 'ean13', 'ean2', 'ean5', 'ean8', 'identcode', 'itf14', 'leitcode', 'planet', 'postnet', 'royalmail', 'upca', 'upce'])) {
         \App::abort(404);
     }
     //Barcode::setBarcodeFont( storage_path( 'pdf/fonts/yahei/normal.ttf' ) );
     $barcodeOptions = array('text' => $code, 'factor' => 1);
     $rendererOptions = array();
     Barcode::render($type, 'image', $barcodeOptions, $rendererOptions);
     $response = \Response::make('', 200);
     $response->header('Content-Type', 'image/png', true);
     return $response;
 }
Example #8
0
 /**
  * Gera a imagem do código de barras e o transforma em base64
  * @return string Retorna a imagem gerada no formato base64
  */
 public function getCodigoBarrasBase64()
 {
     ob_start();
     $text = $this->getNumeroCodigoBarras();
     $options = array('text' => (string) $text, 'imageType' => 'jpeg', 'drawText' => false);
     $barcode = new \Zend\Barcode\Object\Code128();
     $barcode->setOptions($options);
     $barcodeOBj = \Zend\Barcode\Barcode::factory($barcode);
     $imageResource = $barcodeOBj->draw();
     imagejpeg($imageResource);
     $contents = ob_get_contents();
     ob_end_clean();
     return base64_encode($contents);
 }
 /**
  * Use the form to get barcode image from selected barcode object.
  */
 public function indexAction()
 {
     $request = $this->getRequest();
     //default value without post parameter
     $barcodeOptions = ['text' => '123456789'];
     $barcode = Barcode::factory('codabar', 'image', $barcodeOptions);
     if ($request->isPost()) {
         $this->form->setData($request->getPost());
         if ($this->form->isValid()) {
             $barcodeOptions = ['text' => $this->form->getData()['barcode-object-text']];
             $barcode = Barcode::factory($this->form->getData()['barcode-object-select'], 'image', $barcodeOptions);
         }
     }
     imagegif($barcode->draw(), './data/barcode.gif');
     return new ViewModel(['form' => $this->form]);
 }
Example #10
0
 public function prepare()
 {
     // adicionando dados das instruções e demonstrativo no boleto
     (new ClassMethods())->hydrate($this->config['php-zf2-boleto']['instrucoes'], $this->getBoleto());
     // adicionando valores default de configuração do cedente
     (new ClassMethods())->hydrate($this->config['php-zf2-boleto'][$this->banco->getCodigoBanco()]['dados_cedente'], $this->getCedente());
     $nossoNumeroProcessado = (int) $this->getBoleto()->getNossoNumero();
     $nossoNumeroProcessado = \str_pad($nossoNumeroProcessado, 7, '0', STR_PAD_LEFT);
     // Calcula o fator do vencimento (número inteiro que representa a data de vencimento na linha digitavel)
     $fatorVencimento = Util::fatorVencimento($this->getBoleto()->getDataVencimento()->format("d/m/Y"));
     $fatorVencimento = \str_pad($fatorVencimento, 4, '0', STR_PAD_LEFT);
     // Processando o valor para aplicação na linha digitável e no código de barras
     $valor = preg_replace("/[^0-9]/", "", $this->getBoleto()->getValor());
     // removendo formatação do número
     $valorProcessado = \str_pad($valor, 10, '0', STR_PAD_LEFT);
     $parcela = $this->getBoleto()->getQuantidade();
     $parcela = \str_pad($parcela ? $parcela : 1, 3, '0', STR_PAD_LEFT);
     $numeroCliente = (int) $this->getCedente()->getConvenio();
     $numeroCliente = \str_pad($numeroCliente, 7, '0', STR_PAD_LEFT);
     /** 
      * Calcula digito verificador nosso número boletos Bancoob
      * 3197 regra sicoob
      */
     $sequencia = $this->getCedente()->getAgencia() . \str_pad($numeroCliente, 10, '0', STR_PAD_LEFT) . $nossoNumeroProcessado;
     $dvNossoNumero = Util::digitoVerificadorNossoNumeroBancoob($sequencia, '3197');
     $nossoNumeroFormatado = "{$nossoNumeroProcessado}{$dvNossoNumero}";
     // modalidade de cobranca
     $variacao = $this->getCedente()->getVariacaoCarteira();
     $variacao = \str_pad($variacao ? $variacao : 2, 2, '0', STR_PAD_LEFT);
     $campoLivre = "{$variacao}{$numeroCliente}{$nossoNumeroFormatado}{$parcela}";
     // Calcula o dígito verificador do código de barras
     $DV = Util::digitoVerificadorBarra($this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $this->getBanco()->getCarteira() . $this->getCedente()->getAgencia() . $campoLivre);
     /**
      * Compondo a linha base para formação da Linha Digitável e do Código de Barras
      */
     $strLinha = $this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $DV . $fatorVencimento . $valorProcessado . $this->getBanco()->getCarteira() . $this->getCedente()->getAgencia() . $campoLivre;
     // Formatando os dados bancários do cedente para impressão
     $this->getCedente()->setAgenciaCodigo($this->getCedente()->getAgenciaDv() . ' / ' . $this->getCedente()->getCodigocliente());
     // Iniciando opções para criação do Código de Barras
     $barcodeOptions = array('text' => $strLinha);
     // Criando o código de barras em uma imagem e retornando seu base64
     $codigoDeBarras = Barcode::factory('Code25interleaved', 'PhpBoletoZf2\\Lib\\Barcode\\Renderer\\Base64', $barcodeOptions, array());
     // Termina de hidratar o objetodo boleto
     $this->getBoleto()->setCodigoDeBarras($codigoDeBarras)->setLinhaDigitavel(Util::montaLinhaDigitavel($strLinha))->setNossoNumeroFormatado($nossoNumeroFormatado);
     return $this;
 }
Example #11
0
 /**
  * Creates and draws a barcode (wrapping the Zend Barcode component).
  *
  * @param  mixed    $barcode              String name of barcode class, or Traversable object.
  * @param  mixed    $barcodeConfig        An array or Traversable object with barcode parameters.
  * @param  mixed    $rendererConfig       An array or Traversable object with renderer parameters.
  * @param  boolean  $automaticRenderError Set the automatic rendering of exception
  * @return resource
  **/
 public function create($barcode, $barcodeConfig = array(), $rendererConfig = array(), $automaticRenderError = true)
 {
     $renderer = new ImageRenderer($rendererConfig);
     //make sure Zend object plugin manager does not share created barcode object
     $objectPluginManager = Barcode::getObjectPluginManager();
     $originallySharedByDefault = $objectPluginManager->shareByDefault();
     if ($originallySharedByDefault) {
         $objectPluginManager->setShareByDefault(false);
     }
     $barcodeObject = $objectPluginManager->get($barcode, $barcodeConfig);
     if ($originallySharedByDefault) {
         //reset object plugin manager
         $objectPluginManager->setShareByDefault(true);
     }
     $renderer->setBarcode($barcodeObject);
     return new GdImage($renderer->draw(), new RGB(), new MetadataBag());
 }
Example #12
0
 public function testDrawWithExistantResourceReturnResource()
 {
     Barcode\Barcode::setBarcodeFont(__DIR__ . '/../Object/_fonts/Vera.ttf');
     $barcode = new Code39(array('text' => '0123456789'));
     $this->_renderer->setBarcode($barcode);
     $svgResource = new \DOMDocument();
     $rootElement = $svgResource->createElement('svg');
     $rootElement->setAttribute('xmlns', "http://www.w3.org/2000/svg");
     $rootElement->setAttribute('version', '1.1');
     $rootElement->setAttribute('width', 500);
     $rootElement->setAttribute('height', 300);
     $svgResource->appendChild($rootElement);
     $this->_renderer->setResource($svgResource);
     $resource = $this->_renderer->draw();
     $this->assertTrue($resource instanceof \DOMDocument);
     $this->assertSame($resource, $svgResource);
     Barcode\Barcode::setBarcodeFont('');
 }
Example #13
0
 /**
  * Constructor
  * @param array|\Zend\Config\Config $options
  * @return void
  */
 public function __construct($options = null)
 {
     $this->_getDefaultOptions();
     if (Barcode\Barcode::getBarcodeFont() !== null) {
         $this->_font = Barcode\Barcode::getBarcodeFont();
     }
     if ($options instanceof Config\Config) {
         $options = $options->toArray();
     }
     if (is_array($options)) {
         $this->setOptions($options);
     }
     /** @todo check if conversion is correct */
     // $this->_type = strtolower(substr(get_class($this), strlen($this->_barcodeNamespace) + 1));
     $this->_type = substr(strrchr(get_class($this), '\\'), 1);
     if ($this->_mandatoryChecksum) {
         $this->_withChecksum = true;
         $this->_withChecksumInText = true;
     }
 }
Example #14
0
 public function tearDown()
 {
     Barcode\Barcode::setBarcodeFont(null);
 }
Example #15
0
 public function testProxyBarcodeObjectFont()
 {
     Barcode\Barcode::setBarcodeFont('my_font.ttf');
     $barcode = new Object\Code25();
     $this->assertSame('my_font.ttf', $barcode->getFont());
     Barcode\Barcode::setBarcodeFont('');
 }
Example #16
0
 /**
  * Constructor
  * @param array|Traversable $options
  * @return void
  */
 public function __construct($options = null)
 {
     $this->getDefaultOptions();
     $this->font = Barcode\Barcode::getBarcodeFont();
     if ($options instanceof Traversable) {
         $options = ArrayUtils::iteratorToArray($options);
     }
     if (is_array($options)) {
         $this->setOptions($options);
     }
     $this->type = strtolower(substr(get_called_class(), strlen($this->barcodeNamespace) + 1));
     if ($this->mandatoryChecksum) {
         $this->withChecksum = true;
         $this->withChecksumInText = true;
     }
 }
Example #17
0
 /**
  * @expectedException \Zend\Barcode\Renderer\Exception
  */
 public function testNoFontWithOrientation()
 {
     Barcode\Barcode::setBarcodeFont(null);
     $barcode = new Object\Code39(array('text' => '0123456789'));
     $barcode->setOrientation(1);
     $this->_renderer->setBarcode($barcode);
     $this->_renderer->draw();
 }
Example #18
0
 public function eticketHtmlAction()
 {
     $em = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     $package = $em->getRepository("ErsBase\\Entity\\Package")->findOneBy(array('id' => 52));
     $products = $em->getRepository("ErsBase\\Entity\\Product")->findAll();
     $config = $this->getServiceLocator()->get('Config');
     $name = $package->getParticipant()->getFirstname() . ' ' . $package->getParticipant()->getSurname();
     $code = $package->getCode()->getValue();
     /*
      * QR-Code creation
      */
     $qr = $this->getServiceLocator()->get('QRCode');
     $qr->isHttps();
     // or $qr->isHttp();
     #$qr->setData('http://prereg.eja.net/onsite/register/'.  \urlencode($code));
     $onsitereg = $config['ERS']['onsitereg'];
     # ensure the url has no trailing slash
     \rtrim($onsitereg, '/\\');
     $qr->setData($onsitereg . '/' . \urlencode($code));
     $qr->setCorrectionLevel('H', 0);
     $qr->setDimensions(200, 200);
     $qr_config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'ssltransport' => 'tls', 'sslcapath' => '/etc/ssl/certs/', 'sslverifypeer' => false);
     // Instantiate a client object
     $client = new \Zend\Http\Client($qr->getResult(), $qr_config);
     // The following request will be sent over a TLS secure connection.
     $response = $client->send();
     $qr_content = $response->getContent();
     $base64_qrcode = "data:image/png;base64," . \base64_encode($qr_content);
     #file_put_contents(getcwd().'/public/img/qrcode.png', $qr_content);
     /*
      * Barcode creation
      */
     // Only the text to draw is required
     $barcodeOptions = array('text' => $code, 'barHeight' => 40, 'factor' => 1.1, 'drawText' => false);
     // No required options
     $rendererOptions = array();
     // Draw the barcode in a new image,
     $imageResource = \Zend\Barcode\Barcode::factory('code39', 'image', $barcodeOptions, $rendererOptions)->draw();
     ob_start();
     //Start output buffer.
     imagejpeg($imageResource);
     //This will normally output the image, but because of ob_start(), it won't.
     $contents = ob_get_contents();
     //Instead, output above is saved to $contents
     ob_end_clean();
     //End the output buffer.
     #file_put_contents(getcwd().'/public/img/barcode2.jpg', $contents);
     $base64_barcode = "data:image/png;base64," . \base64_encode($contents);
     /*
      * prepare items
      */
     $items = array();
     foreach ($package->getItems() as $item) {
         $items[$item->getProductId()][] = $item;
     }
     $agegroupService = $this->getServiceLocator()->get('PreReg\\Service\\AgegroupService:ticket');
     $agegroup = $agegroupService->getAgegroupByUser($package->getParticipant());
     /* 
      * generate PDF
      */
     $viewModel = new ViewModel();
     #$viewModel->setTemplate('pdf/eticket_'.$this->getLanguage());
     $viewModel->setTemplate('pdf/eticket_en');
     $viewModel->setVariables(array('name' => $name, 'package' => $package, 'items' => $items, 'products' => $products, 'agegroup' => $agegroup, 'code' => $code, 'qrcode' => $base64_qrcode, 'barcode' => $base64_barcode));
     return $viewModel;
 }
Example #19
0
 /**
  * @return string
  *
  * This function returns the barcode represented in a PNG image.
  * The Zend\Barcode library is used, and receives a string with the barcode
  * excluding the check digit (checksum).
  * This function only generates GTIN-12, GTIN-13 and GTIN-14 codes.
  */
 public function getImage()
 {
     $subCode = substr($this->getCode(), 0, -1);
     $code_type = '';
     if ($this->getType() == 'TYPECODE_GTIN_12') {
         $code_type = 'upca';
     }
     if ($this->getType() == 'TYPECODE_GTIN_13') {
         $code_type = 'ean13';
     }
     if ($this->getType() == 'TYPECODE_GTIN_14') {
         $code_type = 'itf14';
     }
     //When working with type code ITF, it should be framed.
     if ($this->getType() == 'TYPECODE_GTIN_14') {
         $barcodeOptions = array('text' => $subCode, 'withBorder' => true, 'factor' => 1);
     } else {
         $barcodeOptions = array('text' => $subCode, 'factor' => 1);
     }
     $rendererOptions = array();
     /** @var Gd $image */
     $image = \Zend\Barcode\Barcode::factory($code_type, 'image', $barcodeOptions, $rendererOptions)->draw();
     ob_start();
     imagepng($image);
     $contents = ob_get_contents();
     ob_end_clean();
     return $contents;
 }
Example #20
0
 public function tearDown()
 {
     Barcode\Barcode::setBarcodeFont(null);
     date_default_timezone_set($this->_originaltimezone);
 }
Example #21
0
 /**
  * Draw the barcode in the rendering resource
  * @return mixed
  */
 public function draw()
 {
     try {
         $this->checkParams();
         $this->initRenderer();
         $this->drawInstructionList();
     } catch (BarcodeException $e) {
         if ($this->automaticRenderError && !$e instanceof BarcodeException\RendererCreationException) {
             $barcode = Barcode::makeBarcode('error', array('text' => $e->getMessage()));
             $this->setBarcode($barcode);
             $this->resource = null;
             $this->initRenderer();
             $this->drawInstructionList();
         } else {
             throw $e;
         }
     }
     return $this->resource;
 }
Example #22
0
 /**
  * Draw the barcode in the rendering resource
  * @return mixed
  */
 public function draw()
 {
     try {
         $this->checkParams();
         $this->_initRenderer();
         $this->_drawInstructionList();
     } catch (\Zend\Exception $e) {
         $renderable = false;
         if ($e instanceof Barcode\Exception) {
             $renderable = $e->isRenderable();
         }
         if ($this->_automaticRenderError && $renderable) {
             $barcode = Barcode\Barcode::makeBarcode('error', array('text' => $e->getMessage()));
             $this->setBarcode($barcode);
             $this->_resource = null;
             $this->_initRenderer();
             $this->_drawInstructionList();
         } else {
             if ($e instanceof Barcode\Exception) {
                 $e->setIsRenderable(false);
             }
             throw $e;
         }
     }
     return $this->_resource;
 }
Example #23
0
 public function generatePdf()
 {
     $config = $this->getServiceLocator()->get('Config');
     if (!extension_loaded('gd')) {
         throw new \Exception('PHP Extension gd needs to be loaded.');
     }
     /*
      * PDF creation
      */
     $paperSize = 'a4';
     $paperOrientation = 'portrait';
     $pdf = new PdfModel();
     $pdf->setOption("paperSize", $paperSize);
     //Defaults to 8x11
     $pdf->setOption("paperOrientation", $paperOrientation);
     //Defaults to portrait
     $name = $this->getParticipant()->getFirstname() . ' ' . $this->getParticipant()->getSurname();
     $code = $this->getPackage()->getCode()->getValue();
     /*
      * QR-Code creation
      */
     $qr = $this->getServiceLocator()->get('QRCode');
     $qr->isHttps();
     // or $qr->isHttp();
     #$qr->setData('http://prereg.eja.net/onsite/register/'.  \urlencode($code));
     $onsitereg = $config['ERS']['onsitereg'];
     # ensure the url has no trailing slash
     \rtrim($onsitereg, '/\\');
     $qr->setData($onsitereg . '/' . \urlencode($code));
     $qr->setCorrectionLevel('H', 0);
     $qr->setDimensions(200, 200);
     $qr_config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'ssltransport' => 'tls', 'sslcapath' => '/etc/ssl/certs/', 'sslverifypeer' => false);
     // Instantiate a client object
     $client = new \Zend\Http\Client($qr->getResult(), $qr_config);
     // The following request will be sent over a TLS secure connection.
     $response = $client->send();
     $qr_content = $response->getContent();
     $base64_qrcode = "data:image/png;base64," . \base64_encode($qr_content);
     #file_put_contents(getcwd().'/public/img/qrcode.png', $qr_content);
     /*
      * Barcode creation
      */
     // Only the text to draw is required
     $barcodeOptions = array('text' => $code, 'barHeight' => 40, 'factor' => 1.1, 'drawText' => false);
     // No required options
     $rendererOptions = array();
     // Draw the barcode in a new image,
     $imageResource = \Zend\Barcode\Barcode::factory('code39', 'image', $barcodeOptions, $rendererOptions)->draw();
     ob_start();
     //Start output buffer.
     imagejpeg($imageResource);
     //This will normally output the image, but because of ob_start(), it won't.
     $contents = ob_get_contents();
     //Instead, output above is saved to $contents
     ob_end_clean();
     //End the output buffer.
     #file_put_contents(getcwd().'/public/img/barcode2.jpg', $contents);
     $base64_barcode = "data:image/png;base64," . \base64_encode($contents);
     /*
      * prepare items
      */
     $items = array();
     foreach ($this->getPackage()->getItems() as $item) {
         if ($item->getStatus() == 'transferred') {
             continue;
         }
         $items[$item->getProductId()][] = $item;
     }
     /* 
      * generate PDF
      */
     $pdfView = new ViewModel();
     $pdfView->setTemplate('pdf/eticket_' . $this->getLanguage());
     $pdfView->setVariables(array('name' => $name, 'package' => $this->getPackage(), 'items' => $items, 'products' => $this->getProducts(), 'agegroup' => $this->getAgegroup(), 'code' => $code, 'qrcode' => $base64_qrcode, 'barcode' => $base64_barcode));
     $pdfRenderer = $this->getServiceLocator()->get('ViewPdfRenderer');
     $html = $pdfRenderer->getHtmlRenderer()->render($pdfView);
     $pdfEngine = $pdfRenderer->getEngine();
     $pdfEngine->set_paper($paperSize, $paperOrientation);
     $pdfEngine->set_base_path(getcwd() . '/');
     $pdfEngine->load_html($html);
     $pdfEngine->render();
     $pdfContent = $pdfEngine->output();
     $filename = $config['ERS']['name_short'] . "_e-Ticket_" . $this->getPackage()->getCode()->getValue() . '_' . $this->getLanguage();
     # TODO: make ticket_path configurable
     $ticket_path = getcwd() . '/data/etickets';
     \rtrim($onsitereg, '/\\');
     if (!is_dir($ticket_path)) {
         mkdir($ticket_path);
     }
     $filePath = $ticket_path . '/' . $filename . '.pdf';
     file_put_contents($filePath, $pdfContent);
     return $filePath;
 }
Example #24
0
 public function prepare()
 {
     /**
      * adicionando dados das instruções e demonstrativo no boleto
      */
     (new ClassMethods())->hydrate($this->config['php-zf2-boleto']['instrucoes'], $this->getBoleto());
     /**
      * Calcula o fator do vencimento (número inteiro que representa a data de vencimento na linha digitavel)
      */
     $fatorVencimento = Util::fatorVencimento($this->getBoleto()->getDataVencimento()->format("d/m/Y"));
     /**
      * Processando o valor para aplicação na linha digitável e no código de barras
      */
     $valor = preg_replace("/[^0-9]/", "", $this->getBoleto()->getValor());
     // removendo formatação do número
     $valorProcessado = \str_pad($valor, 10, '0', STR_PAD_LEFT);
     /**
      * Formatando os dados bancários do cedente para impressão
      */
     $this->getCedente()->setAgenciaCodigo($this->getCedente()->getAgencia() . '-' . $this->getCedente()->getAgenciaDv() . ' / ' . $this->getCedente()->getContaCorrente() . '-' . $this->getCedente()->getContaCorrenteDv());
     // usado quando convenio tem 7 digitos
     $livreZeros = '000000';
     switch ($this->getCedente()->getFormatacaoConvenio()) {
         case 8:
             $convenioProcessado = str_pad($this->getCedente()->getConvenio(), 8, '0', STR_PAD_LEFT);
             $nossoNumeroProcessado = str_pad($this->getBoleto()->getNossoNumero(), 9, '0', STR_PAD_LEFT);
             $DV = Util::modulo11($this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $livreZeros . $convenioProcessado . $nossoNumeroProcessado . $this->getBanco()->getCarteira());
             $strLinha = $this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $DV . $fatorVencimento . $valorProcessado . $livreZeros . $convenioProcessado . $nossoNumeroProcessado . $this->getBanco()->getCarteira();
             $nossoNumeroFormatado = $convenioProcessado . $nossoNumeroProcessado . '-' . Util::modulo11($convenioProcessado . $nossoNumeroProcessado);
             break;
         case 7:
             $convenioProcessado = str_pad($this->getCedente()->getConvenio(), 7, '0', STR_PAD_LEFT);
             $nossoNumeroProcessado = str_pad($this->getBoleto()->getNossoNumero(), 10, '0', STR_PAD_LEFT);
             $DV = Util::modulo11($this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $livreZeros . $convenioProcessado . $nossoNumeroProcessado . $this->getBanco()->getCarteira());
             $strLinha = $this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $DV . $fatorVencimento . $valorProcessado . $livreZeros . $convenioProcessado . $nossoNumeroProcessado . $this->getBanco()->getCarteira();
             $nossoNumeroFormatado = $convenioProcessado . $nossoNumeroProcessado;
             break;
         case 6:
             $convenioProcessado = str_pad($this->getCedente()->getConvenio(), 6, '0', STR_PAD_LEFT);
             switch ($this->getBoleto()->getFormatacaoNossoNumero()) {
                 case 1:
                     $nossoNumeroProcessado = str_pad($this->getBoleto()->getNossoNumero(), 5, '0', STR_PAD_LEFT);
                     $DV = Util::modulo11($this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $convenioProcessado . $nossoNumeroProcessado . $this->getCedente()->getAgencia() . $this->getCedente()->getContaCorrente() . $this->getCedente()->getCarteira());
                     $strLinha = $this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $DV . $fatorVencimento . $valorProcessado . $convenioProcessado . $nossoNumeroProcessado . $this->getCedente()->getAgencia() . $this->getCedente()->getContaCorrente() . $this->getCedente()->getCarteira();
                     $nossoNumeroFormatado = $convenioProcessado . $nossoNumeroProcessado . '-' . Util::modulo11($convenioProcessado . $nossoNumeroProcessado);
                     break;
                 case 2:
                     $numeroServico = 21;
                     $nossoNumeroProcessado = str_pad($this->getBoleto()->getNossoNumero(), 17, '0', STR_PAD_LEFT);
                     $DV = Util::modulo11($this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $fatorVencimento . $valorProcessado . $convenioProcessado . $nossoNumeroProcessado . $numeroServico);
                     $strLinha = $this->getBanco()->getCodigoBanco() . $this->getBanco()->getMoeda() . $DV . $fatorVencimento . $valorProcessado . $convenioProcessado . $nossoNumeroProcessado . $numeroServico;
                     $nossoNumeroFormatado = $nossoNumeroProcessado;
                     break;
             }
             break;
     }
     /**
      * Iniciando opções para criação do Código de Barras
      */
     $barcodeOptions = array('text' => $strLinha);
     /**
      * Criando o código de barras em uma imagem e retornando seu base64
      */
     $codigoDeBarras = Barcode::factory('Code25interleaved', 'PhpBoletoZf2\\Lib\\Barcode\\Renderer\\Base64', $barcodeOptions, array());
     /**
      * Termina de hidratar o objetodo boleto
      */
     $this->getBoleto()->setCodigoDeBarras($codigoDeBarras)->setLinhaDigitavel(Util::montaLinhaDigitavel($strLinha))->setNossoNumeroFormatado($nossoNumeroFormatado);
     return $this;
 }
Example #25
0
 /**
  * Constructor
  * @param array|\Zend\Config\Config $options
  * @return void
  */
 public function __construct($options = null)
 {
     $this->_getDefaultOptions();
     $this->_font = Barcode\Barcode::getBarcodeFont();
     if ($options instanceof Config) {
         $options = $options->toArray();
     }
     if (is_array($options)) {
         $this->setOptions($options);
     }
     $this->_type = strtolower(substr(get_class($this), strlen($this->_barcodeNamespace) + 1));
     if ($this->_mandatoryChecksum) {
         $this->_withChecksum = true;
         $this->_withChecksumInText = true;
     }
 }
 public function saveAs($type, $text, $file)
 {
     $fontfile = __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "Resources" . DIRECTORY_SEPARATOR . "fonts" . DIRECTORY_SEPARATOR . 'Lato-Regular.ttf';
     @unlink($file);
     switch ($type) {
         case $type == 99:
             include_once __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "Resources" . DIRECTORY_SEPARATOR . "phpqrcode" . DIRECTORY_SEPARATOR . "qrlib.php";
             \QRcode::png($text, $file, QR_ECLEVEL_L, 12);
             break;
         case $type == 90:
             $font = new \Imagine\Gd\Font($fontfile, 35, new \Imagine\Image\Color('fff', 100));
             $resource = imagecreatetruecolor(2000, 60);
             $color = new \Imagine\Image\Color('fff');
             $white = imagecolorallocate($resource, 255, 255, 255);
             $black = imagecolorallocate($resource, 0, 0, 0);
             if (false === $white) {
                 throw new RuntimeException('Unable to allocate color');
             }
             if (false === imagefill($resource, 0, 0, $white)) {
                 throw new RuntimeException('Could not set background color fill');
             }
             imagettftext($resource, 35, 0, 10, 50, $black, $fontfile, $text);
             $image = new Image($resource);
             $image->crop(new \Imagine\Image\Point(0, 0), new \Imagine\Image\Box(20 + $font->box($text)->getWidth(), 60));
             $image->save($file);
             break;
         case is_numeric($type):
             $type = $this->types[$type];
         default:
             $validator = new BarcodeValidator(array('adapter' => $type, 'usechecksum' => false));
             //                if (!$validator->isValid($text)) {
             //                    $message = implode("\n", $validator->getMessages());
             //                    throw new \Symfony\Component\HttpKernel\Exception\HttpException(401, $message, null);
             //                }
             //z apki dostaje barcody z
             //                if($type == 'ean13')
             //                {
             //                    $text = substr($text, 0, -1);
             //                }
             $barcodeOptions = array('text' => $text, 'factor' => 3, 'font' => __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "Resources" . DIRECTORY_SEPARATOR . "fonts" . DIRECTORY_SEPARATOR . 'Lato-Regular.ttf');
             $rendererOptions = array();
             $imageRenderer = Barcode::factory($type, 'image', $barcodeOptions, $rendererOptions, false);
             //fix to not throw error when try to render barcode with code with checksum
             if ($imageRenderer->getBarcode()->getWithChecksum()) {
                 //maybe i got barcode without checksum need to test it by try cache :(
                 try {
                     $imageRenderer->getBarcode()->validateText($text);
                 } catch (\Exception $exc) {
                     //propably length error remove checksum
                     //when barcode have mandatoryChecksum and have default
                     //validateSpecificText then renderer waiting for code without checksum :(
                     $imageRenderer->getBarcode()->setText(substr($text, 0, -1));
                 }
             }
             //catch error and send http error 400 not 500 as default
             try {
                 $image = new Image($imageRenderer->draw());
             } catch (\Exception $exc) {
                 $message = $exc->getMessage();
                 throw new \Symfony\Component\HttpKernel\Exception\HttpException(400, $message, null);
             }
             $image->save($file);
     }
     return true;
 }
<?php

require '../vendor/autoload.php';
ob_start();
$text = '91910919190191091090109109190109';
$options = array('text' => (string) $text, 'barHeight' => 40, 'barWidth' => 100, 'imageType' => 'jpeg');
$barcode = new \Zend\Barcode\Object\Code128();
$barcode->setOptions($options);
$barcodeOBj = \Zend\Barcode\Barcode::factory($barcode);
$imageResource = $barcodeOBj->draw();
imagejpeg($imageResource);
$contents = ob_get_contents();
ob_end_clean();
$barcodeGnre = new \Gnre\Render\Barcode128();
$barcodeGnre->setNumeroCodigoBarras('91910919190191091090109109190109');
?>

<img src="<?php 
echo 'data:image/jpeg;base64,' . $barcodeGnre->getCodigoBarrasBase64();
?>
"/>
<img src="<?php 
echo 'data:image/jpeg;base64,' . base64_encode($contents);
?>
"/>

 /**
  * @param $type
  * @param $text
  * @param $file
  * @param array $options
  * @return bool
  */
 public function saveAs($type, $text, $file, $options = array())
 {
     @unlink($file);
     switch ($type) {
         case $type == 'qr':
             include_once __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "Resources" . DIRECTORY_SEPARATOR . "phpqrcode" . DIRECTORY_SEPARATOR . "qrlib.php";
             $level = isset($options['level']) ? $options['level'] : QR_ECLEVEL_L;
             $size = isset($options['size']) ? $options['size'] : 3;
             $margin = isset($options['margin']) ? $options['margin'] : 4;
             \QRcode::png($text, $file, $level, $size, $margin);
             if (isset($options['useOverlay']) && $options['useOverlay']) {
                 $this->addOverlay($file, $size);
             }
             break;
         case is_numeric($type):
             $type = $this->types[$type];
         default:
             $barcodeOptions = array_merge(isset($options['barcodeOptions']) ? $options['barcodeOptions'] : array(), array('text' => $text));
             $rendererOptions = isset($options['rendererOptions']) ? $options['rendererOptions'] : array();
             $rendererOptions['width'] = isset($rendererOptions['width']) ? $rendererOptions['width'] : 2233;
             $rendererOptions['height'] = isset($rendererOptions['height']) ? $rendererOptions['height'] : 649;
             $image = new Image($imageResource = Barcode::factory($type, 'image', $barcodeOptions, $rendererOptions)->draw());
             $image->save($file);
     }
     return true;
 }
Example #29
0
 /**
  * This draws and optionally renders a barcode image
  *
  * @param string $strText The text to represent as a barcode
  * @param bool $blnRender 
  * @return image 
  */
 public static function DrawBarcode($strText, $blnRender = false)
 {
     $arrBarcodeOptions = array('text' => $strText, 'font' => __INCLUDES__ . '/fonts/VeraMono.ttf');
     // No required renderer options
     $arrRendererOptions = array();
     if (!$blnRender) {
         // Draw the barcode and return the resource
         $imgResource = Barcode::draw('code128', 'image', $arrBarcodeOptions, $arrRendererOptions);
         return $imgResource;
     } else {
         // Draw the barcode in a new image,
         // send the headers and the image
         Barcode::render('code128', 'image', $arrBarcodeOptions, $arrRendererOptions);
     }
 }
Example #30
0
 public function generatepdfAction()
 {
     if (!extension_loaded('gd')) {
         throw new Exception('PHP Extension gd needs to be loaded.');
     }
     /*
      * PDF creation
      */
     $pdf = new PdfModel();
     $pdf->setOption("paperSize", "a4");
     //Defaults to 8x11
     $pdf->setOption("paperOrientation", "portrait");
     //Defaults to portrait
     $name = 'Andreas Nitsche';
     $code = 'AABBCCDD';
     /*
      * QR-Code creation
      */
     $qr = $this->getServiceLocator()->get('QRCode');
     $qr->isHttps();
     // or $qr->isHttp();
     $qr->setData('http://prereg.eja.net/onsite/register/' . \urlencode($code));
     $qr->setCorrectionLevel('H', 0);
     $qr->setDimensions(200, 200);
     $config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'ssltransport' => 'tls', 'sslcapath' => '/etc/ssl/certs/', 'sslverifypeer' => false);
     // Instantiate a client object
     $client = new \Zend\Http\Client($qr->getResult(), $config);
     // The following request will be sent over a TLS secure connection.
     $response = $client->send();
     $qr_content = $response->getContent();
     $base64_qrcode = "data:image/png;base64," . \base64_encode($qr_content);
     #file_put_contents(getcwd().'/public/img/qrcode.png', $qr_content);
     /*
      * Code creation
      */
     // Only the text to draw is required
     $barcodeOptions = array('text' => $code, 'barHeight' => 40, 'factor' => 1.1);
     // No required options
     $rendererOptions = array();
     // Draw the barcode in a new image,
     $imageResource = \Zend\Barcode\Barcode::factory('code39', 'image', $barcodeOptions, $rendererOptions)->draw();
     ob_start();
     //Start output buffer.
     imagejpeg($imageResource);
     //This will normally output the image, but because of ob_start(), it won't.
     $contents = ob_get_contents();
     //Instead, output above is saved to $contents
     ob_end_clean();
     //End the output buffer.
     #file_put_contents(getcwd().'/public/img/barcode2.jpg', $contents);
     $base64_barcode = "data:image/png;base64," . \base64_encode($contents);
     /*
      * PDF generation to view
      */
     /*
     $pdf->setVariables(array(
         'name' => $name,
         'code' => $code,
         'qrcode' => $base64_qrcode,
         'barcode' => $base64_barcode,
     ));
     $filename = "EJC2015_e-ticket_".preg_replace('/\ /', '_', $name);
     $pdf->setOption("filename", $filename);
     return $pdf;
     */
     /***********************************/
     $pdfView = new ViewModel();
     $pdfView->setTemplate('pre-reg/test/generatepdf');
     $pdfView->setVariables(array('name' => $name, 'code' => $code, 'qrcode' => $base64_qrcode, 'barcode' => $base64_barcode));
     $pdfRenderer = $this->getServiceLocator()->get('ViewPdfRenderer');
     $html = $pdfRenderer->getHtmlRenderer()->render($pdfView);
     $pdfEngine = $pdfRenderer->getEngine();
     $pdfEngine->load_html($html);
     $pdfEngine->render();
     $pdfContent = $pdfEngine->output();
     $filename = "EJC2015_e-ticket_" . preg_replace('/\\ /', '_', $name);
     file_put_contents(getcwd() . '/public/img/' . $filename . '.pdf', $pdfContent);
     return new ViewModel();
 }