En este artículo vamos a presentar una clase externa en php desarrollada exclusivamente para usar con Scriptcase.
La clase resulta una tabla html formateada con Style In-line que se puede utilizar fácilmente en una aplicación de control, formulario, blank y Report PDF.

Cree una biblioteca con el nombre de DataGrid.

Añada una carpeta llamada class y en esta carpeta un archivo con nombre: DataGrid.class.php y copie el siguiente código para ese archivo:

<?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 ESTÁNDAR DE LA TABLA
 // $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 ESTÁNDAR DE LA CABECERA
 // $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 ESTÁNDAR DE LAS LÍNEAS
 $this->Style['Row']['style']['font-size'] = 'small';
 // $this->Style['Row']['style']['background-color'] = 'WHITE !IMPORTANT';

// TRADUCTOR 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;

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

// AGREGAR ESTILOS_SPC&SPC_ATRIBUTOS A UN 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;
 }

// RESETAR UN 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 AL ATRIBUTO STYLE
 private function agroup_styles($arr) {
 $styles = '';
 while ($val = current($arr)) {
 $styles .= key($arr) . ':' . $val . ';';
 next($arr);
 }
 $styles = ' style="' . $styles . '" ';
 return $styles;
 }

// ABRE EL TAG
 private function openTag($tagName) {

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

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

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

// ATRIBUTO DEL TEMP 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;

// ATRIBUTO PARA LA COLMNA
 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 .= ">";

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

return $tag;
 }

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

// ADICIONANDO LA CABECERA A LA TABLA
 public function addHeader($val) {

// ABRIENDO EL TAG DE LA CABECERA
 if (!$this->CellCount):
 $this->Html .= $this->openTag('Header');
 endif;

// ATRIBUYENDO VALOR DE LA CABECERA
 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;

// CERRANDO EL TAG DE LA CABECERA
 if ($this->CellCount >= $this->Columns):
 $this->Html .= $this->closeTag('Header');
 $this->CellCount = 0;
 endif;
 }

 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;
 }

// AGREGAR COLUMNAS
 public function addCell($val) {
 // ABRIENDO EL TAG DE UNA LÍNEA
 if (!$this->CellCount):
 $this->Html .= $this->openTag('Row');
 endif;

 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;

// CERRANDO EL TAG DE LA LINEA
 if ($this->CellCount >= $this->Columns):
 $this->Html .= $this->closeTag('Row');
 $this->CellCount = 0;
 endif;
 }

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

}

Descargar la clase DataGrid en formato de archivo zip: Clic Aquí

Vamos implementar ahora en una aplicación de Control:

Cree una aplicación de control y agregue un campo virtual de nombre DataGridBasic
Evento OnApplicationInit:

/CREANDO UNA BASE DE DADOS PARA PROBAR

//CREANDO UNA VARIABLE GLOBAL, OPCIONAL DE SALIDA, NO SESIÓN, NO POST, NO GET.
 

[iw]

= new StdClass; //REGISTROS A SER IMPRESOS $_arr[] = [’17/10/2018′, ‘ESPONJA DE LIMPIEZA 4 UNIDADES’, 100, 500000] ; $_arr[] = [’17/10/2018′, ‘JABÓN EN POLVO 500ML’, 100, 600000] ; $_arr[] = [’17/10/2018′, ‘JABÓN SÓLIDO 4 UNIDADES’, 55, 200000] ; $_arr[] = [’17/10/2018′, ‘DETERGENTE 300ML’, 70, 600000]; $_arr[] = [’17/10/2018′, ‘DESINFECTANTE 500ML’, 280, 1500000]; $_arr[] = [’17/10/2018′, ‘LIMPIADOR DE VIDRIOS 350ML’, 300, 2000000] ; $_arr[] = [’17/10/2018′, ‘CLORO 1 LITRO’, 90, 700000] ;

[iw]

->arr=$_arr;

Evento onScriptInit:

//INCLUYENDO NUESTRA BIBLIOTECA EXTERNA
 sc_include_library("prj","DataGrid","class/DataGrid.class.php");

Evento onLoad:

$_arr=[iw]->arr;

//INSTANCIANDO LA CLASE CON 4 COLUMNAS
 $dg2 = new DataGridForTCPDF(4);

//AGREGANDO CABECERAS A LAS COLUMNAS
 $dg2->addHeader(["DATA", 'PRODUCTO', 'CANTIDAD', 'VALOR VENDIDO']);

//AGREGANDO ESTILO DE ALINEAMIENTO A LAS COLUMNAS
 $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 ACUMULADOR
 $total=0;

//PARA LA APLICACIONES DE LINEAS
 //$dg2->setZebraColor(TRUE);
 //$dg2->setZebraColor('LIGHTGRAY');

