Lançado Adianti Framework 7.6!
Clique aqui para saber mais
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 ...
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
  1. <?php require_once('app/lib/pdf/FPDF.php');
  2. class TTableWriterPDFCustom extends FPDF
  3. {
  4.     private $styles;
  5.     private $pdf;
  6.     private $widths;
  7.     private $colcounter;
  8.     private $colHeader;//Título do Relatório
  9.     private $qtdeCol;
  10.     private $titleRepeat;
  11.     private $countTitle;
  12.     private $orientation;//servirá como base de consulta para rodape
  13.     private $unit//servirá como base de consulta para addcell
  14.     private $etiq;
  15.     
  16.     /**
  17.      * Construtor da classe wf_fpdf inicializa a classe
  18.      * @return object
  19.      * @access public
  20.      */
  21.     function TTableWriterPDFCustom($widths,$head,$cols,$titleRepeat=TRUE,$orientation='P'$unit='mm'$format='A4',$isEtiq FALSE)
  22.     {
  23.         //Informa se é para repetir título do relatório em todas as paginas ou só na primeira
  24.         $this->titleRepeat $titleRepeat;
  25.         
  26.         $this->orientation $orientation;
  27.         $this->unit $unit;
  28.         // armazena as larguras
  29.         $this->widths $widths;
  30.         // inicializa atributos
  31.         $this->styles = array();
  32.         $this->colHeader = array();
  33.         $this->colHeader=$head;
  34.         $this->countTitle 0;
  35.         
  36.         $this->setQtdeCol($cols);
  37.         
  38.         $this->etiq $isEtiq;
  39.         
  40.         // create the document styles
  41.          
  42.         $this->addStyle('title''helvetica''9''BI',   '#000000''#EEEEE0');
  43.         $this->addStyle('subtitle''helvetica''9''BI',   '#000000''#EEEEE0');
  44.         $this->addStyle('datap''helvetica''8''',    '#000000''#E8E8E8');
  45.         $this->addStyle('datai''helvetica''8''',    '#000000''#ffffff');
  46.         $this->addStyle('header''helvetica''16''B',  '#000000''#EEEEE0');
  47.         $this->addStyle('footer''helvetica''12''BI''#000000''#EEEEE0');
  48.         $this->addStyle('total''helvetica''9''',   '#000000''#EEEEE0');
  49.         $this->addStyle('subtotal''helvetica''9''',   '#000000''#EEEEE0');
  50.         $this->addStyle('branco''helvetica''16''',   '#000000''#ffffff');
  51.         $this->addStyle('totalCol''helvetica''8''BI',   '#000000''#EEEEE0');
  52.         
  53.         //$this->addStyle('title'            , 'helvetica', '8', 'BI',   '#000000', '#EEEEE0');
  54.         $this->addStyle('titleWhite'        'helvetica''8''BI',   '#000000''#FFFFFF');
  55.         $this->addStyle('titleRed'        'helvetica''8''BI',   'red'     '#ffffff');
  56.         $this->addStyle('titleBlue'        'helvetica''8''BI',   '#1E90FF''#ffffff');
  57.         $this->addStyle('titleYellow'        'helvetica''8''BI',   '#000000''#FFFF00');
  58.         $this->addStyle('titleYellowGreen''helvetica''8''BI',   '#3CB371''#FFFF00');
  59.         $this->addStyle('titleOrange'        'helvetica''8''BI',   '#000000''#FFA500');
  60.         $this->addStyle('titleGreen'        'helvetica''8''BI',   '#000000''#3CB371');
  61.         //$this->addStyle('datap'            , 'helvetica', '8', ''    ,   '#000000', '#E8E8E8');
  62.         //$this->addStyle('datai'            , 'helvetica', '8', ''    ,   '#000000', '#ffffff');
  63.         //$this->addStyle('totalCol'        , 'helvetica', '8', ''    ,   '#000000', '#EEEEE0');
  64.     
  65.         // define o locale
  66.         setlocale(LC_ALL'POSIX');
  67.     
  68.         //$this->headerFunction = "";
  69.         //$this->footerFunction = "";
  70.     
  71.         parent::__construct($orientation$unit$format);
  72.     }
  73.    
  74.         
  75.     public function setQtdeCol($qtde)
  76.     {
  77.         $this->qtdeCol $qtde;
  78.     }
  79.     
  80.     function Footer()
  81.     {
  82.         /** VERIFICA SE É ETIQUETA OU NAO **/
  83.         if ($this->etiq == FALSE) {
  84.              //$this->SetY(-25);
  85.              //Linha
  86.              //$this->SetLineWidth(0.1);
  87.              //$this->Line(10, -30, 10, -35);
  88.              $this->SetY(-19);
  89.              $this->SetFont('Arial','I',7);
  90.              $this->SetTextColor(28134238); // cor da fonte
  91.              
  92.              if ($this->orientation == 'L') {
  93.                  $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');
  94.              } elseif($this->orientation == 'P') {
  95.                  $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');
  96.              }
  97.              
  98.              $this->SetY(-19);
  99.              $this->Cell(2857utf8_decode('Copyright © EMS Tecnologia'),'0','0','L');
  100.          
  101.         }
  102.     }
  103.     
  104.     
  105.     function Header()
  106.     {
  107.         //$this->SetY(10);
  108.         /** VERIFICA SE É ETIQUETA OU NAO **/
  109.         if ($this->etiq == FALSE) {
  110.             /** Adicionamos o Titulo do Relatório    **/
  111.             if ($this->colHeader['titulo']) {
  112.                 //verifica se é para repetir em todas
  113.                 if ($this->titleRepeat) {
  114.                     $this->addRow();//adiciona linha
  115.                     $this->addCell($this->colHeader['titulo'][0], $this->colHeader['titulo'][1], $this->colHeader['titulo'][2], $this->colHeader['titulo'][3]);
  116.                      
  117.                     if (($this->colHeader['coluna'])) {//Verifica se existe colunas enviadas para formar o cabeçalho
  118.                         // create the document styles
  119.                         $totCol intval($this->qtdeCol);
  120.                         $this->addRow();//adiciona linha
  121.                         for ($c 0;$c<=$totCol;$c++)
  122.                         {
  123.                             if (isset($this->colHeader['coluna'][$c][0])) {
  124.                                 if (intval($this->colHeader['coluna'][$c][3]) > 0) {//Verifica se tem colspan
  125.                                     $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2], $this->colHeader['coluna'][$c][3]);
  126.                                 } else {
  127.                                     $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2]);
  128.                                 }
  129.                             }
  130.                          
  131.                         }
  132.                     }
  133.                 } else {
  134.                     if ($this->countTitle ==0) {
  135.                         $this->addRow();//adiciona linha
  136.                         $this->addCell($this->colHeader['titulo'][0], $this->colHeader['titulo'][1], $this->colHeader['titulo'][2], $this->colHeader['titulo'][3]);
  137.                 
  138.                         if (($this->colHeader['coluna'])) {//Verifica se existe colunas enviadas para formar o cabeçalho
  139.                             // create the document styles
  140.                             $totCol intval($this->qtdeCol);
  141.                             $this->addRow();//adiciona linha
  142.                             for ($c 0;$c<=$totCol;$c++)
  143.                             {
  144.                                 if (isset($this->colHeader['coluna'][$c][0])) {
  145.                                     if (intval($this->colHeader['coluna'][$c][3]) > 0) {//Verifica se tem colspan
  146.                                         $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2], $this->colHeader['coluna'][$c][3]);
  147.                                     } else {
  148.                                         $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2]);
  149.                                     }
  150.                                 }
  151.                 
  152.                             }
  153.                         }
  154.                     } else {
  155.                         if (($this->colHeader['coluna'])) {//Verifica se existe colunas enviadas para formar o cabeçalho
  156.                             // create the document styles
  157.                             $totCol intval($this->qtdeCol);
  158.                             $this->addRow();//adiciona linha
  159.                             for ($c 0;$c<=$totCol;$c++)
  160.                             {
  161.                                 if (isset($this->colHeader['coluna'][$c][0])) {
  162.                                     if (intval($this->colHeader['coluna'][$c][3]) > 0) {//Verifica se tem colspan
  163.                                         $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2], $this->colHeader['coluna'][$c][3]);
  164.                                     } else {
  165.                                         $this->addCell($this->colHeader['coluna'][$c][0], $this->colHeader['coluna'][$c][1], $this->colHeader['coluna'][$c][2]);
  166.                                     }
  167.                                 }
  168.                 
  169.                             }
  170.                         }
  171.                     }
  172.                     $this->countTitle +=1;
  173.                 }
  174.             
  175.             }
  176.                                          
  177.             $this->addRow();//adiciona linha
  178.             
  179.         }
  180.         
  181.                 
  182.     }
  183.    
  184.     public function Circle($x$y$r$style='D')
  185.     {
  186.         $this->Ellipse($x,$y,$r,$r,$style);
  187.     }
  188.     
  189.     public function Ellipse($x$y$rx$ry$style='D')
  190.     {
  191.         if($style=='F')
  192.             $op='f';
  193.             elseif($style=='FD' || $style=='DF')
  194.             $op='B';
  195.             else
  196.                 $op='S';
  197.                 $lx=4/3*(M_SQRT2-1)*$rx;
  198.                 $ly=4/3*(M_SQRT2-1)*$ry;
  199.                 $k=$this->k;
  200.                 $h=$this->h;
  201.                 $this->_out(sprintf('%.2F %.2F m %.2F %.2F %.2F %.2F %.2F %.2F c',
  202.                     ($x+$rx)*$k,($h-$y)*$k,
  203.                     ($x+$rx)*$k,($h-($y-$ly))*$k,
  204.                     ($x+$lx)*$k,($h-($y-$ry))*$k,
  205.                     $x*$k,($h-($y-$ry))*$k));
  206.                 $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
  207.                     ($x-$lx)*$k,($h-($y-$ry))*$k,
  208.                     ($x-$rx)*$k,($h-($y-$ly))*$k,
  209.                     ($x-$rx)*$k,($h-$y)*$k));
  210.                 $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
  211.                     ($x-$rx)*$k,($h-($y+$ly))*$k,
  212.                     ($x-$lx)*$k,($h-($y+$ry))*$k,
  213.                     $x*$k,($h-($y+$ry))*$k));
  214.                 $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c %s',
  215.                     ($x+$lx)*$k,($h-($y+$ry))*$k,
  216.                     ($x+$rx)*$k,($h-($y+$ly))*$k,
  217.                     ($x+$rx)*$k,($h-$y)*$k,
  218.                     $op));
  219.     }
  220.     
  221.     /**
  222.      * Adiciona um novo estilo
  223.      * @param @stylename nome do estilo
  224.      * @param @fontface  nome da fonte
  225.      * @param @fontsize  tamanho da fonte
  226.      * @param @fontstyle estilo da fonte (B=bold, I=italic)
  227.      * @param @fontcolor cor da fonte
  228.      * @param @fillcolor cor de preenchimento
  229.      */
  230.     public function addStyle($stylename$fontface$fontsize$fontstyle$fontcolor$fillcolor)
  231.     {
  232.         $this->styles[$stylename] = array($fontface$fontsize$fontstyle$fontcolor$fillcolor);
  233.     }
  234.     
  235.     
  236.     public function addColHeader($type$nomeCol$align$style$colspan)
  237.     {
  238.         $this->colHeader[$type] = array($nomeCol$align$style$colspan);
  239.     }
  240.     
  241.     public function clearColHeader()
  242.     {
  243.         $this->colHeader = array();
  244.     }
  245.     
  246.     /**
  247.      * Aplica um estilo
  248.      * @param $stylename nome do estilo
  249.      */
  250.     public function applyStyle($stylename)
  251.     {
  252.         // verifica se o estilo existe
  253.         if (isset($this->styles[$stylename]))
  254.         {
  255.             $style $this->styles[$stylename];
  256.             // obtém os atributos do estilo
  257.             $fontface    $style[0];
  258.             $fontsize    $style[1];
  259.             $fontstyle   $style[2];
  260.             $fontcolor   $style[3];
  261.             $fillcolor   $style[4];
  262.             
  263.             // aplica os atributos do estilo
  264.             $this->SetFont($fontface$fontstyle); // fonte
  265.             $this->SetFontSize($fontsize); // estilo
  266.             $colorarray self::rgb2int255($fontcolor);
  267.             // cor do texto
  268.             $this->SetTextColor($colorarray[0], $colorarray[1], $colorarray[2]);
  269.             $colorarray self::rgb2int255($fillcolor);
  270.             // cor de preenchimento
  271.             $this->SetFillColor($colorarray[0], $colorarray[1], $colorarray[2]);
  272.         }
  273.     }
  274.     
  275.     /**
  276.      * Converte uma cor em RGB para um vetor de decimais
  277.      * @param $rgb uma string contendo uma cor em RGB
  278.      */
  279.     private function rgb2int255($rgb)
  280.     {
  281.         $red   hexdec(substr($rgb,1,2));
  282.         $green hexdec(substr($rgb,3,2));
  283.         $blue  hexdec(substr($rgb,5,2));
  284.         
  285.         return array($red$green$blue);
  286.     }
  287.     
  288.     /**
  289.      * Adiciona uma nova linha na tabela
  290.      */
  291.     public function addRow()
  292.     {
  293.         $this->Ln(); // quebra de linha
  294.         $this->colcounter 0;
  295.     }
  296.     
  297.     /**
  298.      * Adiciona uma nova célula na linha atual da tabela
  299.      * @param $content   conteúdo da célula
  300.      * @param $align     alinhamento da célula
  301.      * @param $stylename nome do estilo a ser utilizado
  302.      * @param $colspan   quantidade de células a serem mescladas
  303.      * @param $cellplus valor que altera a altura da célula 
  304.      * @param $fundo valor que define se o fundo da célula será desenhado ou não desenhado (true), transparente (false)
  305.      */
  306.     function addCell($content$align$stylename$colspan 1$border 1,$cellplus 0.5,$fundo true)
  307.     {
  308.         if (is_null($stylename) OR !isset($this->styles[$stylename]) )
  309.         {
  310.             throw new Exception(TAdiantiCoreTranslator::translate('Style ^1 not found in ^2'$stylename__METHOD__ ) );
  311.         }
  312.         
  313.         if ($fundo == true) {
  314.             $this->applyStyle($stylename); // aplica o estilo
  315.         }
  316.         
  317.         $fontsize $this->styles[$stylename][1]; // obtém a fonte
  318.         
  319.         if (utf8_encode(utf8_decode($content)) == $content // SE UTF8
  320.         {
  321.             $content utf8_decode($content);
  322.         }
  323.         
  324.         $width 0;
  325.         // calcula a largura da célula (incluindo as mescladas)
  326.         for ($n=$this->colcounter$n<$this->colcounter+$colspan$n++)
  327.         {
  328.             $width += $this->widths[$n];            
  329.         }
  330.         // exibe a célula com o conteúdo passado
  331.         
  332.         
  333.         $this->Cell$width$fontsize $cellplus$content$border0strtoupper(substr($align,0,1)), true);
  334.         
  335.         //Atualiza o valor de n quando o colspan é maior que 1
  336.         if ($colspan 1) {
  337.             $this->colcounter += $colspan;
  338.         } else {
  339.             $this->colcounter ++;
  340.         }
  341.         
  342.     }
  343.     
  344.     /**
  345.      * Adiciona uma nova célula na linha atual da tabela
  346.      * @param $content   conteúdo da célula
  347.      * @param $align     alinhamento da célula
  348.      * @param $stylename nome do estilo a ser utilizado
  349.      * @param $colspan   quantidade de células a serem mescladas
  350.      * @param $cellplus valor que altera a altura da célula
  351.      */
  352.     function addMultiCell($content$align$stylename$colspan 1$border 1,$cellplus 0.5)
  353.     {
  354.         if (is_null($stylename) OR !isset($this->styles[$stylename]) )
  355.         {
  356.             throw new Exception(TAdiantiCoreTranslator::translate('Style ^1 not found in ^2'$stylename__METHOD__ ) );
  357.         }
  358.     
  359.         $this->applyStyle($stylename); // aplica o estilo
  360.         $fontsize $this->styles[$stylename][1]; // obtém a fonte
  361.     
  362.         if (utf8_encode(utf8_decode($content)) == $content // SE UTF8
  363.         {
  364.             $content utf8_decode($content);
  365.         }
  366.     
  367.         $width 0;
  368.         // calcula a largura da célula (incluindo as mescladas)
  369.         for ($n=$this->colcounter$n<$this->colcounter+$colspan$n++)
  370.         {
  371.         $width += $this->widths[$n];
  372.         }
  373.         // exibe a célula com o conteúdo passado
  374.     
  375.     
  376.         $this->MultiCell$width$fontsize $cellplus$content$border0strtoupper(substr($align,0,1)), true);
  377.     
  378.         //Atualiza o valor de n quando o colspan é maior que 1
  379.         if ($colspan 1) {
  380.         $this->colcounter += $colspan;
  381.     } else {
  382.     $this->colcounter ++;
  383.     }
  384.     
  385.     }
  386.     
  387.     /**
  388.      * DashedLine
  389.      * Desenha uma linha horizontal tracejada com o FPDF
  390.      * @package NFePHP
  391.      * @name DashedHLine
  392.      * @version 1.0.1
  393.      * @author Roberto L. Machado <linux.rlm at gmail dot com>
  394.      * @param number $x Posição horizontal inicial, em mm
  395.      * @param number $y Posição vertical inicial, em mm
  396.      * @param number $w Comprimento da linha, em mm
  397.      * @param number $h Espessura da linha, em mm
  398.      * @param number $n Numero de traços na seção da linha com o comprimento $w
  399.      * @return none
  400.      */
  401.     public function DashedHLine($x,$y,$w,$h,$n) {
  402.         $this->SetDrawColor(110);
  403.         $this->SetLineWidth($h);
  404.         $wDash=($w/$n)/2// comprimento dos traços
  405.         for( $i=$x$i<=$x+$w$i += $wDash+$wDash ) {
  406.             for( $j=$i$j<= ($i+$wDash); $j++ ) {
  407.                 if( $j <= ($x+$w-1) ) {
  408.                     $this->Line($j,$y,$j+1,$y);
  409.                 }
  410.             }
  411.         }
  412.         $this->SetDrawColor(0);
  413.     } //fim função DashedHLine
  414.     
  415.     /**
  416.      * DashedVLine
  417.      * Desenha uma linha vertical tracejada com o FPDF
  418.      * @package NFePHP
  419.      * @name DashedVLine
  420.      * @version 1.0
  421.      * @author Roberto L. Machado <linux.rlm at gmail dot com>
  422.      * @author Guilherme Calabria Filho <guiga86 at gmail dot com>
  423.      * @param number $x Posição horizontal inicial, em mm
  424.      * @param number $y Posição vertical inicial, em mm
  425.      * @param number $w Comprimento da linha, em mm
  426.      * @param number $yfinal Espessura da linha, em mm
  427.      * @param number $n Numero de traços na seção da linha com o comprimento $w
  428.      * @return none
  429.      */
  430.     public function DashedVLine($x,$y,$w,$yfinal,$n) {
  431.         $this->SetLineWidth($w);
  432.         //Organizando valores
  433.         if($y>$yfinal) {
  434.             $aux $yfinal;
  435.             $yfinal $y;
  436.             $y $aux;
  437.         }
  438.         while($y<$yfinal&&$n>0){
  439.             $this->Line($x,$y,$x,$y+1);
  440.             $y += 3;
  441.             $n--;
  442.         }
  443.     } //fim função DashedVLine
  444.     
  445.     public function SetDash($black=null$white=null)
  446.     {
  447.         if($black!==null)
  448.             $s=sprintf('[%.3F %.3F] 0 d',$black*$this->k,$white*$this->k);
  449.         else
  450.             $s='[] 0 d';
  451.         $this->_out($s);
  452.     }
  453.     
  454.     /*
  455.      * align: allows to center or align the text. Possible values are:
  456.         U: top
  457.         C: center (default value)
  458.         D: bottom
  459.      */
  460.     public function VCell($w$h=0$txt=''$border=0$ln=0$align=''$fill=false)
  461.     {
  462.         //Output a cell
  463.         $k=$this->k;
  464.         if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak())
  465.         {
  466.             //Automatic page break
  467.             $x=$this->x;
  468.             $ws=$this->ws;
  469.             if($ws>0)
  470.             {
  471.                 $this->ws=0;
  472.                 $this->_out('0 Tw');
  473.             }
  474.             $this->AddPage($this->CurOrientation,$this->CurPageSize);
  475.             $this->x=$x;
  476.             if($ws>0)
  477.             {
  478.                 $this->ws=$ws;
  479.                 $this->_out(sprintf('%.3F Tw',$ws*$k));
  480.             }
  481.         }
  482.         if($w==0)
  483.             $w=$this->w-$this->rMargin-$this->x;
  484.         $s='';
  485.         // begin change Cell function
  486.         if($fill || $border>0)
  487.         {
  488.             if($fill)
  489.                 $op=($border>0) ? 'B' 'f';
  490.             else
  491.                 $op='S';
  492.             if ($border>1) {
  493.                 $s=sprintf('q %.2F w %.2F %.2F %.2F %.2F re %s Q ',$border,
  494.                         $this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
  495.             }
  496.             else
  497.                 $s=sprintf('%.2F %.2F %.2F %.2F re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
  498.         }
  499.         if(is_string($border))
  500.         {
  501.             $x=$this->x;
  502.             $y=$this->y;
  503.             if(is_int(strpos($border,'L')))
  504.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
  505.             else if(is_int(strpos($border,'l')))
  506.                 $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);
  507.     
  508.             if(is_int(strpos($border,'T')))
  509.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
  510.             else if(is_int(strpos($border,'t')))
  511.                 $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);
  512.     
  513.             if(is_int(strpos($border,'R')))
  514.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
  515.             else if(is_int(strpos($border,'r')))
  516.                 $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);
  517.     
  518.             if(is_int(strpos($border,'B')))
  519.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
  520.             else if(is_int(strpos($border,'b')))
  521.                 $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);
  522.         }
  523.         if(trim($txt)!='')
  524.         {
  525.             $cr=substr_count($txt,"\n");
  526.             if ($cr>0) { // Multi line
  527.                 $txts explode("\n"$txt);
  528.                 $lines count($txts);
  529.                 for($l=0;$l<$lines;$l++) {
  530.                     $txt=$txts[$l];
  531.                     $w_txt=$this->GetStringWidth($txt);
  532.                     if ($align=='U')
  533.                         $dy=$this->cMargin+$w_txt;
  534.                     elseif($align=='D')
  535.                     $dy=$h-$this->cMargin;
  536.                     else
  537.                         $dy=($h+$w_txt)/2;
  538.                     $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
  539.                     if($this->ColorFlag)
  540.                         $s.='q '.$this->TextColor.' ';
  541.                     $s.=sprintf('BT 0 1 -1 0 %.2F %.2F Tm (%s) Tj ET ',
  542.                             ($this->x+.5*$w+(.7+$l-$lines/2)*$this->FontSize)*$k,
  543.                             ($this->h-($this->y+$dy))*$k,$txt);
  544.                     if($this->ColorFlag)
  545.                         $s.=' Q ';
  546.                 }
  547.             }
  548.             else { // Single line
  549.                 $w_txt=$this->GetStringWidth($txt);
  550.                 $Tz=100;
  551.                 if ($w_txt>$h-2*$this->cMargin) {
  552.                     $Tz=($h-2*$this->cMargin)/$w_txt*100;
  553.                     $w_txt=$h-2*$this->cMargin;
  554.                 }
  555.                 if ($align=='U')
  556.                     $dy=$this->cMargin+$w_txt;
  557.                 elseif($align=='D')
  558.                 $dy=$h-$this->cMargin;
  559.                 else
  560.                     $dy=($h+$w_txt)/2;
  561.                 $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
  562.                 if($this->ColorFlag)
  563.                     $s.='q '.$this->TextColor.' ';
  564.                 $s.=sprintf('q BT 0 1 -1 0 %.2F %.2F Tm %.2F Tz (%s) Tj ET Q ',
  565.                         ($this->x+.5*$w+.3*$this->FontSize)*$k,
  566.                         ($this->h-($this->y+$dy))*$k,$Tz,$txt);
  567.                 if($this->ColorFlag)
  568.                     $s.=' Q ';
  569.             }
  570.         }
  571.         // end change Cell function
  572.         if($s)
  573.             $this->_out($s);
  574.         $this->lasth=$h;
  575.         if($ln>0)
  576.         {
  577.             //Go to next line
  578.             $this->y+=$h;
  579.             if($ln==1)
  580.                 $this->x=$this->lMargin;
  581.         }
  582.         else
  583.             $this->x+=$w;
  584.     }
  585.     
  586.     
  587.     /*
  588.      * border: indicates if borders must be drawn around the cell. The value can be either a number:
  589.         0: no border
  590.         >0: frame of the corresponding width
  591.         or a string containing some or all of the following characters (in any order):
  592.         L: left
  593.         T: top
  594.         R: right
  595.         B: bottom
  596.         or for bold border:
  597.         l: left
  598.         t: top
  599.         r: right
  600.         b: bottom
  601.         Default value: 0.
  602.      */
  603.     public function Cell($w$h=0$txt=''$border=0$ln=0$align=''$fill=false$link='')
  604.     {
  605.         //Output a cell
  606.         $k=$this->k;
  607.         if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak())
  608.         {
  609.             //Automatic page break
  610.             $x=$this->x;
  611.             $ws=$this->ws;
  612.             if($ws>0)
  613.             {
  614.                 $this->ws=0;
  615.                 $this->_out('0 Tw');
  616.             }
  617.             $this->AddPage($this->CurOrientation,$this->CurPageSize);
  618.             $this->x=$x;
  619.             if($ws>0)
  620.             {
  621.                 $this->ws=$ws;
  622.                 $this->_out(sprintf('%.3F Tw',$ws*$k));
  623.             }
  624.         }
  625.         if($w==0)
  626.             $w=$this->w-$this->rMargin-$this->x;
  627.         $s='';
  628.         // begin change Cell function
  629.         if($fill || $border>0)
  630.         {
  631.             if($fill)
  632.                 $op=($border>0) ? 'B' 'f';
  633.             else
  634.                 $op='S';
  635.             if ($border>1) {
  636.                 $s=sprintf('q %.2F w %.2F %.2F %.2F %.2F re %s Q ',$border,
  637.                         $this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
  638.             }
  639.             else
  640.                 $s=sprintf('%.2F %.2F %.2F %.2F re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
  641.         }
  642.         if(is_string($border))
  643.         {
  644.             $x=$this->x;
  645.             $y=$this->y;
  646.             if(is_int(strpos($border,'L')))
  647.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
  648.             else if(is_int(strpos($border,'l')))
  649.                 $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);
  650.     
  651.             if(is_int(strpos($border,'T')))
  652.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
  653.             else if(is_int(strpos($border,'t')))
  654.                 $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);
  655.     
  656.             if(is_int(strpos($border,'R')))
  657.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
  658.             else if(is_int(strpos($border,'r')))
  659.                 $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);
  660.     
  661.             if(is_int(strpos($border,'B')))
  662.                 $s.=sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
  663.             else if(is_int(strpos($border,'b')))
  664.                 $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);
  665.         }
  666.         if (trim($txt)!='') {
  667.             $cr=substr_count($txt,"\n");
  668.             if ($cr>0) { // Multi line
  669.                 $txts explode("\n"$txt);
  670.                 $lines count($txts);
  671.                 for($l=0;$l<$lines;$l++) {
  672.                     $txt=$txts[$l];
  673.                     $w_txt=$this->GetStringWidth($txt);
  674.                     if($align=='R')
  675.                         $dx=$w-$w_txt-$this->cMargin;
  676.                     elseif($align=='C')
  677.                     $dx=($w-$w_txt)/2;
  678.                     else
  679.                         $dx=$this->cMargin;
  680.     
  681.                     $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
  682.                     if($this->ColorFlag)
  683.                         $s.='q '.$this->TextColor.' ';
  684.                     $s.=sprintf('BT %.2F %.2F Td (%s) Tj ET ',
  685.                             ($this->x+$dx)*$k,
  686.                             ($this->h-($this->y+.5*$h+(.7+$l-$lines/2)*$this->FontSize))*$k,
  687.                             $txt);
  688.                     if($this->underline)
  689.                         $s.=' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt);
  690.                     if($this->ColorFlag)
  691.                         $s.=' Q ';
  692.                     if($link)
  693.                         $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$w_txt,$this->FontSize,$link);
  694.                 }
  695.             }
  696.             else { // Single line
  697.                 $w_txt=$this->GetStringWidth($txt);
  698.                 $Tz=100;
  699.                 if ($w_txt>$w-2*$this->cMargin) { // Need compression
  700.                     $Tz=($w-2*$this->cMargin)/$w_txt*100;
  701.                     $w_txt=$w-2*$this->cMargin;
  702.                 }
  703.                 if($align=='R')
  704.                     $dx=$w-$w_txt-$this->cMargin;
  705.                 elseif($align=='C')
  706.                 $dx=($w-$w_txt)/2;
  707.                 else
  708.                     $dx=$this->cMargin;
  709.                 $txt=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt)));
  710.                 if($this->ColorFlag)
  711.                     $s.='q '.$this->TextColor.' ';
  712.                 $s.=sprintf('q BT %.2F %.2F Td %.2F Tz (%s) Tj ET Q ',
  713.                         ($this->x+$dx)*$k,
  714.                         ($this->h-($this->y+.5*$h+.3*$this->FontSize))*$k,
  715.                         $Tz,$txt);
  716.                 if($this->underline)
  717.                     $s.=' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt);
  718.                 if($this->ColorFlag)
  719.                     $s.=' Q ';
  720.                 if($link)
  721.                     $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$w_txt,$this->FontSize,$link);
  722.             }
  723.         }
  724.         // end change Cell function
  725.         if($s)
  726.             $this->_out($s);
  727.         $this->lasth=$h;
  728.         if($ln>0)
  729.         {
  730.             //Go to next line
  731.             $this->y+=$h;
  732.             if($ln==1)
  733.                 $this->x=$this->lMargin;
  734.         }
  735.         else
  736.             $this->x+=$w;
  737.     }
  738.     
  739.     /**
  740.      * Armazena o conteúdo do documento em um arquivo
  741.      * @param $filename caminho para o arquivo de saída
  742.      */
  743.     public function save($filename)
  744.     {
  745.         $this->Output($filename);
  746.         return TRUE;
  747.     }
  748. ?>


