Nesse artigo vamos apresentar uma classe externa em php desenvolvida exclusivamente para usar com Scriptcase, usando uma biblioteca externa.
A classe resulta um tabela html formatada com Style In-line que pode facilmente ser utilizada em uma aplicação de controle, formulário, blank e Report PDF.

Exemplo, utilizando a classe com suas propriedades padrão:

DATAPRODUTOQUANTIDADEVALOR VENDIDO
13/03/2017ESPONJA DE LIMPEZA 4 UNIDADES100R$ 4,34
13/03/2017SAPÓLIO GARRAFA DE 200ML100R$ 4,34
13/03/2017SABÃO EM PÓ 500ML55R$ 7,50
13/03/2017SABÃO EM PEDRA 4UNIDADES70R$ 3,30
10/03/2017DETERGENTE GARRAFA 300ML280R$ 7,90
12/03/2017DESINFETANTE GARRAVA 500ML300R$ 9,85
13/03/2017LIMPADOR VIDROS GARRAFA 350ML90R$ 12,30
13/03/2017CLORO GARRAFA 1 LITRO26R$ 6,99
TOTAL DE VENDASR$ 7.967,24

Exemplo, customizando o estilo dos elementos:

TITULO DA TABELA
DATAPRODUTOQUANTIDADEVALOR VENDIDO
13/03/2017ESPONJA DE LIMPEZA 4 UNIDADES100R$ 4,34
13/03/2017SAPÓLIO GARRAFA DE 200ML100R$ 4,34
13/03/2017SABÃO EM PÓ 500ML55R$ 7,50
13/03/2017SABÃO EM PEDRA 4UNIDADES70R$ 3,30
10/03/2017DETERGENTE GARRAFA 300ML280R$ 7,90
12/03/2017DESINFETANTE GARRAVA 500ML300R$ 9,85
13/03/2017LIMPADOR VIDROS GARRAFA 350ML90R$ 12,30
13/03/2017CLORO GARRAFA 1 LITRO26R$ 6,99
TOTAL DE VENDASR$ 7.967,24

Adicionando a classe como biblioteca externa:

Crie uma biblioteca com nome de DataGrid.

Adicione uma pasta chamada class e nesta pasta um arquivo com nome: DataGrid.class.php e copie o código a seguir para esse arquivo:

<?php

