AM
Ajuda no relatório tabular
Bom dia Amigos, estou tentando criar um relatório, onde usei o relatório padrão , acrescentei algumas mudanças e esta dando erro se poderem me ajudar, pois não estou conseguindo resolver , ja estou 3 dias e não consigo, segue abai xo meu código e o erro que esta sendo apresentado.
o erro apresentado na tela
Fatal error: Uncaught Error: Call to a member function addRow() on null in C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php:385 Stack trace: #0 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php(342): FPDF->Header() #1 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php(619): FPDF->AddPage('P', Array, 0) #2 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibreportsTTableWriterPDF.class.php(172): FPDF->Cell(50, 15, '2018-10-04', 1, 0, 'L', true) #3 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosappcontrolsistemarelatoriosfornecedoresNotasfornecedoresReport.class.php(213): TTableWriterPDF->addCell('2018-10-04', 'left', 'datap') #4 [internal function]: NotasfornecedoresReport->onGenerate(Array) #5 C:xampphtdocsAdiantiProjetosUnitSoftwareLivroslibadianticontrolTPage.php(51): call_user_func(Array, Array) #6 C:xampphtdocsAdiantiProjetosUnitSoftwareLivroslibadianticontrolTPage.php(205): AdiantiControlTPage->run() #7 C:xamp in C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php on line 385
- <?php
- /**
- * NotasfornecedoresReport Report
- * @author <your name here>
- */
- class NotasfornecedoresReport extends TPage {
- protected $form; // form
- private static $paginas = 2;
- /**
- * Class constructor
- * Creates the page and the registration form
- */
- function __construct() {
- parent::__construct();
- // creates the form
- $this->form = new BootstrapFormBuilder('form_NotasfornecedoresModel_report');
- $this->form->setFormTitle('NotasfornecedoresModel Report');
- // create the form fields
- $tbl_NotasEmissao = new TDate('tbl_NotasEmissao', 'conexao', 'NotasfornecedoresModel', 'idtbl_Notas', 'tbl_NotasTipo');
- $tbl_NotasRecebimento = new TDate('tbl_NotasRecebimento', 'conexao', 'NotasfornecedoresModel', 'idtbl_Notas', 'tbl_NotasTipo');
- $tbl_fornecedores_idtbl_Fornecedores = new TDBCombo('tbl_fornecedores_idtbl_Fornecedores', 'conexao', 'FornecedoresModel', 'idtbl_Fornecedores', 'tbl_FornecedoresNome');
- $tbl_fornecedores_tbl_Empresa_idtbl_Empresa = new TDBCombo('tbl_fornecedores_tbl_Empresa_idtbl_Empresa', 'conexao', 'EmpresaModel', 'idtbl_Empresa', 'tbl_EmpresaNome');
- $output_type = new TRadioGroup('output_type');
- $tbl_NotasEmissao->setMask('dd/mm/yyyy');
- $tbl_NotasRecebimento->setMask('dd/mm/yyyy');
- // add the fields
- $this->form->addFields([new TLabel('Emissão :')], [$tbl_NotasEmissao]);
- $this->form->addFields([new TLabel('Recebimento :')], [$tbl_NotasRecebimento]);
- $this->form->addFields([new TLabel('Fornecedores :')], [$tbl_fornecedores_idtbl_Fornecedores]);
- $this->form->addFields([new TLabel(' Empresa :')], [$tbl_fornecedores_tbl_Empresa_idtbl_Empresa]);
- $this->form->addFields([new TLabel('Output')], [$output_type]);
- $output_type->addValidation('Output', new TRequiredValidator);
- // set sizes
- $tbl_NotasEmissao->setSize('100%');
- $tbl_NotasRecebimento->setSize('100%');
- $tbl_fornecedores_idtbl_Fornecedores->setSize('100%');
- $tbl_fornecedores_tbl_Empresa_idtbl_Empresa->setSize('100%');
- $output_type->setSize('100%');
- $output_type->addItems(array('html' => 'HTML', 'pdf' => 'PDF', 'rtf' => 'RTF', 'xls' => 'XLS'));
- $output_type->setLayout('horizontal');
- $output_type->setUseButton();
- $output_type->setValue('pdf');
- $output_type->setSize(70);
- // add the action button
- $btn = $this->form->addAction(_t('Generate'), new TAction(array($this, 'onGenerate')), 'fa:cog');
- $btn->class = 'btn btn-sm btn-primary';
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 90%';
- // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- parent::add($container);
- }
- public function getNativeWriter() {
- return $this->pdf;
- }
- public function Cabecalho($pdf) {
- try {
- // open a transaction with database 'conexao'
- TTransaction::open('conexao');
- // get the form data into an active record
- $data = $this->form->getData();
- $this->form->validate();
- $repository1 = new TRepository('FornecedoresModel');
- $criteria1 = new TCriteria;
- $objectos = $repository1->load($criteria1, FALSE);
- foreach ($objectos as $objecto) {
- $empresa = $objecto->empresa_model->tbl_EmpresaNome;
- }
- // fill the form with the active record data
- $this->form->setData($data);
- // close the transaction
- TTransaction::close();
- } catch (Exception $e) { // in case of exception
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- $numeroPagina = self::$paginas;
- $pdf->SetFont('Arial', 'I', 8);
- // TITULO
- $pdf->Cell(0, 0, "LIVRO FISCAL", 0, 0);
- $pdf->Cell(80);
- $pdf->PageNo();
- $pdf->Cell(0, 0, ("FL: {$numeroPagina} /{nb}"), 0, 0, 'R');
- $pdf->Ln(20);
- $pdf->Cell(0, 0, "REGISTRO DE ENTRADAS", 0, 0, 'C');
- $pdf->Ln(20);
- $pdf->Cell(100, 0, ( "EMPRESA : {$empresa}"), 0, 0);
- // Line break
- $pdf->Ln(20);
- self::$paginas++;
- }
- /**
- * Generate the report
- */
- function onGenerate() {
- try {
- // open a transaction with database 'conexao'
- TTransaction::open('conexao');
- // get the form data into an active record
- $data = $this->form->getData();
- $this->form->validate();
- $repository = new TRepository('NotasfornecedoresModel');
- $criteria = new TCriteria;
- if ($data->tbl_NotasEmissao) {
- $criteria->add(new TFilter('tbl_NotasEmissao', 'like', "%{$data->tbl_NotasEmissao}%"));
- }
- if ($data->tbl_NotasRecebimento) {
- $criteria->add(new TFilter('tbl_NotasRecebimento', 'like', "%{$data->tbl_NotasRecebimento}%"));
- }
- if ($data->tbl_fornecedores_idtbl_Fornecedores) {
- $criteria->add(new TFilter('tbl_fornecedores_idtbl_Fornecedores', 'like', "%{$data->tbl_fornecedores_idtbl_Fornecedores}%"));
- }
- if ($data->tbl_fornecedores_tbl_Empresa_idtbl_Empresa) {
- $criteria->add(new TFilter('tbl_fornecedores_tbl_Empresa_idtbl_Empresa', 'like', "%{$data->tbl_fornecedores_tbl_Empresa_idtbl_Empresa}%"));
- }
- $objects = $repository->load($criteria, FALSE);
- $format = $data->output_type;
- if ($objects) {
- $widths = array(50, 50, 100, 100);
- switch ($format) {
- case 'html':
- $tr = new TTableWriterHTML($widths);
- break;
- case 'pdf':
- $tr = new TTableWriterPDF($widths);
- $fpdf = $tr->getNativeWriter();
- $fpdf->setHeaderCallback(array($this, 'Cabecalho'));
- $this->Cabecalho($fpdf);
- break;
- case 'xls':
- $tr = new TTableWriterXLS($widths);
- break;
- case 'rtf':
- $tr = new TTableWriterRTF($widths);
- break;
- }
- // create the document styles
- $tr->addStyle('title', 'Arial', '10', 'B', '#ffffff', '#A3A3A3');
- $tr->addStyle('datap', 'Arial', '10', '', '#000000', '#EEEEEE');
- $tr->addStyle('datai', 'Arial', '10', '', '#000000', '#ffffff');
- $tr->addStyle('header', 'Arial', '12', 'I', '#ffffff', '#6B6B6B');
- $tr->addStyle('footer', 'Times', '10', 'I', '#000000', '#A3A3A3');
- // add titles row
- $tr->addRow();
- $tr->addCell('Emissão :', 'left', 'title');
- $tr->addCell('Recebimento :', 'left', 'title');
- $tr->addCell('Fornecedores :', 'right', 'title');
- $tr->addCell(' Empresa :', 'right', 'title');
- // controls the background filling
- $colour = FALSE;
- // data rows
- foreach ($objects as $object) {
- $style = $colour ? 'datap' : 'datai';
- $tr->addRow();
- $tr->addCell($object->tbl_NotasEmissao, 'left', $style);
- $tr->addCell($object->tbl_NotasRecebimento, 'left', $style);
- $tr->addCell($object->tbl_fornecedores_idtbl_Fornecedores, 'right', $style);
- $tr->addCell($object->tbl_fornecedores_tbl_Empresa_idtbl_Empresa, 'right', $style);
- $colour = !$colour;
- }
- // footer row
- $tr->addRow();
- $tr->addCell(date('Y-m-d h:i:s'), 'center', 'footer', 4);
- // stores the file
- if (!file_exists("app/output/NotasfornecedoresModel.{$format}") OR is_writable("app/output/NotasfornecedoresModel.{$format}")) {
- $tr->save("app/output/NotasfornecedoresModel.{$format}");
- } else {
- throw new Exception(_t('Permission denied') . ': ' . "app/output/NotasfornecedoresModel.{$format}");
- }
- // open the report file
- parent::openFile("app/output/NotasfornecedoresModel.{$format}");
- // shows the success message
- new TMessage('info', 'Report generated. Please, enable popups.');
- } else {
- new TMessage('error', 'No records found');
- }
- // fill the form with the active record data
- $this->form->setData($data);
- // close the transaction
- TTransaction::close();
- } catch (Exception $e) { // in case of exception
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- }
- ?>
o erro apresentado na tela
Fatal error: Uncaught Error: Call to a member function addRow() on null in C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php:385 Stack trace: #0 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php(342): FPDF->Header() #1 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php(619): FPDF->AddPage('P', Array, 0) #2 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibreportsTTableWriterPDF.class.php(172): FPDF->Cell(50, 15, '2018-10-04', 1, 0, 'L', true) #3 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosappcontrolsistemarelatoriosfornecedoresNotasfornecedoresReport.class.php(213): TTableWriterPDF->addCell('2018-10-04', 'left', 'datap') #4 [internal function]: NotasfornecedoresReport->onGenerate(Array) #5 C:xampphtdocsAdiantiProjetosUnitSoftwareLivroslibadianticontrolTPage.php(51): call_user_func(Array, Array) #6 C:xampphtdocsAdiantiProjetosUnitSoftwareLivroslibadianticontrolTPage.php(205): AdiantiControlTPage->run() #7 C:xamp in C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php on line 385
Qual a versão do Adianti? Executei seu código e gerou o pdf sem problemas
Oi Nataniel a versão é o 5 , meu problema está apartir da segunda folha, na primeira ele gera direito , quando tem mais de uma folha ele dá este erro. Talvez por não conseguir duplicar o header, pois sem ele funciona.
Chame a função setHeaderCallback sobre a variável com a instância da classe TTableWriterPDF ao invés de usar sobre a instância da FPDF:
Provavelmente você vai ter que fazer outros ajustes, mas é por aí...
Obrigado Nataniel, fiz a modificação e mais alguns ajustes , esta funcionando perfeito, um abraço.
Boa tarde Alexsander, como ficou o teu código, estou com o mesmo problema e não consegui resolver ainda.
Boa tarde meu amigo, sim está funcionando, mas o que está acontecendo com o seu código?
public function getNativeWriter() {
return $this->pdf;
}
public function Header()
{
TTransaction::open('patrimonio');
$header = new TRepository('Tbheader');
$criteria = new TCriteria;
$header = $header->load($criteria);
$this->SetXY(10,15); //SetXY - DEFINE O X E O Y NA PAGINA
$this->Rect(10,10,568,60); //CRIA UM RETÂNGULO QUE COMEÇA NO X = 10, Y = 10 E
//TEM 190 DE LARGURA E 280 DE ALTURA.
//NESTE CASO, É UMA BORDA DE PÁGINA.
//$designer->Ln(90);
$fill = TRUE;
$this->image('',15, 18, 36);
$this->SetFont('Arial','B',10); // DEFINE A FONTE ARIAL, NEGRITO (B), DE TAMANHO 8
foreach ($header as $h)
{
}
$this->setFontColorRGB( '#000000' );
$this->Setxy(55,15);
$this->Cell(185,15,utf8_decode($h->estado),0,1,'L');
$this->Setxy(55,29);
$this->Cell(170, 12, utf8_decode($h->nomeentidade), 0, 0, 'L');
$this->SetFont('Arial','I',10);
$this->Setxy(55,41);
$this->Cell(170, 12, utf8_decode($h->tipoentidade), 0, 0, 'L');
$this->Setxy(55,51);
$this->Cell(185,15,utf8_decode($h->setorpatrimonio),0,1,'L');
//$this->Ln(5);
TTransaction::close();
}
/**
* method onGenerate()
* Executed whenever the user clicks at the generate button
*/
function onGenerate()
{
try
{
// open a transaction with database 'patrimonio'
TTransaction::open('patrimonio');
// get the form data into an active record Customer
$object = $this->form->getData();
$repository = new TRepository('VwDepreciacaoDetalhe');
//$criteria->tbprincipal('order', 'tombo');
$criteria = new TCriteria;
$customers = $repository->load($criteria);
$format = $object->output_type;
$pdf = new FPDF('P','mm',array(100,200));
if ($customers)
{
$widths = array(30, 308, 70, 180, 50, 57, 48, 57);
switch ($format)
{
case 'html':
$tr = new TTableWriterHTML($widths);
break;
case 'pdf':
$tr = new TTableWriterPDF($widths, 'L');
$fpdf = $tr->getNativeWriter(); // ERRO AQUI*************
$fpdf->setHeaderCallback(array($this,'Header'));
$this->Header($fpdf);
break;
case 'rtf':
if (!class_exists('PHPRtfLite_Autoloader'))
{
PHPRtfLite::registerAutoloader();
}
$tr = new TTableWriterRTF($widths, 'L');
break;
}
if (!empty($tr))
{
// create the document styles
$tr->addStyle('title', 'Arial', '8', 'BI', '#000000', '#c6c4c0');
$tr->addStyle('datap', 'Arial', '7', '', '#000000', '#f2f0ed');
$tr->addStyle('datai', 'Arial', '7', '', '#000000', '#ffffff');
//$tr->addStyle('header2', 'Arial', '15', 'BI','#000000', '#ffffff');
$tr->addStyle('header', 'Arial', '14', 'I', '#000000', '#ffffff');
//$tr->addStyle('footer', 'Arial', '12', 'BI', '#2B2B2B', '#ffffff');
$tr->addStyle('total', 'Arial', '7', 'BI', '#222222', '#c6c4c0');
// add a header row
$tr->addRow();
$tr->addCell('Relação de Bens com Depreciação. (DETALHE)', 'C', 'header', 8);
//$tr->addRow();
//$tr->addCell('Relação', 'center', 'header', 6);
// add titles row
$tr->addRow();
$tr->addCell('Tombo', 'center', 'title');
$tr->addCell('Bem', 'center', 'title');
$tr->addCell('Condição', 'center', 'title');
$tr->addCell('Centro', 'center', 'title');
$tr->addCell('Inclusão', 'center', 'title');
$tr->addCell('Aquisição', 'center', 'title');
$tr->addCell('Dep', 'center', 'title');
$tr->addCell('Saldo', 'center', 'title');
// controls the background filling
$colour= FALSE;
$total = 0;
$total2 = 0;
$total3 = 0;
// data rows
foreach ($customers as $customer)
{
$style = $colour ? 'datap' : 'datai';
//$dataIinclusao=date('d/m/Y');
//$num = (2, ',', '.');
$tr->addRow();
$tr->addCell($customer->tombo, 'left', $style);
$tr->addCell($customer->nitem, 'left', $style);
$tr->addCell($customer->ncondicao, 'left', $style);
$tr->addCell($customer->ncentro, 'left', $style);
$tr->addCell(TDate::date2br($customer->dataInclusao), 'center', $style);
$tr->addCell(number_format($customer->valor_bem,2,",","."), 'rigth', $style);
$tr->addCell(number_format($customer->depreciacao_acumulada,2,",","."), 'rigth', $style);
$tr->addCell(number_format($customer->saldo_atual,2,",","."), 'rigth', $style);
$total+= $customer->valor_bem;
$total2+= $customer->depreciacao_acumulada;
$total3+= $customer->saldo_atual;
$colour = !$colour;
}
$valor_bem = number_format($total,2,',','.');
$depreciacao_acumulada = number_format($total2,2,',','.');
$saldo_atual = number_format($total3,2,',','.');
$tr->addRow();
//$tr->addCell('TOTAL: R$ ' . $saldo_atual, 'rigth', 'total', 8);
$tr->addCell('TOTAIS ', 'rigth', 'datai', 5);
$tr->addCell($valor_bem, 'rigth', 'total');
$tr->addCell($depreciacao_acumulada, 'rigth', 'total');
$tr->addCell($saldo_atual, 'rigth', 'total');
// stores the file
if (!file_exists("app/output/Bens.{$format}") OR is_writable("app/output/Bens.{$format}"))
{
$tr->save("app/output/Bens.{$format}");
}
else
{
throw new Exception(_t('Permission denied') . ': ' . "app/output/Bens.{$format}");
}
parent::openFile("app/output/Bens.{$format}");
// shows the success message
new TMessage('info', 'Relatório gerado com sucesso!');
}
}
else
{
new TMessage('error', 'Não existem registros para exibir!');
}
// fill the form with the active record data
$this->form->setData($object);
// close the transaction
TTransaction::close();
}
catch (Exception $e) // in case of exception
{
// shows the exception error message
new TMessage('error', 'Error ' . $e->getMessage());
// undo all pending operations
TTransaction::rollback();
}
}
Alexsander Maciel muito obrigado, mas eu consegui resolver de outra forma aqui.
Boa tarde,
peço desculpas pela demora pois estava em férias , mas para resolver a situção eu criei um topo separado , com as funções do pdf e os dados dentro do tablepdf. mas fico feliz por ter conseguido resolver. um abraço
Alexsander Maciel, estou com esse mesmo problema após atualizar o framework, poderia por gentileza postar seu código aqui pra eu dar uma olhada? Não estou conseguindo resolver!
Boa noite Joaby , peço desculpas , conseguiu resolver a questão ?
Ainda não consegui Alexsander.
Joaby vou postar o código hoje a noite, para te ajudar.
Boa Noite , eu fiz algumas mudanças conforme abaixo :
chamo a função neste trecho
case 'pdf':
$tr = new TTableWriterPDF($widths);
$tr->getNativeWriter();
$tr->setHeaderCallback(array($this, 'header'));
break;
e aqui na função
$dataInicio = explode('-', $data->tbl_NotasEmissao);
list($ano, $mes, $dia) = $dataInicio;
$numeroPagina = self::$paginas + $mes;
//$pdf = new FPDF('P', 'pt', 'A4'); // instancia a classe FPDF
//$pdf->AddPage();
//$pdf->AliasNbPages();
// create the document styles
$pdf->addStyle('titulo', 'Arial', '7', 'I', 0, '#ffffff', '#CCCCCC');
$pdf->addStyle('titulo_tabela', 'Arial', '6', 'B', '#000000', '#EEEEEE');
// TITULO
$pdf->addRow();
$pdf->addCell('LIVRO FISCAL ', 'left', 'titulo');
$pdf->addCell(("FL: {$numeroPagina}"), 'right', 'titulo', 8);
lembrando fi conforme minha necessidade, espero que ajude.