//LOOP DE LECTURA DE LOS REGISTROS
 foreach ($_arr as $value) {
 //APLICAR COLOR DE FONDO DE LA LÍNEA CASO DE NO USAR EL COLOR DEL TEMA DEL SCRIPTCASE
 //$dgE2->setStyle("Row", 'style', 'background-color: WHITE');
 $total=$total+($value[2]*$value[3]);
 $value[3]='R$ '.number_format($value[3], 2, ',', '.');

 $dg2->addCell($value);
 }
 //$dg2->setZebraColor(False);

//LINEA DE TOTAL
 //AGREGANDO LA DIVISIÓN DE CELDA PARA LA SIGUIENTE LÍNEA
 $dg2->setStyle('Cell', 'colspan', '2');

//AGREGANDO UN VALOR
 $dg2->addCell('TOTAL DE VENDAS');

//SEGUNDA DIVISIÓN
 $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 LA TABLA Y ADICIONANDO AL CAMPO VIRTUAL SCRIPTCASE
 {DataGridBasic} = $dg2->create();

Aplicando la clase a una aplicación Informe PDF:

Cree una aplicación de informe PDF basada en el comando select:

Select 1 as none

En el Layout PDF/Código:

$this->Codigo();

Cree el método php con el nombre de código con el código siguiente:

$total=0;

//REGISTROS A SER IMPRESOS
 $_arr[] = ['17/10/2018', 'ESPONJA DE LIMPIEZA 4 UNIDADES', 100, 500000] ;
 $_arr[] = ['17/10/2018', 'JABÓN EN POLVO 500ML', 100, 600000] ;
 $_arr[] = ['17/10/2018', 'JABÓN SÓLIDO 4 UNIDADES', 55, 200000] ;
 $_arr[] = ['17/10/2018', 'DETERGENTE 300ML', 70, 600000];
 $_arr[] = ['17/10/2018', 'DESINFECTANTE 500ML', 280, 1500000];
 $_arr[] = ['17/10/2018', 'LIMPIADOR DE VIDRIOS 350ML', 300, 2000000] ;
 $_arr[] = ['17/10/2018', 'CLORO 1 LITRO', 90, 700000] ;
//INSTANCIANDO LA CLASE INFORMANDO QUE LA TABLA CONTENDRÁ 4 COLUMNAS
$dg = new DataGridForTCPDF(4);

//ESTILO DE LA CABECERA
$dg->setStyle('Header_Cell', 'colspan', '4');

$dg->addHeader('TITULO DE LA TABLA');

$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", 'PRODUCTO', 'CANTIDAD', 'VALOR VENDIDO']);

//ESTILO DE LAS COLUMNAS
$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 LA TABLA
//$dg->setZebraColor('LIGHTGRAY');

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

   //LÍNEA CON CANTIDAD MAYOR O IGUAL A 290

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

   //LÍNEA CON CANTIDAD MAYOR O IGUAL A 50
 if ($value[2]<50){
        $dg->setStyle("Row", 'style', 'background-color: Salmon');
    }

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

//ESTILO DE LA LÍNEA 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 DE LINEAS Y COLUMNAS
$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('ESTILO DE LA TABLA');

//GENERANDO LA TABLA
$html= $dg->create();

//IMPRIMIENDO LA TABLA EN PDF
$this->Pdf->writeHTML($html, true, false, false, false, '');

 

//IMPRIMIENDO LA TABLA EN EL PDF CON POSICIONAMIENTO ABSOLUTO

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

Ejemplo de PDF generado:

Clic Aquí

Una explicación de los ejemplos anteriores en vídeo en este enlace:

Video Parte 2, Clic Aquí

Video Parte 3, Clic Aquí

Mira mas blogspots aca!

Por ,

28 de February de 2019

Compartir esta publicacion

a

También podría gustarte…

Automatización de Procesos de Negocios con Scriptcase

En el mundo empresarial moderno, la eficiencia operativa no es solo un objetivo, es una necesidad. ...

Desarrollo de software impulsado por IA: el papel de ChatGPT

En el mundo en constante evolución de la tecnología, la inteligencia artificial (IA) está desemp...

Low-Code: La Clave para una Transformación Digital Accesible

La transformación digital es un imperativo para las empresas que desean mantenerse competitivas en...

También podría gustarte…

Obtenga nuevas publicaciones, recursos, ofertas y más cada semana.

Utilizaremos la información provista para enviarle por correo electrónico boletines y ofertas. Puede darse de baja de los correos electrónicos en cualquier momento simplemente haciendo clic en el enlace "unsubscribe" en la parte inferior de cualquier correo electrónico o contactándonos a privacy @ scriptcase.net . Obtenga más información sobre nuestra Privacy Police .