class DataGridForTCPDF {

private $Style;
 private $StyleCol;
 private $tagName;
 private $Html;
 private $CellCount;
 private $Columns;
 private $ZebraColor;
 private $ZebraFlag;
 private $LineNum;

public function __construct($Columns = null) {

// ESTILO PADRÃO DA TABELA
 // $this->Style['Table'] = [];

$this->Style['Table']['border'] = '1';
 $this->Style['Table']['bordercolor'] = 'LIGHTGRAY';
 $this->Style['Table']['cellspacing'] = '0.1';
 $this->Style['Table']['cellpadding'] = '1';
 $this->Style['Table']['style']['text-align'] = 'left';
 $this->Style['Table']['style']['border-collapse'] = 'collapse';

// ESTILO PADRÃO DO CABEÇALHO
 // $this->Style['Header'] = [];
 // $this->Style['Header']['bgcolor'] = 'GRAY';
 $this->Style['Header']['style']['background-color'] = 'GRAY';
 $this->Style['Header']['style']['text-align'] = 'center';
 $this->Style['Header']['style']['color'] = 'white';
 $this->Style['Header']['style']['font-size'] = 'x-small';

// ESTILO PADRÃO DAS LINHAS
 $this->Style['Row']['style']['font-size'] = 'small';
 // $this->Style['Row']['style']['background-color'] = 'WHITE !IMPORTANT';

// TRADUTOR DE TAGS
 $this->tagName['Table'] = 'table';
 $this->tagName['Header'] = 'tr';
 $this->tagName['Header_Cell'] = 'th';
 $this->tagName['Row'] = 'tr';
 $this->tagName['Cell'] = 'td';

// Contadores
 $this->CellCount = 0;
 $this->Columns = $Columns;

// ZEBRANDO A TABELA
 $this->ZebraColor = 'GhostWhite';
 $this->ZebraFlag = False;
 }

// ADICIONA ESTILOS__SPC&SPC__ATRIBUTOS A UMA TAG
 public function setStyle($tag, $type, $val, $col = null) {
 $t = strtolower($type);
 $v = strtolower($val);
 if ($t === 'style'):
 $v = explode(':', $v);
 if ($col === NULL):
 $this->Style[$tag][$t][$v[0]] = $v[1];
 else:
 $this->StyleCol[$tag][$col][$t][$v[0]] = $v[1];
 endif;
 else:
 if ($col === NULL):
 $this->Style[$tag][$t] = $v;
 else:
 $this->StyleCol[$tag][$col][$t] = $v;
 endif;
 endif;
 }

// RESETA UM ESTILO
 public function resetStyle($tag, $type, $val, $col = null) {
 if (!$col):
 unset($this->Style[$tag][$type][$val]);
 else:
 unset($this->StyleCol[$tag][$col][$type][$val]);
 endif;
 }

// AGRUPA TIPOS DE ESTILOS AO ATRIBUTO STYLE
 private function agroup_styles($arr) {
 $styles = '';
 while ($val = current($arr)) {
 $styles .= key($arr) . ':' . $val . ';';
 next($arr);
 }
 $styles = ' style="' . $styles . '" ';
 return $styles;
 }

// ABRINDO TAG
 private function openTag($tagName) {

if ($tagName == 'Row') {
 $this->LineNum++;
 }

if ($this->ZebraFlag) {
 $this->applyZebra();
 }

$tag = "<" . $this->tagName[$tagName];

// TEM ATRIBUTO PARA TAGNAME
 if (isset($this->Style[$tagName])):
 foreach ($this->Style[$tagName] as $key => $styleVal) {
 if (is_array($styleVal)):
 $tag .= $this->agroup_styles($styleVal);
 else:
 $tag .= ' ' . $key . '="' . $styleVal . '" ';
 endif;
 }
 endif;

// TEM ESTILO/ATRIBUTO PARA A COLUNA
 if (isset($this->StyleCol[$tagName][$this->CellCount])):
 foreach ($this->StyleCol[$tagName][$this->CellCount] as $key => $styleVal) {
 if (is_array($styleVal)):
 $tag .= $this->agroup_styles($styleVal);
 else:
 $tag .= ' ' . $key . '="' . $styleVal . '" ';
 endif;
 }
 endif;

$tag .= ">";

// RESETANDO BACKGROUND-COLOR
 $this->resetStyle('Row', 'style', 'background-color');
 $this->resetStyle('Row', 'style', 'color');

return $tag;
 }

// FECHANDO TAG
 private function closeTag($tagName) {
 return "tagName[$tagName] . ">";
 }

// ADICIONANDO CABEÇALHO A TABELA
 public function addHeader($val) {

// ABRINDO A TAG DO CABEÇALHO
 if (!$this->CellCount):
 $this->Html .= $this->openTag('Header');
 endif;

// ATRIBUINDO VALOR A CÉLULA DO CABEÇALHO
 if (is_array($val)):
 $this->Columns = count($val);
 $this->CellCount = 0;
 while ($content = current($val)) {
 $this->Html .= $this->openTag('Header_Cell');
 $this->Html .= $content;
 $this->Html .= $this->closeTag('Header_Cell');
 $this->CellCount++;
 next($val);
 }
 else:
 $this->Html .= $this->openTag('Header_Cell');
 $this->Html .= $val;
 $this->Html .= $this->closeTag('Header_Cell');
 IF (isset($this->Style['Header_Cell']['colspan']) and $this->Style['Header_Cell']['colspan']):
 $this->CellCount = $this->CellCount + $this->Style['Header_Cell']['colspan'];
 unset($this->Style['Header_Cell']['colspan']);
 else:
 $this->CellCount++;
 endif;
 endif;

// FECHANDO TAG DO CABEÇALHO
 if ($this->CellCount >= $this->Columns):
 $this->Html .= $this->closeTag('Header');
 $this->CellCount = 0;
 endif;
 }

// SETANDO INICIO DO ZEBRADO__SPC&SPC__DO FUNDO DA LINHA
 public function setZebraColor($cor = FALSE) {
 if ($cor && $cor !== TRUE) {
 $this->ZebraColor = $cor;
 }
 if ($cor) {
 $this->ZebraFlag = True;
 } else {
 $this->ZebraFlag = False;
 }
 }

public function applyZebra() {
 if (!isset($this->Style['Row']['style']['background-color'])):
 if (!($this->LineNum % 2)) {
 $this->Style['Row']['style']['background-color'] = $this->ZebraColor;
 } else {
 $this->resetStyle('Row', 'style', 'background-color');
 }
 endif;
 }

// ADICIONAR COLUNAS
 public function addCell($val) {
 // ABRINDO A TAG DA LINHA
 if (!$this->CellCount):
 $this->Html .= $this->openTag('Row');
 endif;

// ATRIBUINDO VALOR A CÉLULA DA LINHA
 if (is_array($val)):
 $this->Columns = count($val);
$this->CellCount = 0;
 foreach ($val as $content) {
$this->Html .= $this->openTag('Cell');
 $this->Html .= $content;
 $this->Html .= $this->closeTag('Cell');
 $this->CellCount++;
 }
 else:
 $this->Html .= $this->openTag('Cell');
 $this->Html .= $val;
 $this->Html .= $this->closeTag('Cell');
 IF (isset($this->Style['Cell']['colspan']) and $this->Style['Cell']['colspan'] >= 0):
 $this->CellCount = $this->CellCount + $this->Style['Cell']['colspan'];
 unset($this->Style['Cell']['colspan']);
 else:
 $this->CellCount++;
 endif;

endif;

// FECHANDO TAG DA LINHA
 if ($this->CellCount >= $this->Columns):
 $this->Html .= $this->closeTag('Row');
 $this->CellCount = 0;
 endif;
 }

// FINALIZA HTML
 public function create() {
 $this->Html = $this->openTag('Table') . $this->Html;
 $this->Html .= $this->closeTag('Table');
 return $this->Html;
 }

}