Método: onPrintCards (bloco 1)
Nesse bloco defino os parâmetros do relatório
  1. <?php  /**
  2.      * Método onPrintCardsPrecos
  3.      * 
  4.      * @param $dados object Objeto com dados para impressão
  5.      * @param $mesq string Margem esquerda
  6.      * @param $mdir string Margem direita
  7.      * @param $msup string Margem Superior
  8.      * @param $leti string Largura Etiqueta
  9.      * @param $aeti string Altura Etiqueta
  10.      * @param $ehet string Espaço horizontal entre etiquetas
  11.      * @param $nCol string Número de Colunas
  12.      * @param $nLinhas Número de Linhas
  13.      * @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
  14.      * */
  15.     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)
  16.     {
  17.         try
  18.         {            
  19.             
  20.             //$objects = $repository->load($criteria);
  21.             $format  'pdf';
  22.             
  23.             $totCol 1;
  24.             $orientation 'P';
  25.             $unit 'mm';
  26.             $paper 'A4';
  27.              if ($dados)
  28.             {
  29.                 $widths = array($leti);
  30.                 
  31.                 /** CABEÇALHO - deve ser definido antes de estanciar a classe TTableWriterPDFCustom para ser enviado como parâmetro **/
  32.                 
  33.                 $titCol = array();
  34.                 $titCol['titulo'] = array('''center''header'$totCol);//Título do Relatório
  35.                 //Colunas
  36.                 $titCol['coluna'][0] = array( '''center''title',0);
  37.                 
  38.                 $tr = new TTableWriterPDFCustom($widths,$titCol$totCol,FALSE,$orientation,$unit,$paper,TRUE);
  39.                 
  40.                 // define o locale
  41.                 setlocale(LC_ALL'POSIX');
  42.                 
  43.                 $tr->AddPage(); // adiciona uma página
  44.                 //$tr->AliasNbPages('{nb}');
  45.                 $tr->SetAutoPageBreak(TRUE,3);
  46.                 
  47.                 
  48.                 // define cores e fontes para os títulos da tabela
  49.                 $tr->SetFillColor(130,80,70); // cor de fundo
  50.                 $tr->SetTextColor(0,0,0); // cor da fonte
  51.                 $tr->SetFont('arial','',10); // fonte
  52.                 
  53.                 
  54.                 // set margins
  55.                 $tr->SetMargins($mesq$msup,$mdir);
  56.                 // controls the background filling
  57.                 $coluna 0;
  58.                 $linha 0;
  59.                 $alturaQuado0?>


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
  1. <?php foreach ($dados as $dado)
  2.                 {
  3.                     $alturaQuado $aeti;
  4.                     
  5.                     
  6.                     if($coluna == $nCol) { // Se for a última coluna
  7.                         // $columnDefault = true; // $coluna volta para o valor inicial
  8.                         $coluna 0;
  9.                         $linha++; // $linha volta ao seu valor inicial
  10.                         
  11.                     }
  12.                     if($linha == $nLinhas) { // Se for a última linha da página
  13.                         // $addPage = true;
  14.                         $tr->AddPage(); // Adiciona uma nova página
  15.                         $linha 0// $linha volta ao seu valor inicial
  16.                     
  17.                   
  18.                     $posicaoH $coluna*$leti;                     
  19.                     
  20.                     $posicaoV $linha*$aeti;                     
  21.                     $img $dado->photo_path;
  22.                     
  23.                    
  24.                     if($coluna == 0) { // Se a coluna for 0
  25.                         $somaH $mesq// Soma Horizontal ç apenas a margem da esquerda inicial
  26.                     } else { // Senço
  27.                         $somaH $mesq+$posicaoH+($ehet*$coluna); // Soma Horizontal é a margem inicial mais a posiççoH
  28.                     }
  29.                     
  30.                     if($linha == 0) { // Se a linha for 0
  31.                         $somaV $msup// Soma Vertical ç apenas a margem superior inicial
  32.                     } else { // Senço
  33.                         $somaV $msup+$posicaoV// Soma Vertical ç a margem superior inicial mais a posiççoV
  34.                     ?>


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
  1. <?php /****Desenhar os retângulos para o documento*****/
  2.                     //$tr->Rect($somaH, $somaV, 63.5, 25.4,'D');//Teste
  3.                     $tr->SetFont('arial','BI',6);
  4.                     $tr->SetXY($somaH,$somaV+3);
  5.                     $tr->MultiCell(63,6,$descProduto,'TRL','L');
  6.                     $alturaQuado -= 6;
  7.                     $tr->SetFont('arial','',7);
  8.                                         
  9.                     $tr->SetX($somaH);
  10.                     $tr->SetFont('arial','B',6);
  11.                     $tr->MultiCell(63,3,general_functions::utf2iso('Referência: '),'RL','L');
  12.                     $alturaQuado -= 3;
  13.                     $tr->SetFont('arial','',7);
  14.                     $tr->SetX($somaH);
  15.                     $tr->MultiCell(63,4,$referencia,'RL','L');
  16.                     $alturaQuado -= 4?>


Observação: general_functions::utf2iso()
  1. <?php public static function utf2iso($string)
  2.    {
  3.            return iconv('UTF-8''ISO-8859-1'$string);
  4.         
  5.    } ?>


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
  1. <?php //Inserir celula em branco pra finalizar quadro
  2.                     $tr->SetX($somaH);
  3.                     $tr->MultiCell(63,$alturaQuado-1.5,'','RLB','L');
  4.                     
  5.                     /****Inserir Imagem no documento*****/
  6.                     //verifica se selecionou imprimir chancela ect
  7.                     if ($withImg) {
  8.                         if ($img != '') {
  9.                             $tr->Image($img,30+$somaH,10 $somaV,28);
  10.                         }
  11.                         
  12.                     }
  13.                     
  14.                     
  15.                     $coluna++;
  16.                     
  17.                 }
  18.                 
  19.                 if (!file_exists("app/output/printCardsResumo.{$format}") OR is_writable("app/output/printCardsResumo.{$format}"))
  20.                 {
  21.                     $tr->save("app/output/printCardsResumo.{$format}");
  22.                     
  23.                     return "app/output/printCardsResumo.{$format}";
  24.                 }
  25.                 else
  26.                 {
  27.                     return 'Falha';
  28.                     throw new Exception(_t('Permission denied') . ': ' "app/output/printCardsResumo.{$format}");
  29.                     
  30.                 }
  31.                 
  32.                 
  33.                 // shows the success message
  34.                 new TMessage('info''Relatório Gerado.</br>Caso não abra verifique se o navegador está bloqueando popups e então habilite.');
  35.             } else {
  36.                 new TMessage('error''Sem registros para os Filtros');
  37.             }
  38.             
  39.             TTransaction::close();
  40.             
  41.         }
  42.         catch (Exception $e// in case of exception
  43.         {
  44.             // shows the exception error message
  45.             new TMessage('error''<b>Error</b> ' $e->getMessage());
  46.             
  47.             // undo all pending operations
  48.             TTransaction::rollback();
  49.         }
  50.     } ?>


Pronto!
Em anexo coloco o arquivo pdf gerado para que tenham ideia do que vai sair desse código.

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (1)


S

Muito bom Eliezer ! obrigado por compartilhar, ira me ajudar num projeto. Valeu