EM
Reproduzir Cards em PDF com FPDF
Olá pessoal!
Gerando relatório com DomPdf fica muito difícil quando se mexe com imagens, muito pesado e às vezes nem carrega.
Diante desse problema desenvolvi código para esse fim usando a classe fpdf.
Vou postar a classe baseada na TTableWriterPDF do framework com algumas alterações para:
- Gerar Títulos e rodapés
- Condensar texto para não estourar a célula ou cortar o texto
- Gerar Elipses e círculos
- Repetir ou não o cabeçalho
- Otimizado para gerar etiquetas tais como de endereçamento e códigos de barras (Essa parte em especial que foi aproveitada para reproduzir os cards que, para imprimir, não passam de etiquetas formatadas)
Essa classe coloco na pasta app/lib/reports mas pode colocar em qualquer pasta de sua escolha dentro da pasta app/lib
TTableWriterPDFCustom.php
Método: onPrintCards (bloco 1)
Nesse bloco defino os parâmetros do relatório
Método: onPrintCards (bloco 2)
Nesse trecho, já com os dados disponíveis, começo a percorrer o relatório e alterando as variáveis necessárias para chegar ao resultado desejado
Método: onPrintCards (bloco 3)
Nesse trecho quero enfatizar que desejo imprimir as linhas do retângulo do card, portanto façam as alterações que achem necessário.
Com a altura definida retiro o valor da altura da célula de cada linha dessa altura para, ao final, fechar o retângulo
Observação: general_functions::utf2iso()
Método: onPrintCards (bloco Final)
Como informado anteriormente, aqui fecho o quadro retiran 1,5mm para que os cards não se encostem
e por fim, insiro a imagem no relatório caso tenha informado true para o parâmetro $withImg
Pronto!
Em anexo coloco o arquivo pdf gerado para que tenham ideia do que vai sair desse código.
Gerando relatório com DomPdf fica muito difícil quando se mexe com imagens, muito pesado e às vezes nem carrega.
Diante desse problema desenvolvi código para esse fim usando a classe fpdf.
Vou postar a classe baseada na TTableWriterPDF do framework com algumas alterações para:
- Gerar Títulos e rodapés
- Condensar texto para não estourar a célula ou cortar o texto
- Gerar Elipses e círculos
- Repetir ou não o cabeçalho
- Otimizado para gerar etiquetas tais como de endereçamento e códigos de barras (Essa parte em especial que foi aproveitada para reproduzir os cards que, para imprimir, não passam de etiquetas formatadas)
Essa classe coloco na pasta app/lib/reports mas pode colocar em qualquer pasta de sua escolha dentro da pasta app/lib
TTableWriterPDFCustom.php
- <?php require_once('app/lib/pdf/FPDF.php');
- class TTableWriterPDFCustom extends FPDF
- {
- private $styles;
- private $pdf;
- private $widths;
- private $colcounter;
- private $colHeader;//Título do Relatório
- private $qtdeCol;
- private $titleRepeat;
- private $countTitle;
- private $orientation;//servirá como base de consulta para rodape
- private $unit; //servirá como base de consulta para addcell
- private $etiq;
- /**
- * Construtor da classe wf_fpdf inicializa a classe
- * @return object
- * @access public
- */
- function TTableWriterPDFCustom($widths,$head,$cols,$titleRepeat=TRUE,$orientation='P', $unit='mm', $format='A4',$isEtiq = FALSE)
- {
- //Informa se é para repetir título do relatório em todas as paginas ou só na primeira
- $this->titleRepeat = $titleRepeat;
- $this->orientation = $orientation;
- $this->unit = $unit;
- // armazena as larguras
- $this->widths = $widths;
- // inicializa atributos
- $this->styles = array();
- $this->colHeader = array();
- $this->colHeader=$head;
- $this->countTitle = 0;
- $this->setQtdeCol($cols);
- $this->etiq = $isEtiq;
- // create the document styles
- $this->addStyle('title', 'helvetica', '9', 'BI', '#000000', '#EEEEE0');
- $this->addStyle('subtitle', 'helvetica', '9', 'BI', '#000000', '#EEEEE0');
- $this->addStyle('datap', 'helvetica', '8', '', '#000000', '#E8E8E8');
- $this->addStyle('datai', 'helvetica', '8', '', '#000000', '#ffffff');
- $this->addStyle('header', 'helvetica', '16', 'B', '#000000', '#EEEEE0');
- $this->addStyle('footer', 'helvetica', '12', 'BI', '#000000', '#EEEEE0');
- $this->addStyle('total', 'helvetica', '9', '', '#000000', '#EEEEE0');
- $this->addStyle('subtotal', 'helvetica', '9', '', '#000000', '#EEEEE0');
- $this->addStyle('branco', 'helvetica', '16', '', '#000000', '#ffffff');
- $this->addStyle('totalCol', 'helvetica', '8', 'BI', '#000000', '#EEEEE0');
- //$this->addStyle('title' , 'helvetica', '8', 'BI', '#000000', '#EEEEE0');
- $this->addStyle('titleWhite' , 'helvetica', '8', 'BI', '#000000', '#FFFFFF');
- $this->addStyle('titleRed' , 'helvetica', '8', 'BI', 'red' , '#ffffff');
- $this->addStyle('titleBlue' , 'helvetica', '8', 'BI', '#1E90FF', '#ffffff');
- $this->addStyle('titleYellow' , 'helvetica', '8', 'BI', '#000000', '#FFFF00');
- $this->addStyle('titleYellowGreen', 'helvetica', '8', 'BI', '#3CB371', '#FFFF00');
- $this->addStyle('titleOrange' , 'helvetica', '8', 'BI', '#000000', '#FFA500');
- $this->addStyle('titleGreen' , 'helvetica', '8', 'BI', '#000000', '#3CB371');
- //$this->addStyle('datap' , 'helvetica', '8', '' , '#000000', '#E8E8E8');
- //$this->addStyle('datai' , 'helvetica', '8', '' , '#000000', '#ffffff');
- //$this->addStyle('totalCol' , 'helvetica', '8', '' , '#000000', '#EEEEE0');
- // define o locale
- setlocale(LC_ALL, 'POSIX');
- //$this->headerFunction = "";
- //$this->footerFunction = "";
- parent::__construct($orientation, $unit, $format);
- }
- public function setQtdeCol($qtde)
- {
- $this->qtdeCol = $qtde;
- }
- function Footer()
- {
- /** VERIFICA SE É ETIQUETA OU NAO **/
- if ($this->etiq == FALSE) {
- //$this->SetY(-25);
- //Linha
- //$this->SetLineWidth(0.1);
- //$this->Line(10, -30, 10, -35);
- $this->SetY(-19);
- $this->SetFont('Arial','I',7);
- $this->SetTextColor(28, 134, 238); // cor da fonte
- if ($this->orientation == 'L') {
- $this->Cell(285,7,utf8_decode('Emissão: '.aux_db::dateHour2br(date('Y-m-d H:i:s'))).utf8_decode(' - Página ').$this->PageNo().' de {nb}','0','0','R');
- } elseif($this->orientation == 'P') {
- $this->Cell(190,7,utf8_decode('Emissão: '.aux_db::dateHour2br(date('Y-m-d H:i:s'))).utf8_decode(' - Página ').$this->PageNo().' de {nb}','0','0','R');
- }
- $this->SetY(-19);
- $this->Cell(285, 7, utf8_decode('Copyright © EMS Tecnologia'),'0','0','L');
- }
- }
- function Header()
- {
- //$this->SetY(10);
- /** VERIFICA SE É ETIQUETA OU NAO **/
- if ($this->etiq == FALSE) {
- /** Adicionamos o Titulo do Relatório **/
- if ($this->colHeader['titulo']) {
- //verifica se é para repetir em todas
- if ($this->titleRepeat) {
- $this->addRow();//adiciona linha
- $this->addCell($this->colHeader['titulo'][0], $this->colHeader['titulo'][1], $this->colHeader['titulo'][2], $this->colHeader['titulo'][3]);
- if (($this->colHeader['coluna'])) {//Verifica se existe colunas enviadas para formar o cabeçalho
- // create the document styles
- $totCol = intval($this->qtdeCol);
- $this->addRow();//adiciona linha
- for ($c = 0;$c<=$totCol;$c++)
- {
- if (isset($this->colHeader['coluna'][$c][0])) {
- if (intval($this->colHeader['coluna'][$c][3]) > 0) {//Verifica se tem colspan
- $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2], $this->colHeader['coluna'][$c][3]);
- } else {
- $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2]);
- }
- }
- }
- }
- } else {
- if ($this->countTitle ==0) {
- $this->addRow();//adiciona linha
- $this->addCell($this->colHeader['titulo'][0], $this->colHeader['titulo'][1], $this->colHeader['titulo'][2], $this->colHeader['titulo'][3]);
- if (($this->colHeader['coluna'])) {//Verifica se existe colunas enviadas para formar o cabeçalho
- // create the document styles
- $totCol = intval($this->qtdeCol);
- $this->addRow();//adiciona linha
- for ($c = 0;$c<=$totCol;$c++)
- {
- if (isset($this->colHeader['coluna'][$c][0])) {
- if (intval($this->colHeader['coluna'][$c][3]) > 0) {//Verifica se tem colspan
- $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2], $this->colHeader['coluna'][$c][3]);
- } else {
- $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2]);
- }
- }
- }
- }
- } else {
- if (($this->colHeader['coluna'])) {//Verifica se existe colunas enviadas para formar o cabeçalho
- // create the document styles
- $totCol = intval($this->qtdeCol);
- $this->addRow();//adiciona linha
- for ($c = 0;$c<=$totCol;$c++)
- {
- if (isset($this->colHeader['coluna'][$c][0])) {
- if (intval($this->colHeader['coluna'][$c][3]) > 0) {//Verifica se tem colspan
- $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2], $this->colHeader['coluna'][$c][3]);
- } else {
- $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2]);
- }
- }
- }
- }
- }
- $this->countTitle +=1;
- }
- }
- $this->addRow();//adiciona linha
- }
- }
- public function Circle($x, $y, $r, $style='D')
- {
- $this->Ellipse($x,$y,$r,$r,$style);
- }
- public function Ellipse($x, $y, $rx, $ry, $style='D')
- {
- if($style=='F')
- $op='f';
- elseif($style=='FD' || $style=='DF')
- $op='B';
- else
- $op='S';
- $lx=4/3*(M_SQRT2-1)*$rx;
- $ly=4/3*(M_SQRT2-1)*$ry;
- $k=$this->k;
- $h=$this->h;
- $this->_out(sprintf('%.2F %.2F m %.2F %.2F %.2F %.2F %.2F %.2F c',
- ($x+$rx)*$k,($h-$y)*$k,
- ($x+$rx)*$k,($h-($y-$ly))*$k,
- ($x+$lx)*$k,($h-($y-$ry))*$k,
- $x*$k,($h-($y-$ry))*$k));
- $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
- ($x-$lx)*$k,($h-($y-$ry))*$k,
- ($x-$rx)*$k,($h-($y-$ly))*$k,
- ($x-$rx)*$k,($h-$y)*$k));
- $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
- ($x-$rx)*$k,($h-($y+$ly))*$k,
- ($x-$lx)*$k,($h-($y+$ry))*$k,
- $x*$k,($h-($y+$ry))*$k));
- $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c %s',
- ($x+$lx)*$k,($h-($y+$ry))*$k,
- ($x+$rx)*$k,($h-($y+$ly))*$k,
- ($x+$rx)*$k,($h-$y)*$k,
- $op));
- }
- /**
- * Adiciona um novo estilo
- * @param @stylename nome do estilo
- * @param @fontface nome da fonte
- * @param @fontsize tamanho da fonte
- * @param @fontstyle estilo da fonte (B=bold, I=italic)
- * @param @fontcolor cor da fonte
- * @param @fillcolor cor de preenchimento
- */
- public function addStyle($stylename, $fontface, $fontsize, $fontstyle, $fontcolor, $fillcolor)
- {
- $this->styles[$stylename] = array($fontface, $fontsize, $fontstyle, $fontcolor, $fillcolor);
- }
- public function addColHeader($type, $nomeCol, $align, $style, $colspan)
- {
- $this->colHeader[$type] = array($nomeCol, $align, $style, $colspan);
- }
- public function clearColHeader()
- {
- $this->colHeader = array();
- }
- /**
- * Aplica um estilo
- * @param $stylename nome do estilo
- */
- public function applyStyle($stylename)
- {
- // verifica se o estilo existe
- if (isset($this->styles[$stylename]))
- {
- $style = $this->styles[$stylename];
- // obtém os atributos do estilo
- $fontface = $style[0];
- $fontsize = $style[1];
- $fontstyle = $style[2];
- $fontcolor = $style[3];
- $fillcolor = $style[4];
- // aplica os atributos do estilo
- $this->SetFont($fontface, $fontstyle); // fonte
- $this->SetFontSize($fontsize); // estilo
- $colorarray = self::rgb2int255($fontcolor);
- // cor do texto
- $this->SetTextColor($colorarray[0], $colorarray[1], $colorarray[2]);
- $colorarray = self::rgb2int255($fillcolor);
- // cor de preenchimento
- $this->SetFillColor($colorarray[0], $colorarray[1], $colorarray[2]);
- }
- }
- /**
- * Converte uma cor em RGB para um vetor de decimais
- * @param $rgb uma string contendo uma cor em RGB
- */
- private function rgb2int255($rgb)
- {
- $red = hexdec(substr($rgb,1,2));
- $green = hexdec(substr($rgb,3,2));
- $blue = hexdec(substr($rgb,5,2));
- return array($red, $green, $blue);
- }
- /**
- * Adiciona uma nova linha na tabela
- */
- public function addRow()
- {
- $this->Ln(); // quebra de linha
- $this->colcounter = 0;
- }
- /**
- * Adiciona uma nova célula na linha atual da tabela
- * @param $content conteúdo da célula
- * @param $align alinhamento da célula
- * @param $stylename nome do estilo a ser utilizado
- * @param $colspan quantidade de células a serem mescladas
- * @param $cellplus valor que altera a altura da célula
- * @param $fundo valor que define se o fundo da célula será desenhado ou não desenhado (true), transparente (false)
- */
- function addCell($content, $align, $stylename, $colspan = 1, $border = 1,$cellplus = 0.5,$fundo = true)
- {
- if (is_null($stylename) OR !isset($this->styles[$stylename]) )
- {
- throw new Exception(TAdiantiCoreTranslator::translate('Style ^1 not found in ^2', $stylename, __METHOD__ ) );
- }
- if ($fundo == true) {
- $this->applyStyle($stylename); // aplica o estilo
- }
- $fontsize = $this->styles[$stylename][1]; // obtém a fonte
- if (utf8_encode(utf8_decode($content)) == $content ) // SE UTF8
- {
- $content = utf8_decode($content);
- }
- $width = 0;
- // calcula a largura da célula (incluindo as mescladas)
- for ($n=$this->colcounter; $n<$this->colcounter+$colspan; $n++)
- {
- $width += $this->widths[$n];
- }
- // exibe a célula com o conteúdo passado
- $this->Cell( $width, $fontsize * $cellplus, $content, $border, 0, strtoupper(substr($align,0,1)), true);
- //Atualiza o valor de n quando o colspan é maior que 1
- if ($colspan > 1) {
- $this->colcounter += $colspan;
- } else {
- $this->colcounter ++;
- }
- }
- /**
- * Adiciona uma nova célula na linha atual da tabela
- * @param $content conteúdo da célula
- * @param $align alinhamento da célula
- * @param $stylename nome do estilo a ser utilizado
- * @param $colspan quantidade de células a serem mescladas
- * @param $cellplus valor que altera a altura da célula
- */
- function addMultiCell($content, $align, $stylename, $colspan = 1, $border = 1,$cellplus = 0.5)
- {
- if (is_null($stylename) OR !isset($this->styles[$stylename]) )
- {
- throw new Exception(TAdiantiCoreTranslator::translate('Style ^1 not found in ^2', $stylename, __METHOD__ ) );
- }
- $this->applyStyle($stylename); // aplica o estilo
- $fontsize = $this->styles[$stylename][1]; // obtém a fonte
- if (utf8_encode(utf8_decode($content)) == $content ) // SE UTF8
- {
- $content = utf8_decode($content);
- }
- $width = 0;
- // calcula a largura da célula (incluindo as mescladas)
- for ($n=$this->colcounter; $n<$this->colcounter+$colspan; $n++)
- {
- $width += $this->widths[$n];
- }
- // exibe a célula com o conteúdo passado
- $this->MultiCell( $width, $fontsize * $cellplus, $content, $border, 0, strtoupper(substr($align,0,1)), true);
- //Atualiza o valor de n quando o colspan é maior que 1
- if ($colspan > 1) {
- $this->colcounter += $colspan;
- } else {
- $this->colcounter ++;
- }
- }
- /**
- * DashedLine
- * Desenha uma linha horizontal tracejada com o FPDF
- * @package NFePHP
- * @name DashedHLine
- * @version 1.0.1
- * @author Roberto L. Machado <linux.rlm at gmail dot com>
- * @param number $x Posição horizontal inicial, em mm
- * @param number $y Posição vertical inicial, em mm
- * @param number $w Comprimento da linha, em mm
- * @param number $h Espessura da linha, em mm
- * @param number $n Numero de traços na seção da linha com o comprimento $w
- * @return none
- */
- public function DashedHLine($x,$y,$w,$h,$n) {
- $this->SetDrawColor(110);
- $this->SetLineWidth($h);
- $wDash=($w/$n)/2; // comprimento dos traços
- for( $i=$x; $i<=$x+$w; $i += $wDash+$wDash ) {
- for( $j=$i; $j<= ($i+$wDash); $j++ ) {
- if( $j <= ($x+$w-1) ) {
- $this->Line($j,$y,$j+1,$y);
- }
- }
- }
- $this->SetDrawColor(0);
- } //fim função DashedHLine
- /**
- * DashedVLine
- * Desenha uma linha vertical tracejada com o FPDF
- * @package NFePHP
- * @name DashedVLine
- * @version 1.0
- * @author Roberto L. Machado <linux.rlm at gmail dot com>
- * @author Guilherme Calabria Filho <guiga86 at gmail dot com>
- * @param number $x Posição horizontal inicial, em mm
- * @param number $y Posição vertical inicial, em mm
- * @param number $w Comprimento da linha, em mm
- * @param number $yfinal Espessura da linha, em mm
- * @param number $n Numero de traços na seção da linha com o comprimento $w
- * @return none
- */
- public function DashedVLine($x,$y,$w,$yfinal,$n) {
- $this->SetLineWidth($w);
- //Organizando valores
- if($y>$yfinal) {
- $aux = $yfinal;
- $yfinal = $y;
- $y = $aux;
- }
- while($y<$yfinal&&$n>0){
- $this->Line($x,$y,$x,$y+1);
- $y += 3;
- $n--;
- }
- } //fim função DashedVLine
- public function SetDash($black=null, $white=null)
- {
- if($black!==null)
- $s=sprintf('[%.3F %.3F] 0 d',$black*$this->k,$white*$this->k);
- else
- $s='[] 0 d';
- $this->_out($s);
- }
- /*
- * align: allows to center or align the text. Possible values are:
- U: top
- C: center (default value)
- D: bottom
- */
- public function VCell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false)
- {
- //Output a cell
- $k=$this->k;
- if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak())
- {
- //Automatic page break
- $x=$this->x;
- $ws=$this->ws;
- if($ws>0)
- {
- $this->ws=0;
- $this->_out('0 Tw');
- }
- $this->AddPage($this->CurOrientation,$this->CurPageSize);
- $this->x=$x;
- if($ws>0)
- {
- $this->ws=$ws;
- $this->_out(sprintf('%.3F Tw',$ws*$k));
- }
- }
- if($w==0)
- $w=$this->w-$this->rMargin-$this->x;
- $s='';
- // begin change Cell function
- if($fill || $border>0)
- {
- if($fill)
- $op=($border>0) ? 'B' : 'f';
- else
- $op='S';
- if ($border>1) {
- $s=sprintf('q %.2F w %.2F %.2F %.2F %.2F re %s Q ',$border,
- $this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
- }
- else
- $s=sprintf('%.2F %.2F %.2F %.2F re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
- }
- if(is_string($border))
- {
- $x=$this->x;
- $y=$this->y;
- if(is_int(strpos($border,'L')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
- else if(is_int(strpos($border,'l')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
- if(is_int(strpos($border,'T')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
- else if(is_int(strpos($border,'t')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
- if(is_int(strpos($border,'R')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- else if(is_int(strpos($border,'r')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- if(is_int(strpos($border,'B')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- else if(is_int(strpos($border,'b')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- }
- if(trim($txt)!='')
- {
- $cr=substr_count($txt,"\n");
- if ($cr>0) { // Multi line
- $txts = explode("\n", $txt);
- $lines = count($txts);
- for($l=0;$l<$lines;$l++) {
- $txt=$txts[$l];
- $w_txt=$this->GetStringWidth($txt);
- if ($align=='U')
- $dy=$this->cMargin+$w_txt;
- elseif($align=='D')
- $dy=$h-$this->cMargin;
- else
- $dy=($h+$w_txt)/2;
- $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
- if($this->ColorFlag)
- $s.='q '.$this->TextColor.' ';
- $s.=sprintf('BT 0 1 -1 0 %.2F %.2F Tm (%s) Tj ET ',
- ($this->x+.5*$w+(.7+$l-$lines/2)*$this->FontSize)*$k,
- ($this->h-($this->y+$dy))*$k,$txt);
- if($this->ColorFlag)
- $s.=' Q ';
- }
- }
- else { // Single line
- $w_txt=$this->GetStringWidth($txt);
- $Tz=100;
- if ($w_txt>$h-2*$this->cMargin) {
- $Tz=($h-2*$this->cMargin)/$w_txt*100;
- $w_txt=$h-2*$this->cMargin;
- }
- if ($align=='U')
- $dy=$this->cMargin+$w_txt;
- elseif($align=='D')
- $dy=$h-$this->cMargin;
- else
- $dy=($h+$w_txt)/2;
- $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
- if($this->ColorFlag)
- $s.='q '.$this->TextColor.' ';
- $s.=sprintf('q BT 0 1 -1 0 %.2F %.2F Tm %.2F Tz (%s) Tj ET Q ',
- ($this->x+.5*$w+.3*$this->FontSize)*$k,
- ($this->h-($this->y+$dy))*$k,$Tz,$txt);
- if($this->ColorFlag)
- $s.=' Q ';
- }
- }
- // end change Cell function
- if($s)
- $this->_out($s);
- $this->lasth=$h;
- if($ln>0)
- {
- //Go to next line
- $this->y+=$h;
- if($ln==1)
- $this->x=$this->lMargin;
- }
- else
- $this->x+=$w;
- }
- /*
- * border: indicates if borders must be drawn around the cell. The value can be either a number:
- 0: no border
- >0: frame of the corresponding width
- or a string containing some or all of the following characters (in any order):
- L: left
- T: top
- R: right
- B: bottom
- or for bold border:
- l: left
- t: top
- r: right
- b: bottom
- Default value: 0.
- */
- public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
- {
- //Output a cell
- $k=$this->k;
- if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak())
- {
- //Automatic page break
- $x=$this->x;
- $ws=$this->ws;
- if($ws>0)
- {
- $this->ws=0;
- $this->_out('0 Tw');
- }
- $this->AddPage($this->CurOrientation,$this->CurPageSize);
- $this->x=$x;
- if($ws>0)
- {
- $this->ws=$ws;
- $this->_out(sprintf('%.3F Tw',$ws*$k));
- }
- }
- if($w==0)
- $w=$this->w-$this->rMargin-$this->x;
- $s='';
- // begin change Cell function
- if($fill || $border>0)
- {
- if($fill)
- $op=($border>0) ? 'B' : 'f';
- else
- $op='S';
- if ($border>1) {
- $s=sprintf('q %.2F w %.2F %.2F %.2F %.2F re %s Q ',$border,
- $this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
- }
- else
- $s=sprintf('%.2F %.2F %.2F %.2F re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
- }
- if(is_string($border))
- {
- $x=$this->x;
- $y=$this->y;
- if(is_int(strpos($border,'L')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
- else if(is_int(strpos($border,'l')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
- if(is_int(strpos($border,'T')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
- else if(is_int(strpos($border,'t')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
- if(is_int(strpos($border,'R')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- else if(is_int(strpos($border,'r')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- if(is_int(strpos($border,'B')))
- $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- else if(is_int(strpos($border,'b')))
- $s.=sprintf('q 2 w %.2F %.2F m %.2F %.2F l S Q ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
- }
- if (trim($txt)!='') {
- $cr=substr_count($txt,"\n");
- if ($cr>0) { // Multi line
- $txts = explode("\n", $txt);
- $lines = count($txts);
- for($l=0;$l<$lines;$l++) {
- $txt=$txts[$l];
- $w_txt=$this->GetStringWidth($txt);
- if($align=='R')
- $dx=$w-$w_txt-$this->cMargin;
- elseif($align=='C')
- $dx=($w-$w_txt)/2;
- else
- $dx=$this->cMargin;
- $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
- if($this->ColorFlag)
- $s.='q '.$this->TextColor.' ';
- $s.=sprintf('BT %.2F %.2F Td (%s) Tj ET ',
- ($this->x+$dx)*$k,
- ($this->h-($this->y+.5*$h+(.7+$l-$lines/2)*$this->FontSize))*$k,
- $txt);
- if($this->underline)
- $s.=' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt);
- if($this->ColorFlag)
- $s.=' Q ';
- if($link)
- $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$w_txt,$this->FontSize,$link);
- }
- }
- else { // Single line
- $w_txt=$this->GetStringWidth($txt);
- $Tz=100;
- if ($w_txt>$w-2*$this->cMargin) { // Need compression
- $Tz=($w-2*$this->cMargin)/$w_txt*100;
- $w_txt=$w-2*$this->cMargin;
- }
- if($align=='R')
- $dx=$w-$w_txt-$this->cMargin;
- elseif($align=='C')
- $dx=($w-$w_txt)/2;
- else
- $dx=$this->cMargin;
- $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
- if($this->ColorFlag)
- $s.='q '.$this->TextColor.' ';
- $s.=sprintf('q BT %.2F %.2F Td %.2F Tz (%s) Tj ET Q ',
- ($this->x+$dx)*$k,
- ($this->h-($this->y+.5*$h+.3*$this->FontSize))*$k,
- $Tz,$txt);
- if($this->underline)
- $s.=' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt);
- if($this->ColorFlag)
- $s.=' Q ';
- if($link)
- $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$w_txt,$this->FontSize,$link);
- }
- }
- // end change Cell function
- if($s)
- $this->_out($s);
- $this->lasth=$h;
- if($ln>0)
- {
- //Go to next line
- $this->y+=$h;
- if($ln==1)
- $this->x=$this->lMargin;
- }
- else
- $this->x+=$w;
- }
- /**
- * Armazena o conteúdo do documento em um arquivo
- * @param $filename caminho para o arquivo de saída
- */
- public function save($filename)
- {
- $this->Output($filename);
- return TRUE;
- }
- } ?>
Método: onPrintCards (bloco 1)
Nesse bloco defino os parâmetros do relatório
- <?php /**
- * Método onPrintCardsPrecos
- *
- * @param $dados object Objeto com dados para impressão
- * @param $mesq string Margem esquerda
- * @param $mdir string Margem direita
- * @param $msup string Margem Superior
- * @param $leti string Largura Etiqueta
- * @param $aeti string Altura Etiqueta
- * @param $ehet string Espaço horizontal entre etiquetas
- * @param $nCol string Número de Colunas
- * @param $nLinhas Número de Linhas
- * @param $withImg define se é para mostrar imagem ou não, serve para os casos eu que se imprime o mesmo relatório com imagem e sem imagem
- * */
- public static function onPrintCardsResumo($dados,$mesq = 8,$mdir = 8,$msup = 10,$leti = 63.5,$aeti = 25.4,$ehet = 2.6,$nCol = 3,$nLinhas = 4,$withImg=FALSE)
- {
- try
- {
- //$objects = $repository->load($criteria);
- $format = 'pdf';
- $totCol = 1;
- $orientation = 'P';
- $unit = 'mm';
- $paper = 'A4';
- if ($dados)
- {
- $widths = array($leti);
- /** CABEÇALHO - deve ser definido antes de estanciar a classe TTableWriterPDFCustom para ser enviado como parâmetro **/
- $titCol = array();
- $titCol['titulo'] = array('', 'center', 'header', $totCol);//Título do Relatório
- //Colunas
- $titCol['coluna'][0] = array( '', 'center', 'title',0);
- $tr = new TTableWriterPDFCustom($widths,$titCol, $totCol,FALSE,$orientation,$unit,$paper,TRUE);
- // define o locale
- setlocale(LC_ALL, 'POSIX');
- $tr->AddPage(); // adiciona uma página
- //$tr->AliasNbPages('{nb}');
- $tr->SetAutoPageBreak(TRUE,3);
- // define cores e fontes para os títulos da tabela
- $tr->SetFillColor(130,80,70); // cor de fundo
- $tr->SetTextColor(0,0,0); // cor da fonte
- $tr->SetFont('arial','',10); // fonte
- // set margins
- $tr->SetMargins($mesq, $msup,$mdir);
- // controls the background filling
- $coluna = 0;
- $linha = 0;
- $alturaQuado= 0; ?>
Método: onPrintCards (bloco 2)
Nesse trecho, já com os dados disponíveis, começo a percorrer o relatório e alterando as variáveis necessárias para chegar ao resultado desejado
- <?php foreach ($dados as $dado)
- {
- $alturaQuado = $aeti;
- if($coluna == $nCol) { // Se for a última coluna
- // $columnDefault = true; // $coluna volta para o valor inicial
- $coluna = 0;
- $linha++; // $linha volta ao seu valor inicial
- }
- if($linha == $nLinhas) { // Se for a última linha da página
- // $addPage = true;
- $tr->AddPage(); // Adiciona uma nova página
- $linha = 0; // $linha volta ao seu valor inicial
- }
- $posicaoH = $coluna*$leti;
- $posicaoV = $linha*$aeti;
- $img = $dado->photo_path;
- if($coluna == 0) { // Se a coluna for 0
- $somaH = $mesq; // Soma Horizontal ç apenas a margem da esquerda inicial
- } else { // Senço
- $somaH = $mesq+$posicaoH+($ehet*$coluna); // Soma Horizontal é a margem inicial mais a posiççoH
- }
- if($linha == 0) { // Se a linha for 0
- $somaV = $msup; // Soma Vertical ç apenas a margem superior inicial
- } else { // Senço
- $somaV = $msup+$posicaoV; // Soma Vertical ç a margem superior inicial mais a posiççoV
- } ?>
Método: onPrintCards (bloco 3)
Nesse trecho quero enfatizar que desejo imprimir as linhas do retângulo do card, portanto façam as alterações que achem necessário.
Com a altura definida retiro o valor da altura da célula de cada linha dessa altura para, ao final, fechar o retângulo
- <?php /****Desenhar os retângulos para o documento*****/
- //$tr->Rect($somaH, $somaV, 63.5, 25.4,'D');//Teste
- $tr->SetFont('arial','BI',6);
- $tr->SetXY($somaH,$somaV+3);
- $tr->MultiCell(63,6,$descProduto,'TRL','L');
- $alturaQuado -= 6;
- $tr->SetFont('arial','',7);
- $tr->SetX($somaH);
- $tr->SetFont('arial','B',6);
- $tr->MultiCell(63,3,general_functions::utf2iso('Referência: '),'RL','L');
- $alturaQuado -= 3;
- $tr->SetFont('arial','',7);
- $tr->SetX($somaH);
- $tr->MultiCell(63,4,$referencia,'RL','L');
- $alturaQuado -= 4; ?>
Observação: general_functions::utf2iso()
- <?php public static function utf2iso($string)
- {
- return iconv('UTF-8', 'ISO-8859-1', $string);
- } ?>
Método: onPrintCards (bloco Final)
Como informado anteriormente, aqui fecho o quadro retiran 1,5mm para que os cards não se encostem
e por fim, insiro a imagem no relatório caso tenha informado true para o parâmetro $withImg
- <?php //Inserir celula em branco pra finalizar quadro
- $tr->SetX($somaH);
- $tr->MultiCell(63,$alturaQuado-1.5,'','RLB','L');
- /****Inserir Imagem no documento*****/
- //verifica se selecionou imprimir chancela ect
- if ($withImg) {
- if ($img != '') {
- $tr->Image($img,30+$somaH,10 + $somaV,28);
- }
- }
- $coluna++;
- }
- if (!file_exists("app/output/printCardsResumo.{$format}") OR is_writable("app/output/printCardsResumo.{$format}"))
- {
- $tr->save("app/output/printCardsResumo.{$format}");
- return "app/output/printCardsResumo.{$format}";
- }
- else
- {
- return 'Falha';
- throw new Exception(_t('Permission denied') . ': ' . "app/output/printCardsResumo.{$format}");
- }
- // shows the success message
- new TMessage('info', 'Relatório Gerado.</br>Caso não abra verifique se o navegador está bloqueando popups e então habilite.');
- } else {
- new TMessage('error', 'Sem registros para os Filtros');
- }
- TTransaction::close();
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- } ?>
Pronto!
Em anexo coloco o arquivo pdf gerado para que tenham ideia do que vai sair desse código.
Muito bom Eliezer ! obrigado por compartilhar, ira me ajudar num projeto. Valeu