Download da classe DataGrid em arquivo formato zip: Clique aqui.

Explicarei com detalhes o funcionamento da Classe PHP acima no vídeo:

Vídeo Parte 1 Clique Aqui

Vamos implementar agora em uma aplicação de Controle:

Crie uma aplicação de controle e adicione um campo virtual de nome DataGridBasic
Evento OnApplicationInit:

//CRIANDO UMA BASE DE DADOS PARA TESTE

//CRIANDO UMA VARIÁVEL GLOBAL, OPCIONAL DE SAÍDA, NÃO SESSÃO, NÃO POST, NÃO GET.
 [iw] = new StdClass;

//REGISTROS A SEREM IMPRESSOS
 $_arr[] = ['13/03/2017', 'ESPONJA DE LIMPEZA 4 UNIDADES', 100, 4.34] ;
 $_arr[] = ['13/03/2017', 'SAPÓLIO GARRAFA DE 200ML', 100, 4.34] ;
 $_arr[] = ['13/03/2017', 'SABÃO EM PÓ 500ML', 55, 7.50] ;
 $_arr[] = ['13/03/2017', 'SABÃO EM PEDRA 4UNIDADES', 70, 3.30] ;
 $_arr[] = ['10/03/2017', 'DETERGENTE GARRAFA 300ML', 280, 7.90];
 $_arr[] = ['12/03/2017', 'DESINFETANTE GARRAVA 500ML', 300, 9.85];
 $_arr[] = ['13/03/2017', 'LIMPADOR VIDROS GARRAFA 350ML', 90, 12.30] ;
 $_arr[] = ['13/03/2017', 'CLORO GARRAFA 1 LITRO', 26, 6.99] ;

[iw]->arr=$_arr;

Evento onScriptInit:

//INCLUINDO NOSSA BIBLIOTECA EXTERNA
 sc_include_library("prj","DataGrid","class/DataGrid.class.php");

Evento onLoad:

$_arr=[iw]->arr;

//INSTANCIANDO A CLASSE COM 4 COLUNAS
 $dg2 = new DataGridForTCPDF(4);

//ADICIONANDO CABEÇALHOS DAS COLUNAS
 $dg2->addHeader(["DATA", 'PRODUTO', 'QUANTIDADE', 'VALOR VENDIDO']);

//ADICIONANDO ESTILO DE ALINHAMENTO AS COLUNAS
 $dg2->setStyle("Cell", 'style', 'text-align:center', '0');
 $dg2->setStyle("Cell", 'style', 'text-align:left', '1');
 $dg2->setStyle("Cell", 'style', 'text-align:right', '2');
 $dg2->setStyle("Cell", 'style', 'text-align:right', '3');

//INICIANDO TOTALIZADOR
 $total=0;

//PARA APLICAÇÃO DE LINHAS ZEBRADAS
 //$dg2->setZebraColor(TRUE);
 //$dg2->setZebraColor('LIGHTGRAY');

//LOOP DE LEITURA DOS REGISTROS
 foreach ($_arr as $value) {
 //FORÇAR COR DE FUNDO DA LINHA CASO DESEJE NÃO USAR A COR DO TEMA DO SCRIPTCASE
 //$dg2->setStyle("Row", 'style', 'background-color: WHITE');
 $total=$total+($value[2]*$value[3]);
 $value[3]='R$ '.number_format($value[3], 2, ',', '.');

//ADICIONANDO CADA CÉLULA
 $dg2->addCell($value);
 }
 //$dg2->setZebraColor(False);

//LINHA DE TOTAL
 //ADICIONANDO DIVISÃO DE CÉLULA PARA PRÓXIMA LINHA
 $dg2->setStyle('Cell', 'colspan', '2');

//ADICIONANDO VALOR PARA PRIMEIRA DIVISÃO
 $dg2->addCell('TOTAL DE VENDAS');

//TRABALHANDO NA SEGUNDA DIVISÃO DA CELULA
 $dg2->setStyle('Cell', 'colspan', '2');
 $dg2->setStyle('Cell', ' align', 'right');
 $dg2->setStyle('Cell', ' style', 'font-weight: bold');
 $dg2->addCell('R$ '.number_format($total, 2, ',', '.'));

//FINALIZANDO A TABELA E ADICIONANDO AO CAMPO VIRTUAL SCRIPTCASE
 {DataGridBasic} = $dg2->create();

Aplicando a classe a uma aplicação Report PDF:

Crie uma aplicação  Report PDF baseada no comando select:

Select 1 as none

Em Layout PDF/Código:

$this->Codigo();

Crie o método php com nome de Codigo com o código que se segue:

$total=0;

//REGISTROS A SEREM IMPRESSOS
$_arr[] = ['13/03/2017', 'ESPONJA DE LIMPEZA 4 UNIDADES', 100, 4.34] ;
$_arr[] = ['13/03/2017', 'SAPÓLIO GARRAFA DE 200ML', 100, 4.34] ;
$_arr[] = ['13/03/2017', 'SABÃO EM PÓ 500ML', 55, 7.50] ;
$_arr[] = ['13/03/2017', 'SABÃO EM PEDRA 4UNIDADES', 70, 3.30] ;
$_arr[] = ['10/03/2017', 'DETERGENTE GARRAFA 300ML', 280, 7.90];
$_arr[] = ['12/03/2017', 'DESINFETANTE GARRAVA 500ML', 300, 9.85];
$_arr[] = ['13/03/2017', 'LIMPADOR VIDROS GARRAFA 350ML', 90, 12.30] ;
$_arr[] = ['13/03/2017', 'CLORO GARRAFA 1 LITRO', 26, 6.99] ;
//INSTANCIANDO A CLASSE INFORMANDO QUE A TABELA CONTERÁ 4 COLUNAS
$dg = new DataGridForTCPDF(4);

//ESTILO DO CABEÇALHO
$dg->setStyle('Header_Cell', 'colspan', '4');

$dg->addHeader('TITULO DA TABELA');

$dg->setStyle("Header_Cell", 'width', '15%', 0);
$dg->setStyle("Header_Cell", 'width', '50%', 1);
$dg->setStyle("Header_Cell", 'width', '15%', 2);
$dg->setStyle("Header_Cell", 'width', '20%', 3);
$dg->addHeader(["DATA", 'PRODUTO', 'QUANTIDADE', 'VALOR VENDIDO']);

//ESTILO DAS COLUNAS
$dg->setStyle("Cell", 'style', 'text-align:center', '0');
$dg->setStyle("Cell", 'style', 'text-align:left', '1');
$dg->setStyle("Cell", 'style', 'text-align:right', '2');
$dg->setStyle("Cell", 'style', 'text-align:right', '3');
//$dg->setStyle("Cell", 'style', 'font-style: italic', 1);

//ADICIONANDO 
//REGISTROS A TABELA
//$dg->setZebraColor('LIGHTGRAY'); //INFORMANDO UMA COR AS LINHAS ZEBRADAS

$dg->setZebraColor(True);
foreach ($_arr as $value) {
    $total=$total+($value[2]*$value[3]);
    $value[3]='R$ '.number_format($value[3], 2, ',', '.');

   //REALÇANDO LINHA COM QUANTIDADE MAIOR OU IGUAL A 290

    if ($value[2]>=290){
        $dg->setStyle("Row", 'style', 'background-color: MediumSeaGreen');
        $dg->setStyle("Row", 'style', 'color: white');
    }

   //REALÇANDO LINHA COM QUANTIDADE MENOR QUE 50

    if ($value[2]<50){
        $dg->setStyle("Row", 'style', 'background-color: Salmon');
    }

    $dg->addCell($value);
}
$dg->setZebraColor(False);

//ESTILO DA LINHA DE TOTAL
$dg->setStyle('Row', 'style', 'font-size:large');
$dg->setStyle("Row", 'style', 'color: Blue');
$dg->setStyle('Cell', 'colspan', '2');
$dg->setStyle('Cell', ' align', 'center');
$dg->setStyle('Cell', ' style', 'font-weight: bold');
$dg->addCell('TOTAL DE VENDAS'); //;,'R$ 6.274,00']);

$dg->setStyle('Cell', 'colspan', '2');
$dg->setStyle('Cell', ' align', 'right');
$dg->setStyle('Cell', ' style', 'font-weight: bold');
$dg->addCell('R$ '.number_format($total, 2, ',', '.'));

//ESTILO DO RODAPÉ
$dg->setStyle("Row", 'style', 'color: #000');
$dg->setStyle('Row', 'style', 'font-weight: normal');
$dg->setStyle('Row', 'style', 'font-size:xx-small');
$dg->setStyle("Row", 'style', 'font-style: italic');
$dg->setStyle('Cell', ' align', 'center');
$dg->setStyle('Cell', 'colspan', '4');
$dg->addCell('RODAPÉ DA TABELA');

//GERANDO A TABELA

$html= $dg->create();

//IMPRIMINDO A TABELA NO PDF

$this->Pdf->writeHTML($html, true, false, false, false, '');

 

//IMPRIMINDO A TABELA NO PDF COM POSICIONAMENTO ABSOLUTO

//$this->Pdf->writeHTMLCell(100,100,105,100,$html) ;

Uma explicação dos exemplos acima em vídeo no Link:

Vídeo Parte 2 Clique Aqui

Vídeo Parte 3 Clique Aqui

Confira mais posts no nosso blog!

Por ,

23 de maio de 2018

Compartilhar esta postagem

a

Você pode gostar também…

Desenvolvimento de Software Impulsionado pela IA: O Papel do ChatGPT

No mundo em rápida evolução da tecnologia, a inteligência artificial (IA) está desempenhando u...

Low-Code: A Chave para a Transformação Digital Acessível

A transformação digital é um imperativo para empresas que desejam permanecer competitivas na era...

Tendências de TI para 2024: Rumo a Novos Horizontes Tecnológicos

O mundo da Tecnologia da Informação (TI) e do Desenvolvimento Web está em constante evolução, ...

Você pode gostar também…

Receba novas postagens, recursos, ofertas e muito mais a semanalmente.

Nós utilizaremos seu email para te adicionar a nossa Newsletter semanal. Você pode sair desta lista a qualquer momento clicando no link no final dos emails recebidos, ou entrar em contato conosco em vendas@scriptcase.com.br. Conheça nossa Política de Privacidade.