Completed
Push — master ( 0b1d68...e7164a )
by Roberto
12:40 queued 09:51
created

src/NFe/Danfe.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace NFePHP\DA\NFe;
4
5
use InvalidArgumentException;
6
use NFePHP\DA\Legacy\Dom;
7
use NFePHP\DA\Legacy\Pdf;
8
use NFePHP\DA\Legacy\Common;
9
10
class Danfe extends Common
11
{
12
13
    /**
14
     * alinhamento padrão do logo (C-Center)
15
     *
16
     * @var string
17
     */
18
    protected $logoAlign = 'C';
19
    /**
20
     * Posição
21
     * @var float
22
     */
23
    protected $yDados = 0;
24
    /**
25
     * Numero DPEC
26
     *
27
     * @var string
28
     */
29
    protected $numero_registro_dpec = '';
30
     /**
31
     * Parâmetro para exibir ou ocultar os valores do PIS/COFINS.
32
     * @var boolean
33
     */
34
    protected $exibirPIS = true;
35
    /**
36
     * Parâmetro para exibir ou ocultar os valores do ICMS Interestadual e Valor Total dos Impostos.
37
     * @var boolean
38
     */
39
    protected $exibirIcmsInterestadual = true;
40
    /**
41
     * Parâmetro para exibir ou ocultar o texto sobre valor aproximado dos tributos.
42
     * @var boolean
43
     */
44
    protected $exibirValorTributos = true;
45
    /**
46
     * Parâmetro para exibir ou ocultar o texto adicional sobre a forma de pagamento
47
     * e as informações de fatura/duplicata.
48
     * @var boolean
49
     */
50
    protected $exibirTextoFatura = false;
51
    /**
52
     * Parâmetro do controle se deve concatenar automaticamente informações complementares
53
     * na descrição do produto, como por exemplo, informações sobre impostos.
54
     * @var boolean
55
     */
56
    protected $descProdInfoComplemento = true;
57
    /**
58
     * Parâmetro do controle se deve gerar quebras de linha com "\n" a partir de ";" na descrição do produto.
59
     * @var boolean
60
     */
61
    protected $descProdQuebraLinha = true;
62
    /**
63
     * objeto fpdf()
64
     * @var object
65
     */
66
    protected $pdf;
67
    /**
68
     * XML NFe
69
     * @var string
70
     */
71
    protected $xml;
72
    /**
73
     * path para logomarca em jpg
74
     * @var string
75
     */
76
    protected $logomarca = '';
77
    /**
78
     * mesagens de erro
79
     * @var string
80
     */
81
    protected $errMsg = '';
82
    /**
83
     * status de erro true um erro ocorreu false sem erros
84
     * @var boolean
85
     */
86
    protected $errStatus = false;
87
    /**
88
     * orientação da DANFE
89
     * P-Retrato ou L-Paisagem
90
     * @var string
91
     */
92
    protected $orientacao = 'P';
93
    /**
94
     * formato do papel
95
     * @var string
96
     */
97
    protected $papel = 'A4';
98
    /**
99
     * Nome da Fonte para gerar o DANFE
100
     * @var string
101
     */
102
    protected $fontePadrao = 'Times';
103
    /**
104
     * Texto
105
     * @var string
106
     */
107
    protected $textoAdic = '';
108
    /**
109
     * Largura
110
     * @var float
111
     */
112
    protected $wAdic = 0;
113
    /**
114
     * largura imprimivel, em milímetros
115
     * @var float
116
     */
117
    protected $wPrint;
118
    /**
119
     * Comprimento (altura) imprimivel, em milímetros
120
     * @var float
121
     */
122
    protected $hPrint;
123
    protected $maxH;
124
    protected $maxW;
125
    /**
126
     * largura do canhoto (25mm) apenas para a formatação paisagem
127
     * @var float
128
     */
129
    protected $wCanhoto = 25;
130
    /**
131
     * Formato chave
132
     * @var string
133
     */
134
    protected $formatoChave = "#### #### #### #### #### #### #### #### #### #### ####";
135
    /**
136
     * quantidade de itens já processados na montagem do DANFE
137
     * @var integer
138
     */
139
    protected $qtdeItensProc;
140
    /**
141
     * Document
142
     * @var DOMDocument
143
     */
144
    protected $dom;
145
    /**
146
     * Node
147
     * @var DOMNode
148
     */
149
    protected $infNFe;
150
    /**
151
     * Node
152
     * @var DOMNode
153
     */
154
    protected $ide;
155
    /**
156
     * Node
157
     * @var DOMNode
158
     */
159
    protected $entrega;
160
    /**
161
     * Node
162
     * @var DOMNode
163
     */
164
    protected $retirada;
165
    /**
166
     * Node
167
     * @var DOMNode
168
     */
169
    protected $emit;
170
    /**
171
     * Node
172
     * @var DOMNode
173
     */
174
    protected $dest;
175
    /**
176
     * Node
177
     * @var DOMNode
178
     */
179
    protected $enderEmit;
180
    /**
181
     * Node
182
     * @var DOMNode
183
     */
184
    protected $enderDest;
185
    /**
186
     * Node
187
     * @var DOMNode
188
     */
189
    protected $det;
190
    /**
191
     * Node
192
     * @var DOMNode
193
     */
194
    protected $cobr;
195
    /**
196
     * Node
197
     * @var DOMNode
198
     */
199
    protected $dup;
200
    /**
201
     * Node
202
     * @var DOMNode
203
     */
204
    protected $ICMSTot;
205
    /**
206
     * Node
207
     * @var DOMNode
208
     */
209
    protected $ISSQNtot;
210
    /**
211
     * Node
212
     * @var DOMNode
213
     */
214
    protected $transp;
215
    /**
216
     * Node
217
     * @var DOMNode
218
     */
219
    protected $transporta;
220
    /**
221
     * Node
222
     * @var DOMNode
223
     */
224
    protected $veicTransp;
225
    /**
226
     * Node reboque
227
     * @var DOMNode
228
     */
229
    protected $reboque;
230
    /**
231
     * Node infAdic
232
     * @var DOMNode
233
     */
234
    protected $infAdic;
235
    /**
236
     * Tipo de emissão
237
     * @var integer
238
     */
239
    protected $tpEmis;
240
    /**
241
     * Node infProt
242
     * @var DOMNode
243
     */
244
    protected $infProt;
245
    /**
246
     * 1-Retrato/ 2-Paisagem
247
     * @var integer
248
     */
249
    protected $tpImp;
250
    /**
251
     * Node compra
252
     * @var DOMNode
253
     */
254
    protected $compra;
255
    /**
256
     * ativa ou desativa o modo de debug
257
     * @var integer
258
     */
259
    protected $debugmode = false;
260
    /**
261
     * Creditos para integrador
262
     * @var string
263
     */
264
    protected $creditos = '';
265
266
    /**
267
     * __construct
268
     *
269
     * @name  __construct
270
     * @param string  $docXML      Conteúdo XML da NF-e (com ou sem a tag nfeProc)
271
     * @param string  $logoimage   Caminho para o arquivo do logo
272
     */
273
    public function __construct(
274
        $xml
275
    ) {
276
        $this->debugMode();
277
        $this->loadDoc($xml);
278
    }
279
    
280
    /**
281
     * Ativa ou desativa o modo debug
282
     * @param bool $activate
283
     * @return bool
284
     */
285
    public function debugMode($activate = null)
286
    {
287
        if (isset($activate) && is_bool($activate)) {
288
            $this->debugmode = $activate;
289
        }
290
        if ($this->debugmode) {
291
            //ativar modo debug
292
            error_reporting(E_ALL);
293
            ini_set('display_errors', 'On');
294
        } else {
295
            //desativar modo debug
296
            error_reporting(0);
297
            ini_set('display_errors', 'Off');
298
        }
299
        return $this->debugmode;
300
    }
301
302
    /**
303
     * Add the credits to the integrator in the footer message
304
     * @param string $message
305
     */
306
    public function creditsIntegratorFooter($message = '')
307
    {
308
        $this->creditos = trim($message);
309
    }
310
    
311
    /**
312
     * Dados brutos do PDF
313
     * @return string
314
     */
315
    public function render()
316
    {
317
        if (empty($this->pdf)) {
318
            $this->monta();
319
        }
320
        return $this->pdf->getPdf();
321
    }
322
323
    /**
324
     * monta
325
     * Monta a DANFE conforme as informações fornecidas para a classe durante sua
326
     * construção. Constroi DANFEs com até 3 páginas podendo conter até 56 itens.
327
     * A definição de margens e posições iniciais para a impressão são estabelecidas
328
     * pelo conteúdo da funçao e podem ser modificados.
329
     *
330
     * @param  string $orientacao (Opcional) Estabelece a orientação da impressão
331
     *  (ex. P-retrato), se nada for fornecido será usado o padrão da NFe
332
     * @param  string $papel      (Opcional) Estabelece o tamanho do papel (ex. A4)
333
     * @return string O ID da NFe numero de 44 digitos extraido do arquivo XML
334
     */
335
    public function monta(
336
        $logo = '',
337
        $orientacao = '',
338
        $papel = 'A4',
339
        $logoAlign = 'C',
340
        $depecNumReg = '',
341
        $margSup = 2,
342
        $margEsq = 2,
343
        $margInf = 2
344
    ) {
345
        $this->pdf = '';
346
        $this->logomarca = $logo;
347
        //se a orientação estiver em branco utilizar o padrão estabelecido na NF
348
        if ($orientacao == '') {
349
            if ($this->tpImp == '1') {
350
                $orientacao = 'P';
351
            } else {
352
                $orientacao = 'L';
353
            }
354
        }
355
        $this->orientacao = $orientacao;
356
        $this->papel = $papel;
357
        $this->logoAlign = $logoAlign;
358
        $this->numero_registro_dpec = $depecNumReg;
359
        //instancia a classe pdf
360
        $this->pdf = new Pdf($this->orientacao, 'mm', $this->papel);
361
        //margens do PDF, em milímetros. Obs.: a margem direita é sempre igual à
362
        //margem esquerda. A margem inferior *não* existe na FPDF, é definida aqui
363
        //apenas para controle se necessário ser maior do que a margem superior
364
        // posição inicial do conteúdo, a partir do canto superior esquerdo da página
365
        $xInic = $margEsq;
366
        $yInic = $margSup;
367
        if ($this->orientacao == 'P') {
368
            if ($papel == 'A4') {
369
                $this->maxW = 210;
370
                $this->maxH = 297;
371
            }
372
        } else {
373
            if ($papel == 'A4') {
374
                $this->maxH = 210;
375
                $this->maxW = 297;
376
                //se paisagem multiplica a largura do canhoto pela quantidade de canhotos
377
                $this->wCanhoto *= $this->qCanhoto;
378
            }
379
        }
380
        //total inicial de paginas
381
        $totPag = 1;
382
        //largura imprimivel em mm: largura da folha menos as margens esq/direita
383
        $this->wPrint = $this->maxW-($margEsq * 2);
384
        //comprimento (altura) imprimivel em mm: altura da folha menos as margens
385
        //superior e inferior
386
        $this->hPrint = $this->maxH-$margSup-$margInf;
387
        // estabelece contagem de paginas
388
        $this->pdf->aliasNbPages();
389
        // fixa as margens
390
        $this->pdf->setMargins($margEsq, $margSup);
391
        $this->pdf->setDrawColor(0, 0, 0);
392
        $this->pdf->setFillColor(255, 255, 255);
393
        // inicia o documento
394
        $this->pdf->open();
395
        // adiciona a primeira página
396
        $this->pdf->addPage($this->orientacao, $this->papel);
397
        $this->pdf->setLineWidth(0.1);
398
        $this->pdf->setTextColor(0, 0, 0);
399
400
        //##################################################################
401
        // CALCULO DO NUMERO DE PAGINAS A SEREM IMPRESSAS
402
        //##################################################################
403
        //Verificando quantas linhas serão usadas para impressão das duplicatas
404
        $linhasDup = 0;
405
        if (($this->dup->length > 0) && ($this->dup->length <= 7)) {
406
            $linhasDup = 1;
407
        } elseif (($this->dup->length > 7) && ($this->dup->length <= 14)) {
408
            $linhasDup = 2;
409
        } elseif (($this->dup->length > 14) && ($this->dup->length <= 21)) {
410
            $linhasDup = 3;
411
        } elseif ($this->dup->length > 21) {
412
            // chinnonsantos 11/05/2016: Limite máximo de impressão de duplicatas na NFe,
413
            // só vai ser exibito as 21 primeiras duplicatas (parcelas de pagamento),
414
            // se não oculpa espaço d+, cada linha comporta até 7 duplicatas.
415
            $linhasDup = 3;
416
        }
417
        //verifica se será impressa a linha dos serviços ISSQN
418
        $linhaISSQN = 0;
419
        if ((isset($this->ISSQNtot)) && ($this->getTagValue($this->ISSQNtot, 'vServ') > 0)) {
420
            $linhaISSQN = 1;
421
        }
422
        //calcular a altura necessária para os dados adicionais
423
        if ($this->orientacao == 'P') {
424
            $this->wAdic = round($this->wPrint*0.66, 0);
425
        } else {
426
            $this->wAdic = round(($this->wPrint-$this->wCanhoto)*0.5, 0);
427
        }
428
        $fontProduto = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
429
        $this->textoAdic = '';
430
        if (isset($this->retirada)) {
431
            $txRetCNPJ = $this->getTagValue($this->retirada, "CNPJ");
432
            $txRetxLgr = $this->getTagValue($this->retirada, "xLgr");
433
            $txRetnro = $this->getTagValue($this->retirada, "nro");
434
            $txRetxCpl = $this->getTagValue($this->retirada, "xCpl", " - ");
435
            $txRetxBairro = $this->getTagValue($this->retirada, "xBairro");
436
            $txRetxMun = $this->getTagValue($this->retirada, "xMun");
437
            $txRetUF = $this->getTagValue($this->retirada, "UF");
438
            $this->textoAdic .= "LOCAL DE RETIRADA : ".
439
                    $txRetCNPJ.
440
                    '-' .
441
                    $txRetxLgr .
442
                    ', ' .
443
                    $txRetnro .
444
                    ' ' .
445
                    $txRetxCpl .
446
                    ' - ' .
447
                    $txRetxBairro .
448
                    ' ' .
449
                    $txRetxMun .
450
                    ' - ' .
451
                    $txRetUF .
452
                    "\r\n";
453
        }
454
        //dados do local de entrega da mercadoria
455
        if (isset($this->entrega)) {
456
            $txRetCNPJ = $this->getTagValue($this->entrega, "CNPJ");
457
            $txRetxLgr = $this->getTagValue($this->entrega, "xLgr");
458
            $txRetnro = $this->getTagValue($this->entrega, "nro");
459
            $txRetxCpl = $this->getTagValue($this->entrega, "xCpl", " - ");
460
            $txRetxBairro = $this->getTagValue($this->entrega, "xBairro");
461
            $txRetxMun = $this->getTagValue($this->entrega, "xMun");
462
            $txRetUF = $this->getTagValue($this->entrega, "UF");
463
            if ($this->textoAdic != '') {
464
                $this->textoAdic .= ". \r\n";
465
            }
466
            $this->textoAdic .= "LOCAL DE ENTREGA : ".$txRetCNPJ.'-'.$txRetxLgr.', '.$txRetnro.' '.$txRetxCpl.
467
               ' - '.$txRetxBairro.' '.$txRetxMun.' - '.$txRetUF."\r\n";
468
        }
469
        //informações adicionais
470
        $this->textoAdic .= $this->geraInformacoesDasNotasReferenciadas();
471
        if (isset($this->infAdic)) {
472
            $i = 0;
473
            if ($this->textoAdic != '') {
474
                $this->textoAdic .= ". \r\n";
475
            }
476
            $this->textoAdic .= ! empty($this->getTagValue($this->infAdic, "infCpl")) ?
477
                'Inf. Contribuinte: ' .
478
                $this->anfaveaDANFE($this->getTagValue($this->infAdic, "infCpl")) : '';
479
            $infPedido = $this->geraInformacoesDaTagCompra();
480
            if ($infPedido != "") {
481
                $this->textoAdic .= $infPedido;
482
            }
483
            $this->textoAdic .= $this->getTagValue($this->dest, "email", ' Email do Destinatário: ');
484
            $this->textoAdic .= ! empty($this->getTagValue($this->infAdic, "infAdFisco")) ?
485
                "\r\n Inf. fisco: " .
486
                $this->getTagValue($this->infAdic, "infAdFisco") : '';
487
            $obsCont = $this->infAdic->getElementsByTagName("obsCont");
488
            if (isset($obsCont)) {
489
                foreach ($obsCont as $obs) {
490
                    $campo =  $obsCont->item($i)->getAttribute("xCampo");
491
                    $xTexto = ! empty($obsCont->item($i)->getElementsByTagName("xTexto")->item(0)->nodeValue) ?
492
                        $obsCont->item($i)->getElementsByTagName("xTexto")->item(0)->nodeValue : '';
493
                    $this->textoAdic .= "\r\n" . $campo . ':  ' . trim($xTexto);
494
                    $i++;
495
                }
496
            }
497
        }
498
        //INCLUSO pela NT 2013.003 Lei da Transparência
499
        //verificar se a informação sobre o valor aproximado dos tributos
500
        //já se encontra no campo de informações adicionais
501
        if ($this->exibirValorTributos) {
502
            $flagVTT = strpos(strtolower(trim($this->textoAdic)), 'valor');
503
            $flagVTT = $flagVTT || strpos(strtolower(trim($this->textoAdic)), 'vl');
504
            $flagVTT = $flagVTT && strpos(strtolower(trim($this->textoAdic)), 'aprox');
505
            $flagVTT = $flagVTT && (strpos(strtolower(trim($this->textoAdic)), 'trib') ||
506
                    strpos(strtolower(trim($this->textoAdic)), 'imp'));
507
            $vTotTrib = $this->getTagValue($this->ICMSTot, 'vTotTrib');
508
            if ($vTotTrib != '' && !$flagVTT) {
509
                $this->textoAdic .= "\n Valor Aproximado dos Tributos : R$ " . number_format($vTotTrib, 2, ",", ".");
510
            }
511
        }
512
        //fim da alteração NT 2013.003 Lei da Transparência
513
        $this->textoAdic = str_replace(";", "\n", $this->textoAdic);
514
        $alinhas = explode("\n", $this->textoAdic);
515
        $numlinhasdados = 0;
516
        foreach ($alinhas as $linha) {
517
            $numlinhasdados += $this->pdf->getNumLines($linha, $this->wAdic, $fontProduto);
518
        }
519
        $hdadosadic = round(($numlinhasdados+3) * $this->pdf->fontSize, 0);
520
        if ($hdadosadic < 10) {
521
            $hdadosadic = 10;
522
        }
523
        //altura disponivel para os campos da DANFE
524
        $hcabecalho = 47;//para cabeçalho
525
        $hdestinatario = 25;//para destinatario
526
        $hduplicatas = 12;//para cada grupo de 7 duplicatas
527
        $himposto = 18;// para imposto
528
        $htransporte = 25;// para transporte
529
        $hissqn = 11;// para issqn
530
        $hfooter = 5;// para rodape
531
        $hCabecItens = 4;//cabeçalho dos itens
532
        //alturas disponiveis para os dados
533
        $hDispo1 = $this->hPrint - 10 - ($hcabecalho +
534
            $hdestinatario + ($linhasDup * $hduplicatas) + $himposto + $htransporte +
535
            ($linhaISSQN * $hissqn) + $hdadosadic + $hfooter + $hCabecItens +
536
            $this->sizeExtraTextoFatura());
537
        if ($this->orientacao == 'P') {
538
            $hDispo1 -= 24 * $this->qCanhoto;//para canhoto
539
            $w = $this->wPrint;
540
        } else {
541
            $hcanhoto = $this->hPrint;//para canhoto
542
            $w = $this->wPrint - $this->wCanhoto;
543
        }
544
        $hDispo2 = $this->hPrint - 10 - ($hcabecalho + $hfooter + $hCabecItens)-4;
545
        //Contagem da altura ocupada para impressão dos itens
546
        $fontProduto = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
547
        $numlinhas = 0;
548
        $hUsado = $hCabecItens;
549
        $w2 = round($w*0.28, 0);
550
        $hDispo = $hDispo1;
551
        $totPag = 1;
552
        $i = 0;
553
        while ($i < $this->det->length) {
554
            $texto = $this->descricaoProduto($this->det->item($i));
555
            $numlinhas = $this->pdf->getNumLines($texto, $w2, $fontProduto);
556
            $hUsado += round(($numlinhas * $this->pdf->fontSize) + ($numlinhas * 0.5), 2);
557
            if ($hUsado > $hDispo) {
558
                $totPag++;
559
                $hDispo = $hDispo2;
560
                $hUsado = $hCabecItens;
561
                // Remove canhoto para páginas secundárias em modo paisagem ('L')
562
                $w2 = round($this->wPrint*0.28, 0);
563
                $i--; // decrementa para readicionar o item que não coube nessa pagina na outra.
564
            }
565
            $i++;
566
        } //fim da soma das areas de itens usadas
567
        $qtdeItens = $i; //controle da quantidade de itens no DANFE
568
        //montagem da primeira página
569
        $pag = 1;
570
        $x = $xInic;
571
        $y = $yInic;
572
        //coloca o(s) canhoto(s) da NFe
573
        if ($this->orientacao == 'P') {
574
            for ($i = 1; $i <= $this->qCanhoto; $i++) {
575
                $y = $this->canhoto($x, $y);
576
            }
577
        } else {
578
            for ($i = 1; $i <= $this->qCanhoto; $i++) {
579
                $this->canhoto($x, $y);
580
                $x = 25 * $i;
581
            }
582
        }
583
        //coloca o cabeçalho
584
        $y = $this->header($x, $y, $pag, $totPag);
585
        //coloca os dados do destinatário
586
        $y = $this->destinatarioDANFE($x, $y+1);
587
        
588
        
589
        //Verifica as formas de pagamento da nota fiscal
590
        $formaPag = [];
591
        if (isset($this->detPag) && $this->detPag->length > 0) {
592
            foreach ($this->detPag as $k => $d) {
593
                $fPag = !empty($this->detPag->item($k)->getElementsByTagName('tPag')->item(0)->nodeValue) ?
0 ignored issues
show
The property detPag does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
594
                    $this->detPag->item($k)->getElementsByTagName('tPag')->item(0)->nodeValue : '0';
595
                $formaPag[$fPag] = $fPag;
596
            }
597
        }
598
        //caso tenha boleto imprimir fatura
599
        if ($this->dup->length > 0) {
600
            $y = $this->fatura($x, $y+1);
601
        } else {
602
            //Se somente tiver a forma de pagamento sem pagamento ou outros não imprimir nada
603
            if (count($formaPag)=='1' && (isset($formaPag[90]) || isset($formaPag[99]))) {
604
                $y = $y;
605
            } else {
606
                //caso tenha mais de uma forma de pagamento ou seja diferente de boleto exibe a
607
                //forma de pagamento e o valor
608
                $y = $this->pagamento($x, $y+1);
609
            }
610
        }
611
        //coloca os dados dos impostos e totais da NFe
612
        $y = $this->imposto($x, $y+1);
613
        //coloca os dados do trasnporte
614
        $y = $this->transporte($x, $y+1);
615
        //itens da DANFE
616
        $nInicial = 0;
617
618
        $y = $this->itens($x, $y+1, $nInicial, $hDispo1, $pag, $totPag, $hCabecItens);
619
620
        //coloca os dados do ISSQN
621
        if ($linhaISSQN == 1) {
622
            $y = $this->issqn($x, $y+4);
623
        } else {
624
            $y += 4;
625
        }
626
        //coloca os dados adicionais da NFe
627
        $y = $this->dadosAdicionais($x, $y, $hdadosadic);
628
        //coloca o rodapé da página
629
        if ($this->orientacao == 'P') {
630
            $this->rodape($xInic);
631
        } else {
632
            $this->rodape($xInic);
633
        }
634
635
        //loop para páginas seguintes
636
        for ($n = 2; $n <= $totPag; $n++) {
637
            // fixa as margens
638
            $this->pdf->setMargins($margEsq, $margSup);
639
            //adiciona nova página
640
            $this->pdf->addPage($this->orientacao, $this->papel);
641
            //ajusta espessura das linhas
642
            $this->pdf->setLineWidth(0.1);
643
            //seta a cor do texto para petro
644
            $this->pdf->setTextColor(0, 0, 0);
645
            // posição inicial do relatorio
646
            $x = $xInic;
647
            $y = $yInic;
648
            //coloca o cabeçalho na página adicional
649
            $y = $this->header($x, $y, $n, $totPag);
650
            //coloca os itens na página adicional
651
            $y = $this->itens($x, $y+1, $nInicial, $hDispo2, $n, $totPag, $hCabecItens);
652
            //coloca o rodapé da página
653
            if ($this->orientacao == 'P') {
654
                $this->rodape($xInic);
655
            } else {
656
                $this->rodape($xInic);
657
            }
658
            //se estiver na última página e ainda restar itens para inserir, adiciona mais uma página
659
            if ($n == $totPag && $this->qtdeItensProc < $qtdeItens) {
660
                $totPag++;
661
            }
662
        }
663
    }
664
665
    /**
666
     * anfavea
667
     * Função para transformar o campo cdata do padrão ANFAVEA para
668
     * texto imprimível
669
     *
670
     * @param  string $cdata campo CDATA
671
     * @return string conteúdo do campo CDATA como string
672
     */
673
    protected function anfaveaDANFE($cdata = '')
674
    {
675
        if ($cdata == '') {
676
            return '';
677
        }
678
        //remove qualquer texto antes ou depois da tag CDATA
679
        $cdata = str_replace('<![CDATA[', '<CDATA>', $cdata);
680
        $cdata = str_replace(']]>', '</CDATA>', $cdata);
681
        $cdata = preg_replace('/\s\s+/', ' ', $cdata);
682
        $cdata = str_replace("> <", "><", $cdata);
683
        $len = strlen($cdata);
684
        $startPos = strpos($cdata, '<');
685
        if ($startPos === false) {
686
            return $cdata;
687
        }
688
        for ($x=$len; $x>0; $x--) {
689
            if (substr($cdata, $x, 1) == '>') {
690
                $endPos = $x;
691
                break;
692
            }
693
        }
694
        if ($startPos > 0) {
695
            $parte1 = substr($cdata, 0, $startPos);
696
        } else {
697
            $parte1 = '';
698
        }
699
        $parte2 = substr($cdata, $startPos, $endPos-$startPos+1);
700
        if ($endPos < $len) {
701
            $parte3 = substr($cdata, $endPos + 1, $len - $endPos - 1);
702
        } else {
703
            $parte3 = '';
704
        }
705
        $texto = trim($parte1).' '.trim($parte3);
706
        if (strpos($parte2, '<CDATA>') === false) {
707
            $cdata = '<CDATA>'.$parte2.'</CDATA>';
708
        } else {
709
            $cdata = $parte2;
710
        }
711
        //Retira a tag <FONTE IBPT> (caso existir) pois não é uma estrutura válida XML
712
        $cdata = str_replace('<FONTE IBPT>', '', $cdata);
713
        //carrega o xml CDATA em um objeto DOM
714
        $dom = new Dom();
715
        $dom->loadXML($cdata, LIBXML_NOBLANKS | LIBXML_NOEMPTYTAG);
716
        //$xml = $dom->saveXML();
717
        //grupo CDATA infADprod
718
        $id = $dom->getElementsByTagName('id')->item(0);
719
        $div = $dom->getElementsByTagName('div')->item(0);
720
        $entg = $dom->getElementsByTagName('entg')->item(0);
721
        $dest = $dom->getElementsByTagName('dest')->item(0);
722
        $ctl = $dom->getElementsByTagName('ctl')->item(0);
723
        $ref = $dom->getElementsByTagName('ref')->item(0);
724
        if (isset($id)) {
725
            if ($id->hasAttributes()) {
726
                foreach ($id->attributes as $attr) {
727
                    $name = $attr->nodeName;
728
                    $value = $attr->nodeValue;
729
                    $texto .= " $name : $value";
730
                }
731
            }
732
        }
733
        if (isset($div)) {
734
            if ($div->hasAttributes()) {
735
                foreach ($div->attributes as $attr) {
736
                    $name = $attr->nodeName;
737
                    $value = $attr->nodeValue;
738
                    $texto .= " $name : $value";
739
                }
740
            }
741
        }
742
        if (isset($entg)) {
743
            if ($entg->hasAttributes()) {
744
                foreach ($entg->attributes as $attr) {
745
                    $name = $attr->nodeName;
746
                    $value = $attr->nodeValue;
747
                    $texto .= " $name : $value";
748
                }
749
            }
750
        }
751
        if (isset($dest)) {
752
            if ($dest->hasAttributes()) {
753
                foreach ($dest->attributes as $attr) {
754
                    $name = $attr->nodeName;
755
                    $value = $attr->nodeValue;
756
                    $texto .= " $name : $value";
757
                }
758
            }
759
        }
760
        if (isset($ctl)) {
761
            if ($ctl->hasAttributes()) {
762
                foreach ($ctl->attributes as $attr) {
763
                    $name = $attr->nodeName;
764
                    $value = $attr->nodeValue;
765
                    $texto .= " $name : $value";
766
                }
767
            }
768
        }
769
        if (isset($ref)) {
770
            if ($ref->hasAttributes()) {
771
                foreach ($ref->attributes as $attr) {
772
                    $name = $attr->nodeName;
773
                    $value = $attr->nodeValue;
774
                    $texto .= " $name : $value";
775
                }
776
            }
777
        }
778
        //grupo CADATA infCpl
779
        $t = $dom->getElementsByTagName('transmissor')->item(0);
780
        $r = $dom->getElementsByTagName('receptor')->item(0);
781
        $versao = ! empty($dom->getElementsByTagName('versao')->item(0)->nodeValue) ?
782
            'Versao:'.$dom->getElementsByTagName('versao')->item(0)->nodeValue.' ' : '';
783
        $especieNF = ! empty($dom->getElementsByTagName('especieNF')->item(0)->nodeValue) ?
784
            'Especie:'.$dom->getElementsByTagName('especieNF')->item(0)->nodeValue.' ' : '';
785
        $fabEntrega = ! empty($dom->getElementsByTagName('fabEntrega')->item(0)->nodeValue) ?
786
            'Entrega:'.$dom->getElementsByTagName('fabEntrega')->item(0)->nodeValue.' ' : '';
787
        $dca = ! empty($dom->getElementsByTagName('dca')->item(0)->nodeValue) ?
788
            'dca:'.$dom->getElementsByTagName('dca')->item(0)->nodeValue.' ' : '';
789
        $texto .= "".$versao.$especieNF.$fabEntrega.$dca;
790
        if (isset($t)) {
791
            if ($t->hasAttributes()) {
792
                $texto .= " Transmissor ";
793
                foreach ($t->attributes as $attr) {
794
                    $name = $attr->nodeName;
795
                    $value = $attr->nodeValue;
796
                    $texto .= " $name : $value";
797
                }
798
            }
799
        }
800
        if (isset($r)) {
801
            if ($r->hasAttributes()) {
802
                $texto .= " Receptor ";
803
                foreach ($r->attributes as $attr) {
804
                    $name = $attr->nodeName;
805
                    $value = $attr->nodeValue;
806
                    $texto .= " $name : $value";
807
                }
808
            }
809
        }
810
        return $texto;
811
    }
812
813
814
    /**
815
     * Verifica o status da NFe
816
     *
817
     * @return array
818
     */
819
    protected function statusNFe()
820
    {
821
        if (!isset($this->nfeProc)) {
822
            return ['status' => false, 'message' => 'NFe NÃO PROTOCOLADA'];
823
        }
824
        if ($this->getTagValue($this->ide, "tpAmb") == '2') {
825
            return ['status' => false, 'message' => 'NFe EMITIDA EM HOMOLOGAÇÃO'];
826
        }
827
        $cStat = $this->getTagValue($this->nfeProc, "cStat");
828
        if ($cStat == '101'
829
            || $cStat == '151'
830
            || $cStat == '135'
831
            || $cStat == '155'
832
        ) {
833
            return ['status' => false, 'message' => 'NFe CANCELADA'];
834
        }
835
        
836
        if ($cStat == '110' ||
837
               $cStat == '301' ||
838
               $cStat == '302'
839
               
840
        ) {
841
            return ['status' => false, 'message' => 'NFe DENEGADA'];
842
        }
843
        return ['status' => true, 'message' => ''];
844
    }
845
846
    protected function notaDPEC()
847
    {
848
        return $this->numero_registro_dpec != '';
849
    }
850
851
852
853
    /**
854
     *header
855
     * Monta o cabelhalho da DANFE (retrato e paisagem)
856
     *
857
     * @param  number $x      Posição horizontal inicial, canto esquerdo
858
     * @param  number $y      Posição vertical inicial, canto superior
859
     * @param  number $pag    Número da Página
860
     * @param  number $totPag Total de páginas
861
     * @return number Posição vertical final
862
     */
863
    protected function header($x = 0, $y = 0, $pag = '1', $totPag = '1')
864
    {
865
        $oldX = $x;
866
        $oldY = $y;
867
        if ($this->orientacao == 'P') {
868
              $maxW = $this->wPrint;
869
        } else {
870
            if ($pag == 1) { // primeira página
871
                $maxW = $this->wPrint - $this->wCanhoto;
872
            } else { // páginas seguintes
873
                $maxW = $this->wPrint;
874
            }
875
        }
876
        //####################################################################################
877
        //coluna esquerda identificação do emitente
878
        $w = round($maxW*0.41, 0);
879
        if ($this->orientacao == 'P') {
880
            $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>'I'];
881
        } else {
882
            $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>'B'];
883
        }
884
        $w1 = $w;
885
        $h=32;
886
        $oldY += $h;
887
        $this->pdf->textBox($x, $y, $w, $h);
888
        $texto = 'IDENTIFICAÇÃO DO EMITENTE';
889
        $this->pdf->textBox($x, $y, $w, 5, $texto, $aFont, 'T', 'C', 0, '');
890
        //estabelecer o alinhamento
891
        //pode ser left L, center C, right R, full logo L
892
        //se for left separar 1/3 da largura para o tamanho da imagem
893
        //os outros 2/3 serão usados para os dados do emitente
894
        //se for center separar 1/2 da altura para o logo e 1/2 para os dados
895
        //se for right separa 2/3 para os dados e o terço seguinte para o logo
896
        //se não houver logo centraliza dos dados do emitente
897
        // coloca o logo
898
        if (!empty($this->logomarca)) {
899
            $logoInfo = getimagesize($this->logomarca);
900
            $type = strtolower(explode('/', $logoInfo['mime'])[1]);
901
            if ($type == 'png') {
902
                $this->logomarca = $this->imagePNGtoJPG($this->logomarca);
903
                $type == 'jpg';
904
            }
905
            //largura da imagem em mm
906
            $logoWmm = ($logoInfo[0]/72)*25.4;
907
            //altura da imagem em mm
908
            $logoHmm = ($logoInfo[1]/72)*25.4;
909
            if ($this->logoAlign=='L') {
910
                $nImgW = round($w/3, 0);
911
                $nImgH = round($logoHmm * ($nImgW/$logoWmm), 0);
912
                $xImg = $x+1;
913
                $yImg = round(($h-$nImgH)/2, 0)+$y;
914
                //estabelecer posições do texto
915
                $x1 = round($xImg + $nImgW +1, 0);
916
                $y1 = round($h/3+$y, 0);
917
                $tw = round(2*$w/3, 0);
918
            } elseif ($this->logoAlign=='C') {
919
                $nImgH = round($h/3, 0);
920
                $nImgW = round($logoWmm * ($nImgH/$logoHmm), 0);
921
                $xImg = round(($w-$nImgW)/2+$x, 0);
922
                $yImg = $y+3;
923
                $x1 = $x;
924
                $y1 = round($yImg + $nImgH + 1, 0);
925
                $tw = $w;
926
            } elseif ($this->logoAlign=='R') {
927
                $nImgW = round($w/3, 0);
928
                $nImgH = round($logoHmm * ($nImgW/$logoWmm), 0);
929
                $xImg = round($x+($w-(1+$nImgW)), 0);
930
                $yImg = round(($h-$nImgH)/2, 0)+$y;
931
                $x1 = $x;
932
                $y1 = round($h/3+$y, 0);
933
                $tw = round(2*$w/3, 0);
934
            } elseif ($this->logoAlign=='F') {
935
                $nImgH = round($h-5, 0);
936
                $nImgW = round($logoWmm * ($nImgH/$logoHmm), 0);
937
                $xImg = round(($w-$nImgW)/2+$x, 0);
938
                $yImg = $y+3;
939
                $x1 = $x;
940
                $y1 = round($yImg + $nImgH + 1, 0);
941
                $tw = $w;
942
            }
943
            $type = (substr($this->logomarca, 0, 7) === 'data://') ? 'jpg' : null;
944
            $this->pdf->Image($this->logomarca, $xImg, $yImg, $nImgW, $nImgH, $type);
945
        } else {
946
            $x1 = $x;
947
            $y1 = round($h/3+$y, 0);
948
            $tw = $w;
949
        }
950
        // monta as informações apenas se diferente de full logo
951
        if ($this->logoAlign !== 'F') {
952
            //Nome emitente
953
            $aFont = ['font'=>$this->fontePadrao, 'size'=>12, 'style'=>'B'];
954
            $texto = $this->emit->getElementsByTagName("xNome")->item(0)->nodeValue;
955
            $this->pdf->textBox($x1, $y1, $tw, 8, $texto, $aFont, 'T', 'C', 0, '');
956
            //endereço
957
            $y1 = $y1+5;
958
            $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>''];
959
            $fone = ! empty($this->enderEmit->getElementsByTagName("fone")->item(0)->nodeValue)
960
                 ? $this->enderEmit->getElementsByTagName("fone")->item(0)->nodeValue
961
                 : '';
962
            $lgr = $this->getTagValue($this->enderEmit, "xLgr");
963
            $nro = $this->getTagValue($this->enderEmit, "nro");
964
            $cpl = $this->getTagValue($this->enderEmit, "xCpl", " - ");
965
            $bairro = $this->getTagValue($this->enderEmit, "xBairro");
966
            $CEP = $this->getTagValue($this->enderEmit, "CEP");
967
            $CEP = $this->formatField($CEP, "#####-###");
968
            $mun = $this->getTagValue($this->enderEmit, "xMun");
969
            $UF = $this->getTagValue($this->enderEmit, "UF");
970
            $texto = $lgr . ", " . $nro . $cpl . "\n" . $bairro . " - "
971
                    . $CEP . "\n" . $mun . " - " . $UF . " "
972
                    . "Fone/Fax: " . $fone;
973
            $this->pdf->textBox($x1, $y1, $tw, 8, $texto, $aFont, 'T', 'C', 0, '');
974
        }
975
976
        //####################################################################################
977
        //coluna central Danfe
978
        $x += $w;
979
        $w=round($maxW * 0.17, 0);//35;
980
        $w2 = $w;
981
        $h = 32;
982
        $this->pdf->textBox($x, $y, $w, $h);
983
  
984
        $texto = "DANFE";
985
        $aFont = ['font'=>$this->fontePadrao, 'size'=>14, 'style'=>'B'];
986
        $this->pdf->textBox($x, $y+1, $w, $h, $texto, $aFont, 'T', 'C', 0, '');
987
        $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>''];
988
        $texto = 'Documento Auxiliar da Nota Fiscal Eletrônica';
989
        $h = 20;
990
        $this->pdf->textBox($x, $y+6, $w, $h, $texto, $aFont, 'T', 'C', 0, '', false);
991
        
992
993
        $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>''];
994
        $texto = '0 - ENTRADA';
995
        $y1 = $y + 14;
996
        $h = 8;
997
        $this->pdf->textBox($x+2, $y1, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
998
        $texto = '1 - SAÍDA';
999
        $y1 = $y + 17;
1000
        $this->pdf->textBox($x+2, $y1, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
1001
        //tipo de nF
1002
        $aFont = ['font'=>$this->fontePadrao, 'size'=>12, 'style'=>'B'];
1003
        $y1 = $y + 13;
1004
        $h = 7;
1005
        $texto = $this->ide->getElementsByTagName('tpNF')->item(0)->nodeValue;
1006
        $this->pdf->textBox($x+27, $y1, 5, $h, $texto, $aFont, 'C', 'C', 1, '');
1007
        //numero da NF
1008
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1009
        $y1 = $y + 20;
1010
        $numNF = str_pad($this->ide->getElementsByTagName('nNF')->item(0)->nodeValue, 9, "0", STR_PAD_LEFT);
1011
        $numNF = $this->formatField($numNF, "###.###.###");
1012
        $texto = "Nº. " . $numNF;
1013
        $this->pdf->textBox($x, $y1, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1014
        //Série
1015
        $y1 = $y + 23;
1016
        $serie = str_pad($this->ide->getElementsByTagName('serie')->item(0)->nodeValue, 3, "0", STR_PAD_LEFT);
1017
        $texto = "Série " . $serie;
1018
        $this->pdf->textBox($x, $y1, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1019
        //numero paginas
1020
        $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>'I'];
1021
        $y1 = $y + 26;
1022
        $texto = "Folha " . $pag . "/" . $totPag;
1023
        $this->pdf->textBox($x, $y1, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1024
1025
        //####################################################################################
1026
        //coluna codigo de barras
1027
        $x += $w;
1028
        $w = ($maxW-$w1-$w2);//85;
1029
        $w3 = $w;
1030
        $h = 32;
1031
        $this->pdf->textBox($x, $y, $w, $h);
1032
        $this->pdf->setFillColor(0, 0, 0);
1033
        $chave_acesso = str_replace('NFe', '', $this->infNFe->getAttribute("Id"));
1034
        $bW = 75;
1035
        $bH = 12;
1036
        //codigo de barras
1037
        $this->pdf->code128($x+(($w-$bW)/2), $y+2, $chave_acesso, $bW, $bH);
1038
        //linhas divisorias
1039
        $this->pdf->line($x, $y+4+$bH, $x+$w, $y+4+$bH);
1040
        $this->pdf->line($x, $y+12+$bH, $x+$w, $y+12+$bH);
1041
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1042
        $y1 = $y+4+$bH;
1043
        $h = 7;
1044
        $texto = 'CHAVE DE ACESSO';
1045
        $this->pdf->textBox($x, $y1, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
1046
        $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>'B'];
1047
        $y1 = $y+8+$bH;
1048
        $texto = $this->formatField($chave_acesso, $this->formatoChave);
1049
        $this->pdf->textBox($x+2, $y1, $w-2, $h, $texto, $aFont, 'T', 'C', 0, '');
1050
        $y1 = $y+12+$bH;
1051
        $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>''];
1052
        $chaveContingencia="";
1053
        if ($this->notaDpec()) {
1054
            $cabecalhoProtoAutorizacao = 'NÚMERO DE REGISTRO DPEC';
1055
        } else {
1056
            $cabecalhoProtoAutorizacao = 'PROTOCOLO DE AUTORIZAÇÃO DE USO';
1057
        }
1058
        if (($this->tpEmis == 2 || $this->tpEmis == 5) && !$this->notaDpec()) {
1059
            $cabecalhoProtoAutorizacao = "DADOS DA NF-E";
1060
            $chaveContingencia = $this->geraChaveAdicionalDeContingencia();
1061
            $this->pdf->setFillColor(0, 0, 0);
1062
            //codigo de barras
1063
            $this->pdf->code128($x+11, $y1+1, $chaveContingencia, $bW*.9, $bH/2);
1064
        } else {
1065
            $texto = 'Consulta de autenticidade no portal nacional da NF-e';
1066
            $this->pdf->textBox($x+2, $y1, $w-2, $h, $texto, $aFont, 'T', 'C', 0, '');
1067
            $y1 = $y+16+$bH;
1068
            $texto = 'www.nfe.fazenda.gov.br/portal ou no site da Sefaz Autorizadora';
1069
            $this->pdf->textBox(
1070
                $x+2,
1071
                $y1,
1072
                $w-2,
1073
                $h,
1074
                $texto,
1075
                $aFont,
1076
                'T',
1077
                'C',
1078
                0,
1079
                'http://www.nfe.fazenda.gov.br/portal ou no site da Sefaz Autorizadora'
1080
            );
1081
        }
1082
1083
        //####################################################################################
1084
        //Dados da NF do cabeçalho
1085
        //natureza da operação
1086
        $texto = 'NATUREZA DA OPERAÇÃO';
1087
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1088
        $w = $w1+$w2;
1089
        $y = $oldY;
1090
        $oldY += $h;
1091
        $x = $oldX;
1092
        $h = 7;
1093
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1094
        $texto = $this->ide->getElementsByTagName("natOp")->item(0)->nodeValue;
1095
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1096
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1097
        $x += $w;
1098
        $w = $w3;
1099
        //PROTOCOLO DE AUTORIZAÇÃO DE USO ou DADOS da NF-E
1100
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1101
        $this->pdf->textBox($x, $y, $w, $h, $cabecalhoProtoAutorizacao, $aFont, 'T', 'L', 1, '');
1102
        // algumas NFe podem estar sem o protocolo de uso portanto sua existencia deve ser
1103
        // testada antes de tentar obter a informação.
1104
        // NOTA : DANFE sem protocolo deve existir somente no caso de contingência !!!
1105
        // Além disso, existem várias NFes em contingência que eu recebo com protocolo de autorização.
1106
        // Na minha opinião, deveríamos mostra-lo, mas o  manual  da NFe v4.01 diz outra coisa...
1107
        if (($this->tpEmis == 2 || $this->tpEmis == 5) && !$this->notaDpec()) {
1108
            $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>'B'];
1109
            $texto = $this->formatField($chaveContingencia, "#### #### #### #### #### #### #### #### ####");
1110
            $cStat = '';
1111
        } else {
1112
            $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1113
            if ($this->notaDpec()) {
1114
                $texto = $this->numero_registro_dpec;
1115
                $cStat = '';
1116
            } else {
1117
                if (isset($this->nfeProc)) {
1118
                    $texto = ! empty($this->nfeProc->getElementsByTagName("nProt")->item(0)->nodeValue) ?
1119
                            $this->nfeProc->getElementsByTagName("nProt")->item(0)->nodeValue : '';
1120
                    $tsHora = $this->convertTime($this->nfeProc->getElementsByTagName("dhRecbto")->item(0)->nodeValue);
1121
                    if ($texto != '') {
1122
                        $texto .= "  -  " . date('d/m/Y H:i:s', $tsHora);
1123
                    }
1124
                    $cStat = $this->nfeProc->getElementsByTagName("cStat")->item(0)->nodeValue;
1125
                } else {
1126
                    $texto = '';
1127
                    $cStat = '';
1128
                }
1129
            }
1130
        }
1131
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1132
        //####################################################################################
1133
        //INSCRIÇÃO ESTADUAL
1134
        $w = round($maxW * 0.333, 0);
1135
        $y += $h;
1136
        $oldY += $h;
1137
        $x = $oldX;
1138
        $texto = 'INSCRIÇÃO ESTADUAL';
1139
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1140
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1141
        $texto = $this->getTagValue($this->emit, "IE");
1142
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1143
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1144
        //INSCRIÇÃO ESTADUAL DO SUBST. TRIBUT.
1145
        $x += $w;
1146
        $texto = 'INSCRIÇÃO ESTADUAL DO SUBST. TRIBUT.';
1147
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1148
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1149
        $texto = ! empty($this->emit->getElementsByTagName("IEST")->item(0)->nodeValue)
1150
             ? $this->emit->getElementsByTagName("IEST")->item(0)->nodeValue
1151
             : '';
1152
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1153
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1154
        //CNPJ
1155
        $x += $w;
1156
        $w = ($maxW-(2*$w));
1157
        $texto = 'CNPJ / CPF';
1158
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1159
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1160
        //Pegando valor do CPF/CNPJ
1161
        if (! empty($this->emit->getElementsByTagName("CNPJ")->item(0)->nodeValue)) {
1162
            $texto = $this->formatField(
1163
                $this->emit->getElementsByTagName("CNPJ")->item(0)->nodeValue,
1164
                "###.###.###/####-##"
1165
            );
1166
        } else {
1167
            $texto = ! empty($this->emit->getElementsByTagName("CPF")->item(0)->nodeValue) ?
1168
                $this->formatField(
1169
                    $this->emit->getElementsByTagName("CPF")->item(0)->nodeValue,
1170
                    "###.###.###-##"
1171
                ) : '';
1172
        }
1173
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1174
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1175
1176
        //####################################################################################
1177
        //Indicação de NF Homologação, cancelamento e falta de protocolo
1178
        $tpAmb = $this->ide->getElementsByTagName('tpAmb')->item(0)->nodeValue;
1179
        //indicar cancelamento
1180
        $resp = $this->statusNFe();
1181
        if (!$resp['status']) {
1182
            $x = 10;
1183
            $y = $this->hPrint-130;
1184
            $h = 25;
1185
            $w = $maxW-(2*$x);
1186
            $this->pdf->setTextColor(90, 90, 90);
1187
            $texto = $resp['message'];
1188
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1189
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1190
            $y += $h;
1191
            $h = 5;
1192
            $w = $maxW-(2*$x);
1193
            if (isset($this->infProt) && $resp['status']) {
1194
                $xMotivo = $this->infProt->getElementsByTagName("xMotivo")->item(0)->nodeValue;
1195
            } else {
1196
                $xMotivo = '';
1197
            }
1198
            $texto = "SEM VALOR FISCAL\n".$xMotivo;
1199
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1200
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1201
            $this->pdf->setTextColor(0, 0, 0);
1202
        }
1203
        
1204
        /*
1205
        if ($this->pNotaCancelada()) {
1206
            //101 Cancelamento
1207
            $x = 10;
1208
            $y = $this->hPrint-130;
1209
            $h = 25;
1210
            $w = $maxW-(2*$x);
1211
            $this->pdf->SetTextColor(90, 90, 90);
1212
            $texto = "NFe CANCELADA";
1213
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1214
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1215
            $this->pdf->SetTextColor(0, 0, 0);
1216
        }*/
1217
1218
        if ($this->notaDpec() || $this->tpEmis == 4) {
1219
            //DPEC
1220
            $x = 10;
1221
            $y = $this->hPrint-130;
1222
            $h = 25;
1223
            $w = $maxW-(2*$x);
1224
            $this->pdf->SetTextColor(200, 200, 200);
1225
            $texto = "DANFE impresso em contingência -\n".
1226
                     "DPEC regularmente recebido pela Receita\n".
1227
                     "Federal do Brasil";
1228
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1229
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1230
            $this->pdf->SetTextColor(0, 0, 0);
1231
        }
1232
        /*
1233
        if ($this->pNotaDenegada()) {
1234
            //110 301 302 Denegada
1235
            $x = 10;
1236
            $y = $this->hPrint-130;
1237
            $h = 25;
1238
            $w = $maxW-(2*$x);
1239
            $this->pdf->SetTextColor(90, 90, 90);
1240
            $texto = "NFe USO DENEGADO";
1241
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1242
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1243
            $y += $h;
1244
            $h = 5;
1245
            $w = $maxW-(2*$x);
1246
            if (isset($this->infProt)) {
1247
                $xMotivo = $this->infProt->getElementsByTagName("xMotivo")->item(0)->nodeValue;
1248
            } else {
1249
                $xMotivo = '';
1250
            }
1251
            $texto = "SEM VALOR FISCAL\n".$xMotivo;
1252
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1253
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1254
            $this->pdf->SetTextColor(0, 0, 0);
1255
        }
1256
         *
1257
         */
1258
        //indicar sem valor
1259
        /*
1260
        if ($tpAmb != 1) {
1261
            $x = 10;
1262
            if ($this->orientacao == 'P') {
1263
                $y = round($this->hPrint*2/3, 0);
1264
            } else {
1265
                $y = round($this->hPrint/2, 0);
1266
            }
1267
            $h = 5;
1268
            $w = $maxW-(2*$x);
1269
            $this->pdf->SetTextColor(90, 90, 90);
1270
            $texto = "SEM VALOR FISCAL";
1271
            $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1272
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1273
            $aFont = ['font'=>$this->fontePadrao, 'size'=>30, 'style'=>'B'];
1274
            $texto = "AMBIENTE DE HOMOLOGAÇÃO";
1275
            $this->pdf->textBox($x, $y+14, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1276
            $this->pdf->SetTextColor(0, 0, 0);
1277
        } else {
1278
            $x = 10;
1279
            if ($this->orientacao == 'P') {
1280
                $y = round($this->hPrint*2/3, 0);
1281
            } else {
1282
                $y = round($this->hPrint/2, 0);
1283
            }//fim orientacao
1284
            $h = 5;
1285
            $w = $maxW-(2*$x);
1286
            $this->pdf->SetTextColor(90, 90, 90);
1287
            //indicar FALTA DO PROTOCOLO se NFe não for em contingência
1288
            if (($this->tpEmis == 2 || $this->tpEmis == 5) && !$this->notaDpec()) {
1289
                //Contingência
1290
                $texto = "DANFE Emitido em Contingência";
1291
                $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1292
                $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1293
                $aFont = ['font'=>$this->fontePadrao, 'size'=>30, 'style'=>'B'];
1294
                $texto = "devido à problemas técnicos";
1295
                $this->pdf->textBox($x, $y+12, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1296
            } else {
1297
                if (!isset($this->nfeProc)) {
1298
                    if (!$this->notaDpec()) {
1299
                        $texto = "SEM VALOR FISCAL";
1300
                        $aFont = ['font'=>$this->fontePadrao, 'size'=>48, 'style'=>'B'];
1301
                        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1302
                    }
1303
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>30, 'style'=>'B'];
1304
                    $texto = "FALTA PROTOCOLO DE APROVAÇÃO DA SEFAZ";
1305
                    if (!$this->notaDpec()) {
1306
                        $this->pdf->textBox($x, $y+12, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1307
                    } else {
1308
                        $this->pdf->textBox($x, $y+25, $w, $h, $texto, $aFont, 'C', 'C', 0, '');
1309
                    }
1310
                }//fim nefProc
1311
            }//fim tpEmis
1312
            $this->pdf->SetTextColor(0, 0, 0);
1313
        }
1314
         *
1315
         */
1316
        return $oldY;
1317
    } //fim header
1318
1319
    /**
1320
     * destinatarioDANFE
1321
     * Monta o campo com os dados do destinatário na DANFE. (retrato e paisagem)
1322
     *
1323
     * @name   destinatarioDANFE
1324
     * @param  number $x Posição horizontal canto esquerdo
1325
     * @param  number $y Posição vertical canto superior
1326
     * @return number Posição vertical final
1327
     */
1328
    protected function destinatarioDANFE($x = 0, $y = 0)
1329
    {
1330
        //####################################################################################
1331
        //DESTINATÁRIO / REMETENTE
1332
        $oldX = $x;
1333
        $oldY = $y;
1334
        if ($this->orientacao == 'P') {
1335
            $maxW = $this->wPrint;
1336
        } else {
1337
            $maxW = $this->wPrint - $this->wCanhoto;
1338
        }
1339
        $w = $maxW;
1340
        $h = 7;
1341
        $texto = 'DESTINATÁRIO / REMETENTE';
1342
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1343
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
1344
        //NOME / RAZÃO SOCIAL
1345
        $w = round($maxW*0.61, 0);
1346
        $w1 = $w;
1347
        $y += 3;
1348
        $texto = 'NOME / RAZÃO SOCIAL';
1349
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1350
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1351
        $texto = $this->dest->getElementsByTagName("xNome")->item(0)->nodeValue;
1352
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1353
        if ($this->orientacao == 'P') {
1354
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'L', 0, '');
1355
        } else {
1356
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'L', 1, '');
1357
        }
1358
        //CNPJ / CPF
1359
        $x += $w;
1360
        $w = round($maxW*0.23, 0);
1361
        $w2 = $w;
1362
        $texto = 'CNPJ / CPF';
1363
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1364
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1365
        //Pegando valor do CPF/CNPJ
1366
        if (! empty($this->dest->getElementsByTagName("CNPJ")->item(0)->nodeValue)) {
1367
            $texto = $this->formatField(
1368
                $this->dest->getElementsByTagName("CNPJ")->item(0)->nodeValue,
1369
                "###.###.###/####-##"
1370
            );
1371
        } else {
1372
            $texto = ! empty($this->dest->getElementsByTagName("CPF")->item(0)->nodeValue) ?
1373
                    $this->formatField(
1374
                        $this->dest->getElementsByTagName("CPF")->item(0)->nodeValue,
1375
                        "###.###.###-##"
1376
                    ) : '';
1377
        }
1378
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1379
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1380
        //DATA DA EMISSÃO
1381
        $x += $w;
1382
        $w = $maxW-($w1+$w2);
1383
        $wx = $w;
1384
        $texto = 'DATA DA EMISSÃO';
1385
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1386
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1387
        $dEmi = ! empty($this->ide->getElementsByTagName("dEmi")->item(0)->nodeValue) ?
1388
                $this->ide->getElementsByTagName("dEmi")->item(0)->nodeValue : '';
1389
        if ($dEmi == '') {
1390
            $dEmi = ! empty($this->ide->getElementsByTagName("dhEmi")->item(0)->nodeValue) ?
1391
                    $this->ide->getElementsByTagName("dhEmi")->item(0)->nodeValue : '';
1392
            $aDemi = explode('T', $dEmi);
1393
            $dEmi = $aDemi[0];
1394
        }
1395
        $texto = $this->ymdTodmy($dEmi);
1396
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1397
        if ($this->orientacao == 'P') {
1398
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1399
        } else {
1400
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 1, '');
1401
        }
1402
        //ENDEREÇO
1403
        $w = round($maxW*0.47, 0);
1404
        $w1 = $w;
1405
        $y += $h;
1406
        $x = $oldX;
1407
        $texto = 'ENDEREÇO';
1408
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1409
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1410
        $texto = $this->dest->getElementsByTagName("xLgr")->item(0)->nodeValue;
1411
        $texto .= ', ' . $this->dest->getElementsByTagName("nro")->item(0)->nodeValue;
1412
        $texto .= $this->getTagValue($this->dest, "xCpl", " - ");
1413
1414
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1415
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'L', 0, '', true);
1416
        //BAIRRO / DISTRITO
1417
        $x += $w;
1418
        $w = round($maxW*0.21, 0);
1419
        $w2 = $w;
1420
        $texto = 'BAIRRO / DISTRITO';
1421
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1422
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1423
        $texto = $this->dest->getElementsByTagName("xBairro")->item(0)->nodeValue;
1424
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1425
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1426
        //CEP
1427
        $x += $w;
1428
        $w = $maxW-$w1-$w2-$wx;
1429
        $w2 = $w;
1430
        $texto = 'CEP';
1431
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1432
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1433
        $texto = ! empty($this->dest->getElementsByTagName("CEP")->item(0)->nodeValue) ?
1434
                $this->dest->getElementsByTagName("CEP")->item(0)->nodeValue : '';
1435
        $texto = $this->formatField($texto, "#####-###");
1436
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1437
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1438
        //DATA DA SAÍDA
1439
        $x += $w;
1440
        $w = $wx;
1441
        $texto = 'DATA DA SAÍDA/ENTRADA';
1442
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1443
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1444
        $dSaiEnt = ! empty($this->ide->getElementsByTagName("dSaiEnt")->item(0)->nodeValue) ?
1445
                $this->ide->getElementsByTagName("dSaiEnt")->item(0)->nodeValue : '';
1446
        if ($dSaiEnt == '') {
1447
            $dSaiEnt = ! empty($this->ide->getElementsByTagName("dhSaiEnt")->item(0)->nodeValue) ?
1448
                    $this->ide->getElementsByTagName("dhSaiEnt")->item(0)->nodeValue : '';
1449
            $aDsaient = explode('T', $dSaiEnt);
1450
            $dSaiEnt = $aDsaient[0];
1451
        }
1452
        $texto = $this->ymdTodmy($dSaiEnt);
1453
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1454
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1455
        //MUNICÍPIO
1456
        $w = $w1;
1457
        $y += $h;
1458
        $x = $oldX;
1459
        $texto = 'MUNICÍPIO';
1460
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1461
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1462
        $texto = $this->dest->getElementsByTagName("xMun")->item(0)->nodeValue;
1463
        if (strtoupper(trim($texto)) == "EXTERIOR" && $this->dest->getElementsByTagName("xPais")->length > 0) {
1464
            $texto .= " - " .  $this->dest->getElementsByTagName("xPais")->item(0)->nodeValue;
1465
        }
1466
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1467
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'L', 0, '');
1468
        //UF
1469
        $x += $w;
1470
        $w = 8;
1471
        $texto = 'UF';
1472
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1473
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1474
        $texto = $this->dest->getElementsByTagName("UF")->item(0)->nodeValue;
1475
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1476
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1477
        //FONE / FAX
1478
        $x += $w;
1479
        $w = round(($maxW -$w1-$wx-8)/2, 0);
1480
        $w3 = $w;
1481
        $texto = 'FONE / FAX';
1482
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1483
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1484
        $texto = ! empty($this->dest->getElementsByTagName("fone")->item(0)->nodeValue) ?
1485
                $this->dest->getElementsByTagName("fone")->item(0)->nodeValue : '';
1486
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1487
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1488
        //INSCRIÇÃO ESTADUAL
1489
        $x += $w;
1490
        $w = $maxW -$w1-$wx-8-$w3;
1491
        $texto = 'INSCRIÇÃO ESTADUAL';
1492
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1493
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1494
        $IE = $this->dest->getElementsByTagName("IE");
1495
        $texto = ($IE && $IE->length > 0) ? $IE->item(0)->nodeValue : '';
1496
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1497
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1498
        //HORA DA SAÍDA
1499
        $x += $w;
1500
        $w = $wx;
1501
        $texto = 'HORA DA SAÍDA/ENTRADA';
1502
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1503
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
1504
        $hSaiEnt = ! empty($this->ide->getElementsByTagName("hSaiEnt")->item(0)->nodeValue) ?
1505
                $this->ide->getElementsByTagName("hSaiEnt")->item(0)->nodeValue : '';
1506
        if ($hSaiEnt == '') {
1507
            $dhSaiEnt = ! empty($this->ide->getElementsByTagName("dhSaiEnt")->item(0)->nodeValue) ?
1508
                    $this->ide->getElementsByTagName("dhSaiEnt")->item(0)->nodeValue : '';
1509
            $tsDhSaiEnt = $this->convertTime($dhSaiEnt);
1510
            if ($tsDhSaiEnt != '') {
1511
                $hSaiEnt = date('H:i:s', $tsDhSaiEnt);
1512
            }
1513
        }
1514
        $texto = $hSaiEnt;
1515
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1516
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
1517
        return ($y + $h);
1518
    } //fim da função destinatarioDANFE
1519
1520
     /**
1521
     * getTextoFatura
1522
     * Gera a String do Texto da Fatura
1523
      *
1524
     * @name   getTextoFatura
1525
     * @return uma String com o texto ou "";
1526
     */
1527
    protected function getTextoFatura()
1528
    {
1529
        if (isset($this->cobr)) {
1530
            $fat = $this->cobr->getElementsByTagName("fat")->item(0);
1531
            if (isset($fat)) {
1532
                if (!empty($this->getTagValue($this->ide, "indPag"))) {
1533
                    $textoIndPag = "";
1534
                    $indPag = $this->getTagValue($this->ide, "indPag");
1535
                    if ($indPag === "0") {
1536
                        $textoIndPag = "Pagamento à Vista - ";
1537
                    } elseif ($indPag === "1") {
1538
                        $textoIndPag = "Pagamento à Prazo - ";
1539
                    }
1540
                    $nFat = $this->getTagValue($fat, "nFat", "Fatura: ");
1541
                    $vOrig = $this->getTagValue($fat, "vOrig", " Valor Original: ");
1542
                    $vDesc = $this->getTagValue($fat, "vDesc", " Desconto: ");
1543
                    $vLiq = $this->getTagValue($fat, "vLiq", " Valor Líquido: ");
1544
                    $texto = $textoIndPag . $nFat . $vOrig . $vDesc . $vLiq;
1545
                    return $texto;
1546
                } else {
1547
                    $pag = $this->dom->getElementsByTagName("pag");
1548
                    if ($tPag = $this->getTagValue($pag->item(0), "tPag")) {
1549
                        return $this->tipoPag($tPag);
1550
                    }
1551
                }
1552
            }
1553
        }
1554
        return "";
1555
    }
1556
1557
     /**
1558
     * sizeExtraTextoFatura
1559
     * Calcula o espaço ocupado pelo texto da fatura. Este espaço só é utilizado quando não houver duplicata.
1560
      *
1561
     * @name   sizeExtraTextoFatura
1562
     * @return integer
1563
     */
1564
    protected function sizeExtraTextoFatura()
1565
    {
1566
        $textoFatura = $this->getTextoFatura();
1567
        //verificar se existem duplicatas
1568
        if ($this->dup->length == 0 && $textoFatura !== "") {
1569
            return 10;
1570
        }
1571
        return 0;
1572
    }
1573
1574
    /**
1575
     * fatura
1576
     * Monta o campo de duplicatas da DANFE (retrato e paisagem)
1577
     *
1578
     * @name   fatura
1579
     * @param  number $x Posição horizontal canto esquerdo
1580
     * @param  number $y Posição vertical canto superior
1581
     * @return number Posição vertical final
1582
     */
1583
    protected function fatura($x, $y)
1584
    {
1585
        $linha = 1;
1586
        $h = 8+3;
1587
        $oldx = $x;
1588
        $textoFatura = $this->getTextoFatura();
1589
        //verificar se existem duplicatas
1590
        if ($this->dup->length > 0 || $textoFatura !== "") {
1591
            //#####################################################################
1592
            //FATURA / DUPLICATA
1593
            $texto = "FATURA / DUPLICATA";
1594
            if ($this->orientacao == 'P') {
1595
                $w = $this->wPrint;
1596
            } else {
1597
                $w = 271;
1598
            }
1599
            $h = 8;
1600
            $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1601
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
1602
            $y += 3;
1603
            $dups = "";
1604
            $dupcont = 0;
1605
            $nFat = $this->dup->length;
1606
            if ($nFat > 7) {
1607
                $myH = 6;
1608
                $myW = $this->wPrint;
1609
                if ($this->orientacao == 'L') {
1610
                    $myW -= $this->wCanhoto;
1611
                }
1612
                $aFont = ['font' => $this->fontePadrao, 'size' => 9, 'style' => ''];
1613
                $texto = "Existem mais de 7 duplicatas registradas, portanto não "
1614
                    . "serão exibidas, confira diretamente pelo XML.";
1615
                $this->pdf->textBox($x, $y, $myW, $myH, $texto, $aFont, 'C', 'C', 1, '');
1616
                return ($y + $h - 3);
1617
            }
1618
            if ($textoFatura !== "" && $this->exibirTextoFatura) {
1619
                $myH=6;
1620
                $myW = $this->wPrint;
1621
                if ($this->orientacao == 'L') {
1622
                    $myW -= $this->wCanhoto;
1623
                }
1624
                $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>''];
1625
                $this->pdf->textBox($x, $y, $myW, $myH, $textoFatura, $aFont, 'C', 'L', 1, '');
1626
                $y+=$myH+1;
1627
            }
1628
            if ($this->orientacao == 'P') {
1629
                $w = round($this->wPrint/7.018, 0)-1;
1630
            } else {
1631
                $w = 28;
1632
            }
1633
            $increm = 1;
1634
            foreach ($this->dup as $k => $d) {
1635
                $nDup = ! empty($this->dup->item($k)->getElementsByTagName('nDup')->item(0)->nodeValue) ?
1636
                        $this->dup->item($k)->getElementsByTagName('nDup')->item(0)->nodeValue : '';
1637
                $dDup = ! empty($this->dup->item($k)->getElementsByTagName('dVenc')->item(0)->nodeValue) ?
1638
                        $this->ymdTodmy($this->dup->item($k)->getElementsByTagName('dVenc')->item(0)->nodeValue) : '';
1639
                $vDup = ! empty($this->dup->item($k)->getElementsByTagName('vDup')->item(0)->nodeValue) ?
1640
                        'R$ ' . number_format(
1641
                            $this->dup->item($k)->getElementsByTagName('vDup')->item(0)->nodeValue,
1642
                            2,
1643
                            ",",
1644
                            "."
1645
                        ) : '';
1646
                $h = 8;
1647
                $texto = '';
1648
                if ($nDup!='0' && $nDup!='') {
1649
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1650
                    $this->pdf->textBox($x, $y, $w, $h, 'Num.', $aFont, 'T', 'L', 1, '');
1651
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1652
                    $this->pdf->textBox($x, $y, $w, $h, $nDup, $aFont, 'T', 'R', 0, '');
1653
                } else {
1654
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1655
                    $this->pdf->textBox($x, $y, $w, $h, ($dupcont+1)."", $aFont, 'T', 'L', 1, '');
1656
                }
1657
                $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1658
                $this->pdf->textBox($x, $y, $w, $h, 'Venc.', $aFont, 'C', 'L', 0, '');
1659
                $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1660
                $this->pdf->textBox($x, $y, $w, $h, $dDup, $aFont, 'C', 'R', 0, '');
1661
                $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1662
                $this->pdf->textBox($x, $y, $w, $h, 'Valor', $aFont, 'B', 'L', 0, '');
1663
                $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1664
                $this->pdf->textBox($x, $y, $w, $h, $vDup, $aFont, 'B', 'R', 0, '');
1665
                $x += $w+$increm;
1666
                $dupcont += 1;
1667
                if ($this->orientacao == 'P') {
1668
                    $maxDupCont = 6;
1669
                } else {
1670
                    $maxDupCont = 8;
1671
                }
1672
                if ($dupcont > $maxDupCont) {
1673
                    $y += 9;
1674
                    $x = $oldx;
1675
                    $dupcont = 0;
1676
                    $linha += 1;
1677
                }
1678
                if ($linha == 5) {
1679
                    $linha = 4;
1680
                    break;
1681
                }
1682
            }
1683
            if ($dupcont == 0) {
1684
                $y -= 9;
1685
                $linha--;
1686
            }
1687
            return ($y+$h);
1688
        } else {
1689
            $linha = 0;
1690
            return ($y-2);
1691
        }
1692
    }
1693
1694
    /**
1695
     * pagamento
1696
     * Monta o campo de pagamentos da DANFE (retrato e paisagem) (foi baseada na fatura)
1697
     *
1698
     * @name   pagamento
1699
     * @param  number $x Posição horizontal canto esquerdo
1700
     * @param  number $y Posição vertical canto superior
1701
     * @return number Posição vertical final
1702
     */
1703
    protected function pagamento($x, $y)
1704
    {
1705
        $linha = 1;
1706
        $h = 8+3;
1707
        $oldx = $x;
1708
        //verificar se existem cobranças definidas
1709
        if (isset($this->detPag) && $this->detPag->length > 0) {
1710
            //#####################################################################
1711
            //Tipo de pagamento
1712
            $texto = "PAGAMENTO";
1713
            if ($this->orientacao == 'P') {
1714
                $w = $this->wPrint;
1715
            } else {
1716
                $w = 271;
1717
            }
1718
            $h = 8;
1719
            $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1720
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
1721
            $y += 3;
1722
            $dups = "";
1723
            $dupcont = 0;
1724
            if ($this->orientacao == 'P') {
1725
                $w = round($this->wPrint/7.018, 0)-1;
1726
            } else {
1727
                $w = 28;
1728
            }
1729
            if ($this->orientacao == 'P') {
1730
                $maxDupCont = 6;
1731
            } else {
1732
                $maxDupCont = 8;
1733
            }
1734
            $increm = 1;
1735
            $formaPagamento = ['01'=>'Dinheiro','02'=>'Cheque','03'=>'Cartão de Crédito',
1736
                                    '04'=>'Cartão de Débito','05'=>'Crédito Loja','10'=>'Vale Alimentação',
1737
                                    '11'=>'Vale Refeição','12'=>'Vale Presente','13'=>'Vale Combustível',
1738
                                    '14'=>'Duplicata Mercantil','15'=>'Boleto','90'=>'Sem pagamento','99'=>'Outros'];
1739
            $bandeira = ['01'=>'Visa','02'=>'Mastercard','03'=>'American','04'=>'Sorocred','05'=>'Diners',
1740
                              '06'=>'Elo','07'=>'Hipercard','08'=>'Aura','09'=>'Cabal','99'=>'Outros'];
1741
            foreach ($this->detPag as $k => $d) {
1742
                $fPag = !empty($this->detPag->item($k)->getElementsByTagName('tPag')->item(0)->nodeValue)
1743
                    ? $this->detPag->item($k)->getElementsByTagName('tPag')->item(0)->nodeValue : '0';
1744
                $vPag = ! empty($this->detPag->item($k)->getElementsByTagName('vPag')->item(0)->nodeValue)
1745
                    ? 'R$ ' . number_format(
1746
                        $this->detPag->item($k)->getElementsByTagName('vPag')->item(0)->nodeValue,
1747
                        2,
1748
                        ",",
1749
                        "."
1750
                    ) : '';
1751
                $h = 6;
1752
                $texto = '';
1753
                if (isset($formaPagamento[$fPag])) {
1754
                    /*Exibir Item sem pagamento ou outros?*/
1755
                    if ($fPag=='90' || $fPag=='99') {
1756
                        continue;
1757
                    }
1758
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1759
                    $this->pdf->textBox($x, $y, $w, $h, 'Forma', $aFont, 'T', 'L', 1, '');
1760
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1761
                    $this->pdf->textBox($x, $y, $w, $h, $formaPagamento[$fPag], $aFont, 'T', 'R', 0, '');
1762
                } else {
1763
                    $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
1764
                    $this->pdf->textBox($x, $y, $w, $h, "Forma ".$fPag." não encontrado", $aFont, 'T', 'L', 1, '');
1765
                }
1766
                $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1767
                $this->pdf->textBox($x, $y, $w, $h, 'Valor', $aFont, 'B', 'L', 0, '');
1768
                $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1769
                $this->pdf->textBox($x, $y, $w, $h, $vPag, $aFont, 'B', 'R', 0, '');
1770
                $x += $w+$increm;
1771
                $dupcont += 1;
1772
1773
                if ($dupcont>$maxDupCont) {
1774
                    $y += 9;
1775
                    $x = $oldx;
1776
                    $dupcont = 0;
1777
                    $linha += 1;
1778
                }
1779
                if ($linha == 5) {
1780
                    $linha = 4;
1781
                    break;
1782
                }
1783
            }
1784
            if ($dupcont == 0) {
1785
                $y -= 9;
1786
                $linha--;
1787
            }
1788
            return ($y+$h);
1789
        } else {
1790
            $linha = 0;
1791
            return ($y-2);
1792
        }
1793
    } //fim da função pagamento
1794
    
1795
    /**
1796
     * impostoHelper
1797
     * Auxilia a montagem dos campos de impostos e totais da DANFE
1798
     *
1799
     * @name   impostoHelper
1800
     * @param  float $x Posição horizontal canto esquerdo
1801
     * @param  float $y Posição vertical canto superior
1802
     * @param  float $w Largura do campo
1803
     * @param  float $h Altura do campo
1804
     * @param  float $h Título do campo
1805
     * @param  float $h Valor do imposto
1806
     * @return float Sugestão do $x do próximo imposto
1807
     */
1808
    protected function impostoHelper($x, $y, $w, $h, $titulo, $campoImposto)
1809
    {
1810
        $valorImposto = '0, 00';
1811
        $the_field = $this->ICMSTot->getElementsByTagName($campoImposto)->item(0);
1812
        if (isset($the_field)) {
1813
            $the_value = $the_field->nodeValue;
1814
            if (!empty($the_value)) {
1815
                $valorImposto = number_format($the_value, 2, ",", ".");
1816
            }
1817
        }
1818
1819
        $fontTitulo = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1820
        $fontValor = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1821
        $this->pdf->textBox($x, $y, $w, $h, $titulo, $fontTitulo, 'T', 'L', 1, '');
1822
        $this->pdf->textBox($x, $y, $w, $h, $valorImposto, $fontValor, 'B', 'R', 0, '');
1823
1824
        $next_x = $x + $w;
1825
        return $next_x;
1826
    }
1827
1828
    /**
1829
     * imposto
1830
     * Monta o campo de impostos e totais da DANFE (retrato e paisagem)
1831
     *
1832
     * @param  number $x Posição horizontal canto esquerdo
1833
     * @param  number $y Posição vertical canto superior
1834
     * @return number Posição vertical final
1835
     */
1836
    protected function imposto($x, $y)
1837
    {
1838
        $x_inicial = $x;
1839
        //#####################################################################
1840
1841
1842
        $campos_por_linha = 9;
1843
        if (!$this->exibirPIS) {
1844
            $campos_por_linha--;
1845
        }
1846
        if (!$this->exibirIcmsInterestadual) {
1847
            $campos_por_linha -= 2;
1848
        }
1849
1850
        if ($this->orientacao == 'P') {
1851
            $maxW = $this->wPrint;
1852
            $title_size = 31;
1853
        } else {
1854
            $maxW = $this->wPrint - $this->wCanhoto;
1855
            $title_size = 40;
1856
        }
1857
        $w = $maxW / $campos_por_linha;
1858
1859
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1860
        $texto = "CÁLCULO DO IMPOSTO";
1861
        $this->pdf->textBox($x, $y, $title_size, 8, $texto, $aFont, 'T', 'L', 0, '');
1862
        $y += 3;
1863
        $h = 7;
1864
1865
        $x = $this->impostoHelper($x, $y, $w, $h, "BASE DE CÁLC. DO ICMS", "vBC");
1866
        $x = $this->impostoHelper($x, $y, $w, $h, "VALOR DO ICMS", "vICMS");
1867
        $x = $this->impostoHelper($x, $y, $w, $h, "BASE DE CÁLC. ICMS S.T.", "vBCST");
1868
        $x = $this->impostoHelper($x, $y, $w, $h, "VALOR DO ICMS SUBST.", "vST");
1869
        $x = $this->impostoHelper($x, $y, $w, $h, "V. IMP. IMPORTAÇÃO", "vII");
1870
1871
        if ($this->exibirIcmsInterestadual) {
1872
            $x = $this->impostoHelper($x, $y, $w, $h, "V. ICMS UF REMET.", "vICMSUFRemet");
1873
            $x = $this->impostoHelper($x, $y, $w, $h, "V. FCP UF DEST.", "vFCPUFDest");
1874
        }
1875
1876
        if ($this->exibirPIS) {
1877
            $x = $this->impostoHelper($x, $y, $w, $h, "VALOR DO PIS", "vPIS");
1878
        }
1879
1880
        $x = $this->impostoHelper($x, $y, $w, $h, "V. TOTAL PRODUTOS", "vProd");
1881
1882
        //
1883
1884
        $y += $h;
1885
        $x = $x_inicial;
1886
1887
        $x = $this->impostoHelper($x, $y, $w, $h, "VALOR DO FRETE", "vFrete");
1888
        $x = $this->impostoHelper($x, $y, $w, $h, "VALOR DO SEGURO", "vSeg");
1889
        $x = $this->impostoHelper($x, $y, $w, $h, "DESCONTO", "vDesc");
1890
        $x = $this->impostoHelper($x, $y, $w, $h, "OUTRAS DESPESAS", "vOutro");
1891
        $x = $this->impostoHelper($x, $y, $w, $h, "VALOR TOTAL IPI", "vIPI");
1892
1893
        if ($this->exibirIcmsInterestadual) {
1894
            $x = $this->impostoHelper($x, $y, $w, $h, "V. ICMS UF DEST.", "vICMSUFDest");
1895
            $x = $this->impostoHelper($x, $y, $w, $h, "V. TOT. TRIB.", "vTotTrib");
1896
        }
1897
1898
        if ($this->exibirPIS) {
1899
            $x = $this->impostoHelper($x, $y, $w, $h, "VALOR DA COFINS", "vCOFINS");
1900
        }
1901
        $x = $this->impostoHelper($x, $y, $w, $h, "V. TOTAL DA NOTA", "vNF");
1902
1903
        return ($y+$h);
1904
    } //fim imposto
1905
1906
    /**
1907
     * transporte
1908
     * Monta o campo de transportes da DANFE (retrato e paisagem)
1909
     *
1910
     * @name   transporte
1911
     * @param  float $x Posição horizontal canto esquerdo
1912
     * @param  float $y Posição vertical canto superior
1913
     * @return float Posição vertical final
1914
     */
1915
    protected function transporte($x, $y)
1916
    {
1917
        $oldX = $x;
1918
        if ($this->orientacao == 'P') {
1919
            $maxW = $this->wPrint;
1920
        } else {
1921
            $maxW = $this->wPrint - $this->wCanhoto;
1922
        }
1923
        //#####################################################################
1924
        //TRANSPORTADOR / VOLUMES TRANSPORTADOS
1925
        $texto = "TRANSPORTADOR / VOLUMES TRANSPORTADOS";
1926
        $w = $maxW;
1927
        $h = 7;
1928
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
1929
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
1930
        //NOME / RAZÃO SOCIAL
1931
        $w1 = $maxW*0.29;
1932
        $y += 3;
1933
        $texto = 'NOME / RAZÃO SOCIAL';
1934
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1935
        $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'T', 'L', 1, '');
1936
        if (isset($this->transporta)) {
1937
            $texto = ! empty($this->transporta->getElementsByTagName("xNome")->item(0)->nodeValue) ?
1938
                    $this->transporta->getElementsByTagName("xNome")->item(0)->nodeValue : '';
1939
        } else {
1940
            $texto = '';
1941
        }
1942
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1943
        $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'B', 'L', 0, '');
1944
        //FRETE POR CONTA
1945
        $x += $w1;
1946
        $w2 = $maxW*0.15;
1947
        $texto = 'FRETE';
1948
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1949
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
1950
        $tipoFrete = ! empty($this->transp->getElementsByTagName("modFrete")->item(0)->nodeValue) ?
1951
                $this->transp->getElementsByTagName("modFrete")->item(0)->nodeValue : '0';
1952
        switch ($tipoFrete) {
1953
            case 0:
1954
                $texto = "0-Por conta do Rem";
1955
                break;
1956
            case 1:
1957
                $texto = "1-Por conta do Dest";
1958
                break;
1959
            case 2:
1960
                $texto = "2-Por conta de Terceiros";
1961
                break;
1962
            case 3:
1963
                $texto = "3-Próprio por conta do Rem";
1964
                break;
1965
            case 4:
1966
                $texto = "4-Próprio por conta do Dest";
1967
                break;
1968
            case 9:
1969
                $texto = "9-Sem Transporte";
1970
                break;
1971
        }
1972
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1973
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'C', 'C', 1, '');
1974
        //CÓDIGO ANTT
1975
        $x += $w2;
1976
        $texto = 'CÓDIGO ANTT';
1977
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1978
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
1979
        if (isset($this->veicTransp)) {
1980
            $texto = ! empty($this->veicTransp->getElementsByTagName("RNTC")->item(0)->nodeValue) ?
1981
                    $this->veicTransp->getElementsByTagName("RNTC")->item(0)->nodeValue : '';
1982
        } else {
1983
            $texto = '';
1984
        }
1985
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
1986
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'B', 'C', 0, '');
1987
        //PLACA DO VEÍC
1988
        $x += $w2;
1989
        $texto = 'PLACA DO VEÍCULO';
1990
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
1991
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
1992
        if (isset($this->veicTransp)) {
1993
            $texto = ! empty($this->veicTransp->getElementsByTagName("placa")->item(0)->nodeValue) ?
1994
                    $this->veicTransp->getElementsByTagName("placa")->item(0)->nodeValue : '';
1995
        } elseif (isset($this->reboque)) {
1996
            $texto = ! empty($this->reboque->getElementsByTagName("placa")->item(0)->nodeValue) ?
1997
                    $this->reboque->getElementsByTagName("placa")->item(0)->nodeValue : '';
1998
        } else {
1999
            $texto = '';
2000
        }
2001
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2002
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'B', 'C', 0, '');
2003
        //UF
2004
        $x += $w2;
2005
        $w3 = round($maxW*0.04, 0);
2006
        $texto = 'UF';
2007
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2008
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'T', 'L', 1, '');
2009
        if (isset($this->veicTransp)) {
2010
            $texto = ! empty($this->veicTransp->getElementsByTagName("UF")->item(0)->nodeValue) ?
2011
                    $this->veicTransp->getElementsByTagName("UF")->item(0)->nodeValue : '';
2012
        } elseif (isset($this->reboque)) {
2013
            $texto = ! empty($this->reboque->getElementsByTagName("UF")->item(0)->nodeValue) ?
2014
                    $this->reboque->getElementsByTagName("UF")->item(0)->nodeValue : '';
2015
        } else {
2016
            $texto = '';
2017
        }
2018
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2019
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'B', 'C', 0, '');
2020
        //CNPJ / CPF
2021
        $x += $w3;
2022
        $w = $maxW-($w1+3*$w2+$w3);
2023
        $texto = 'CNPJ / CPF';
2024
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2025
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2026
        if (isset($this->transporta)) {
2027
            $texto = ! empty($this->transporta->getElementsByTagName("CNPJ")->item(0)->nodeValue) ?
2028
                    $this->formatField(
2029
                        $this->transporta->getElementsByTagName("CNPJ")->item(0)->nodeValue,
2030
                        "##.###.###/####-##"
2031
                    ) : '';
2032
            if ($texto == '') {
2033
                $texto = ! empty($this->transporta->getElementsByTagName("CPF")->item(0)->nodeValue) ?
2034
                        $this->formatField(
2035
                            $this->transporta->getElementsByTagName("CPF")->item(0)->nodeValue,
2036
                            "###.###.###-##"
2037
                        ) : '';
2038
            }
2039
        } else {
2040
            $texto = '';
2041
        }
2042
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2043
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
2044
        //#####################################################################
2045
        //ENDEREÇO
2046
        $y += $h;
2047
        $x = $oldX;
2048
        $h = 7;
2049
        $w1 = $maxW*0.44;
2050
        $texto = 'ENDEREÇO';
2051
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2052
        $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'T', 'L', 1, '');
2053
        if (isset($this->transporta)) {
2054
            $texto = ! empty($this->transporta->getElementsByTagName("xEnder")->item(0)->nodeValue) ?
2055
                    $this->transporta->getElementsByTagName("xEnder")->item(0)->nodeValue : '';
2056
        } else {
2057
            $texto = '';
2058
        }
2059
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2060
        $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'B', 'L', 0, '');
2061
        //MUNICÍPIO
2062
        $x += $w1;
2063
        $w2 = round($maxW*0.30, 0);
2064
        $texto = 'MUNICÍPIO';
2065
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2066
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
2067
        if (isset($this->transporta)) {
2068
            $texto = ! empty($this->transporta->getElementsByTagName("xMun")->item(0)->nodeValue) ?
2069
                    $this->transporta->getElementsByTagName("xMun")->item(0)->nodeValue : '';
2070
        } else {
2071
            $texto = '';
2072
        }
2073
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2074
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'B', 'C', 0, '');
2075
        //UF
2076
        $x += $w2;
2077
        $w3 = round($maxW*0.04, 0);
2078
        $texto = 'UF';
2079
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2080
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'T', 'L', 1, '');
2081
        if (isset($this->transporta)) {
2082
            $texto = ! empty($this->transporta->getElementsByTagName("UF")->item(0)->nodeValue) ?
2083
                    $this->transporta->getElementsByTagName("UF")->item(0)->nodeValue : '';
2084
        } else {
2085
            $texto = '';
2086
        }
2087
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2088
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'B', 'C', 0, '');
2089
        //INSCRIÇÃO ESTADUAL
2090
        $x += $w3;
2091
        $w = $maxW-($w1+$w2+$w3);
2092
        $texto = 'INSCRIÇÃO ESTADUAL';
2093
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2094
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2095
        $texto = '';
2096
        if (isset($this->transporta)) {
2097
            if (! empty($this->transporta->getElementsByTagName("IE")->item(0)->nodeValue)) {
2098
                $texto = $this->transporta->getElementsByTagName("IE")->item(0)->nodeValue;
2099
            }
2100
        }
2101
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2102
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'C', 0, '');
2103
        //Tratar Multiplos volumes
2104
        $volumes = $this->transp->getElementsByTagName('vol');
2105
        $quantidade = 0;
2106
        $especie = '';
2107
        $marca = '';
2108
        $numero = '';
2109
        $texto = '';
2110
        $pesoBruto=0;
2111
        $pesoLiquido=0;
2112
        foreach ($volumes as $volume) {
2113
            $quantidade += ! empty($volume->getElementsByTagName("qVol")->item(0)->nodeValue) ?
2114
                    $volume->getElementsByTagName("qVol")->item(0)->nodeValue : 0;
2115
            $pesoBruto += ! empty($volume->getElementsByTagName("pesoB")->item(0)->nodeValue) ?
2116
                    $volume->getElementsByTagName("pesoB")->item(0)->nodeValue : 0;
2117
            $pesoLiquido += ! empty($volume->getElementsByTagName("pesoL")->item(0)->nodeValue) ?
2118
                    $volume->getElementsByTagName("pesoL")->item(0)->nodeValue : 0;
2119
            $texto = ! empty($this->transp->getElementsByTagName("esp")->item(0)->nodeValue) ?
2120
                    $this->transp->getElementsByTagName("esp")->item(0)->nodeValue : '';
2121
            if ($texto != $especie && $especie != '') {
2122
                //tem várias especies
2123
                $especie = 'VARIAS';
2124
            } else {
2125
                $especie = $texto;
2126
            }
2127
            $texto = ! empty($this->transp->getElementsByTagName("marca")->item(0)->nodeValue) ?
2128
                    $this->transp->getElementsByTagName("marca")->item(0)->nodeValue : '';
2129
            if ($texto != $marca && $marca != '') {
2130
                //tem várias especies
2131
                $marca = 'VARIAS';
2132
            } else {
2133
                $marca = $texto;
2134
            }
2135
            $texto = ! empty($this->transp->getElementsByTagName("nVol")->item(0)->nodeValue) ?
2136
                    $this->transp->getElementsByTagName("nVol")->item(0)->nodeValue : '';
2137
            if ($texto != $numero && $numero != '') {
2138
                //tem várias especies
2139
                $numero = 'VARIOS';
2140
            } else {
2141
                $numero = $texto;
2142
            }
2143
        }
2144
2145
        //#####################################################################
2146
        //QUANTIDADE
2147
        $y += $h;
2148
        $x = $oldX;
2149
        $h = 7;
2150
        $w1 = round($maxW*0.10, 0);
2151
        $texto = 'QUANTIDADE';
2152
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2153
        $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'T', 'L', 1, '');
2154
        if (!empty($quantidade)) {
2155
            $texto = $quantidade;
2156
            $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2157
            $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'B', 'C', 0, '');
2158
        }
2159
        //ESPÉCIE
2160
        $x += $w1;
2161
        $w2 = round($maxW*0.17, 0);
2162
        $texto = 'ESPÉCIE';
2163
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2164
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
2165
        $texto = $especie;
2166
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2167
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'B', 'C', 0, '');
2168
        //MARCA
2169
        $x += $w2;
2170
        $texto = 'MARCA';
2171
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2172
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
2173
        $texto = ! empty($this->transp->getElementsByTagName("marca")->item(0)->nodeValue) ?
2174
                $this->transp->getElementsByTagName("marca")->item(0)->nodeValue : '';
2175
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2176
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'B', 'C', 0, '');
2177
        //NUMERAÇÃO
2178
        $x += $w2;
2179
        $texto = 'NUMERAÇÃO';
2180
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2181
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'T', 'L', 1, '');
2182
        $texto = $numero;
2183
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2184
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'B', 'C', 0, '');
2185
        //PESO BRUTO
2186
        $x += $w2;
2187
        $w3 = round($maxW*0.20, 0);
2188
        $texto = 'PESO BRUTO';
2189
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2190
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'T', 'L', 1, '');
2191
        if (is_numeric($pesoBruto) && $pesoBruto > 0) {
2192
            $texto = number_format($pesoBruto, 3, ",", ".");
2193
        } else {
2194
            $texto = '';
2195
        }
2196
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2197
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'B', 'R', 0, '');
2198
        //PESO LÍQUIDO
2199
        $x += $w3;
2200
        $w = $maxW -($w1+3*$w2+$w3);
2201
        $texto = 'PESO LÍQUIDO';
2202
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2203
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2204
        if (is_numeric($pesoLiquido) && $pesoLiquido > 0) {
2205
            $texto = number_format($pesoLiquido, 3, ",", ".");
2206
        } else {
2207
            $texto = '';
2208
        }
2209
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2210
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'R', 0, '');
2211
        return ($y+$h);
2212
    } //fim transporte
2213
2214
2215
2216
    protected function descricaoProdutoHelper($origem, $campo, $formato)
2217
    {
2218
        $valor_original = $origem->getElementsByTagName($campo)->item(0);
2219
        if (!isset($valor_original)) {
2220
            return "";
2221
        }
2222
        $valor_original = $valor_original->nodeValue;
2223
        $valor = ! empty($valor_original) ? number_format($valor_original, 2, ",", ".") : '';
2224
2225
        if ($valor != "") {
2226
            return sprintf($formato, $valor);
2227
        }
2228
        return "";
2229
    }
2230
2231
    /**
2232
     * descricaoProduto
2233
     * Monta a string de descrição de cada Produto
2234
     *
2235
     * @name   descricaoProduto
2236
     * @param  DOMNode itemProd
2237
     * @return string descricao do produto
2238
     */
2239
    protected function descricaoProduto($itemProd)
2240
    {
2241
        $prod = $itemProd->getElementsByTagName('prod')->item(0);
2242
        $ICMS = $itemProd->getElementsByTagName("ICMS")->item(0);
2243
        $ICMSUFDest = $itemProd->getElementsByTagName("ICMSUFDest")->item(0);
2244
        $impostos = '';
2245
2246
        if (!empty($ICMS)) {
2247
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vBCFCP", " BcFcp=%s");
2248
            $impostos .= $this->descricaoProdutoHelper($ICMS, "pFCP", " pFcp=%s%%");
2249
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vFCP", " vFcp=%s");
2250
            $impostos .= $this->descricaoProdutoHelper($ICMS, "pRedBC", " pRedBC=%s%%");
2251
            $impostos .= $this->descricaoProdutoHelper($ICMS, "pMVAST", " IVA/MVA=%s%%");
2252
            $impostos .= $this->descricaoProdutoHelper($ICMS, "pICMSST", " pIcmsSt=%s%%");
2253
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vBCST", " BcIcmsSt=%s");
2254
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vICMSST", " vIcmsSt=%s");
2255
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vBCFCPST", " BcFcpSt=%s");
2256
            $impostos .= $this->descricaoProdutoHelper($ICMS, "pFCPST", " pFcpSt=%s%%");
2257
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vFCPST", " vFcpSt=%s");
2258
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vBCSTRet", " vBcStRet=%s");
2259
            $impostos .= $this->descricaoProdutoHelper($ICMS, "pST", " pSt=%s");
2260
            $impostos .= $this->descricaoProdutoHelper($ICMS, "vICMSSTRet", " vIcmsStRet=%s");
2261
        }
2262
        if (!empty($ICMSUFDest)) {
2263
            $impostos .= $this->descricaoProdutoHelper($ICMSUFDest, "pFCPUFDest", " pFCPUFDest=%s%%");
2264
            $impostos .= $this->descricaoProdutoHelper($ICMSUFDest, "pICMSUFDest", " pICMSUFDest=%s%%");
2265
            $impostos .= $this->descricaoProdutoHelper($ICMSUFDest, "pICMSInterPart", " pICMSInterPart=%s%%");
2266
            $impostos .= $this->descricaoProdutoHelper($ICMSUFDest, "vFCPUFDest", " vFCPUFDest=%s");
2267
            $impostos .= $this->descricaoProdutoHelper($ICMSUFDest, "vICMSUFDest", " vICMSUFDest=%s");
2268
            $impostos .= $this->descricaoProdutoHelper($ICMSUFDest, "vICMSUFRemet", " vICMSUFRemet=%s");
2269
        }
2270
        $infAdProd = ! empty($itemProd->getElementsByTagName('infAdProd')->item(0)->nodeValue)
2271
            ? substr(
2272
                $this->anfaveaDANFE($itemProd->getElementsByTagName('infAdProd')->item(0)->nodeValue),
2273
                0,
2274
                500
2275
            )
2276
            : '';
2277
        if (! empty($infAdProd)) {
2278
            $infAdProd = trim($infAdProd);
2279
            $infAdProd .= ' ';
2280
        }
2281
        $loteTxt ='';
2282
        $rastro = $prod->getElementsByTagName("med");
2283
        if (!empty($prod->getElementsByTagName("rastro"))) {
2284
            $rastro = $prod->getElementsByTagName("rastro");
2285
            $i = 0;
2286
            while ($i < $rastro->length) {
2287
                $loteTxt .= $this->getTagValue($rastro->item($i), 'nLote', ' Lote: ');
2288
                $loteTxt .= $this->getTagValue($rastro->item($i), 'qLote', ' Quant: ');
2289
                $loteTxt .= $this->getTagDate($rastro->item($i), 'dFab', ' Fab: ');
2290
                $loteTxt .= $this->getTagDate($rastro->item($i), 'dVal', ' Val: ');
2291
                $loteTxt .= $this->getTagValue($rastro->item($i), 'vPMC', ' PMC: ');
2292
                $i++;
2293
            }
2294
            if ($loteTxt != '') {
2295
                $loteTxt.= ' ';
2296
            }
2297
        }
2298
        //NT2013.006 FCI
2299
        $nFCI = (! empty($itemProd->getElementsByTagName('nFCI')->item(0)->nodeValue)) ?
2300
                ' FCI:'.$itemProd->getElementsByTagName('nFCI')->item(0)->nodeValue : '';
2301
        $tmp_ad=$infAdProd . ($this->descProdInfoComplemento ? $loteTxt . $impostos . $nFCI : '');
2302
        $texto = $prod->getElementsByTagName("xProd")->item(0)->nodeValue . (strlen($tmp_ad)!=0?"\n    ".$tmp_ad:'');
2303
        //decodifica os caracteres html no xml
2304
        $texto = html_entity_decode($texto);
2305
        if ($this->descProdQuebraLinha) {
2306
            $texto = str_replace(";", "\n", $texto);
2307
        }
2308
        return $texto;
2309
    }
2310
2311
    /**
2312
     * itens
2313
     * Monta o campo de itens da DANFE (retrato e paisagem)
2314
     *
2315
     * @name   itens
2316
     * @param  float $x       Posição horizontal canto esquerdo
2317
     * @param  float $y       Posição vertical canto superior
2318
     * @param  float $nInicio Número do item inicial
2319
     * @param  float $max     Número do item final
2320
     * @param  float $hmax    Altura máxima do campo de itens em mm
2321
     * @return float Posição vertical final
2322
     */
2323
    protected function itens($x, $y, &$nInicio, $hmax, $pag = 0, $totpag = 0, $hCabecItens = 7)
2324
    {
2325
        $oldX = $x;
2326
        $oldY = $y;
2327
        $totItens = $this->det->length;
2328
        //#####################################################################
2329
        //DADOS DOS PRODUTOS / SERVIÇOS
2330
        $texto = "DADOS DOS PRODUTOS / SERVIÇOS ";
2331
        if ($this->orientacao == 'P') {
2332
            $w = $this->wPrint;
2333
        } else {
2334
            if ($nInicio < 2) { // primeira página
2335
                $w = $this->wPrint - $this->wCanhoto;
2336
            } else { // páginas seguintes
2337
                $w = $this->wPrint;
2338
            }
2339
        }
2340
        $h = 4;
2341
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
2342
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
2343
        $y += 3;
2344
        //desenha a caixa dos dados dos itens da NF
2345
        $hmax += 1;
2346
        $texto = '';
2347
        $this->pdf->textBox($x, $y, $w, $hmax);
2348
        //##################################################################################
2349
        // cabecalho LOOP COM OS DADOS DOS PRODUTOS
2350
        //CÓDIGO PRODUTO
2351
        $texto = "CÓDIGO PRODUTO";
2352
        $w1 = round($w*0.09, 0);
2353
        $h = 4;
2354
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2355
        $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2356
        $this->pdf->line($x+$w1, $y, $x+$w1, $y+$hmax);
2357
        //DESCRIÇÃO DO PRODUTO / SERVIÇO
2358
        $x += $w1;
2359
        $w2 = round($w*0.28, 0);
2360
        $texto = 'DESCRIÇÃO DO PRODUTO / SERVIÇO';
2361
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2362
        $this->pdf->textBox($x, $y, $w2, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2363
        $this->pdf->line($x+$w2, $y, $x+$w2, $y+$hmax);
2364
        //NCM/SH
2365
        $x += $w2;
2366
        $w3 = round($w*0.06, 0);
2367
        $texto = 'NCM/SH';
2368
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2369
        $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2370
        $this->pdf->line($x+$w3, $y, $x+$w3, $y+$hmax);
2371
        //O/CST ou O/CSOSN
2372
        $x += $w3;
2373
        $w4 = round($w*0.05, 0);
2374
        $texto = 'O/CSOSN';//Regime do Simples CRT = 1 ou CRT = 2
2375
        if ($this->getTagValue($this->emit, 'CRT') == '3') {
2376
             $texto = 'O/CST';//Regime Normal
2377
        }
2378
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2379
        $this->pdf->textBox($x, $y, $w4, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2380
        $this->pdf->line($x+$w4, $y, $x+$w4, $y+$hmax);
2381
        //CFOP
2382
        $x += $w4;
2383
        $w5 = round($w*0.04, 0);
2384
        $texto = 'CFOP';
2385
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2386
        $this->pdf->textBox($x, $y, $w5, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2387
        $this->pdf->line($x+$w5, $y, $x+$w5, $y+$hmax);
2388
        //UN
2389
        $x += $w5;
2390
        $w6 = round($w*0.03, 0);
2391
        $texto = 'UN';
2392
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2393
        $this->pdf->textBox($x, $y, $w6, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2394
        $this->pdf->line($x+$w6, $y, $x+$w6, $y+$hmax);
2395
        //QUANT
2396
        $x += $w6;
2397
        $w7 = round($w*0.07, 0);
2398
        $texto = 'QUANT';
2399
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2400
        $this->pdf->textBox($x, $y, $w7, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2401
        $this->pdf->line($x+$w7, $y, $x+$w7, $y+$hmax);
2402
        //VALOR UNIT
2403
        $x += $w7;
2404
        $w8 = round($w*0.06, 0);
2405
        $texto = 'VALOR UNIT';
2406
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2407
        $this->pdf->textBox($x, $y, $w8, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2408
        $this->pdf->line($x+$w8, $y, $x+$w8, $y+$hmax);
2409
        //VALOR TOTAL
2410
        $x += $w8;
2411
        $w9 = round($w*0.06, 0);
2412
        $texto = 'VALOR TOTAL';
2413
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2414
        $this->pdf->textBox($x, $y, $w9, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2415
        $this->pdf->line($x+$w9, $y, $x+$w9, $y+$hmax);
2416
        //B.CÁLC ICMS
2417
        $x += $w9;
2418
        $w10 = round($w*0.06, 0);
2419
        $texto = 'B.CÁLC ICMS';
2420
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2421
        $this->pdf->textBox($x, $y, $w10, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2422
        $this->pdf->line($x+$w10, $y, $x+$w10, $y+$hmax);
2423
        //VALOR ICMS
2424
        $x += $w10;
2425
        $w11 = round($w*0.06, 0);
2426
        $texto = 'VALOR ICMS';
2427
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2428
        $this->pdf->textBox($x, $y, $w11, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2429
        $this->pdf->line($x+$w11, $y, $x+$w11, $y+$hmax);
2430
        //VALOR IPI
2431
        $x += $w11;
2432
        $w12 = round($w*0.05, 0);
2433
        $texto = 'VALOR IPI';
2434
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2435
        $this->pdf->textBox($x, $y, $w12, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2436
        $this->pdf->line($x+$w12, $y, $x+$w12, $y+$hmax);
2437
        //ALÍQ. ICMS
2438
        $x += $w12;
2439
        $w13 = round($w*0.035, 0);
2440
        $texto = 'ALÍQ. ICMS';
2441
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2442
        $this->pdf->textBox($x, $y, $w13, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2443
        $this->pdf->line($x+$w13, $y, $x+$w13, $y+$hmax);
2444
        //ALÍQ. IPI
2445
        $x += $w13;
2446
        $w14 = $w-($w1+$w2+$w3+$w4+$w5+$w6+$w7+$w8+$w9+$w10+$w11+$w12+$w13);
2447
        $texto = 'ALÍQ. IPI';
2448
        $this->pdf->textBox($x, $y, $w14, $h, $texto, $aFont, 'C', 'C', 0, '', false);
2449
        $this->pdf->line($oldX, $y+$h+1, $oldX + $w, $y+$h+1);
2450
        $y += 5;
2451
        //##################################################################################
2452
        // LOOP COM OS DADOS DOS PRODUTOS
2453
        $i = 0;
2454
        $hUsado = $hCabecItens;
2455
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
2456
        foreach ($this->det as $d) {
2457
            if ($i >= $nInicio) {
2458
                $thisItem = $this->det->item($i);
2459
                //carrega as tags do item
2460
                $prod = $thisItem->getElementsByTagName("prod")->item(0);
2461
                $imposto = $this->det->item($i)->getElementsByTagName("imposto")->item(0);
2462
                $ICMS = $imposto->getElementsByTagName("ICMS")->item(0);
2463
                $IPI  = $imposto->getElementsByTagName("IPI")->item(0);
2464
                $textoProduto = trim($this->descricaoProduto($thisItem));
2465
2466
                $linhaDescr = $this->pdf->getNumLines($textoProduto, $w2, $aFont);
2467
                $h = round(($linhaDescr * $this->pdf->fontSize)+ ($linhaDescr * 0.5), 2);
2468
                $hUsado += $h;
2469
2470
                $diffH = $hmax - $hUsado;
2471
2472
                if ($pag != $totpag) {
2473
                    if (1 > $diffH && $i < $totItens) {
2474
                        //ultrapassa a capacidade para uma única página
2475
                        //o restante dos dados serão usados nas proximas paginas
2476
                        $nInicio = $i;
2477
                        break;
2478
                    }
2479
                }
2480
                $y_linha=$y+$h;
2481
                // linha entre itens
2482
                $this->pdf->dashedHLine($oldX, $y_linha, $w, 0.1, 120);
2483
                //corrige o x
2484
                $x=$oldX;
2485
                //codigo do produto
2486
                $texto = $prod->getElementsByTagName("cProd")->item(0)->nodeValue;
2487
                $this->pdf->textBox($x, $y, $w1, $h, $texto, $aFont, 'T', 'C', 0, '');
2488
                $x += $w1;
2489
                //DESCRIÇÃO
2490
                if ($this->orientacao == 'P') {
2491
                    $this->pdf->textBox($x, $y, $w2, $h, $textoProduto, $aFont, 'T', 'L', 0, '', false);
2492
                } else {
2493
                    $this->pdf->textBox($x, $y, $w2, $h, $textoProduto, $aFont, 'T', 'L', 0, '', false);
2494
                }
2495
                $x += $w2;
2496
                //NCM
2497
                $texto = ! empty($prod->getElementsByTagName("NCM")->item(0)->nodeValue) ?
2498
                        $prod->getElementsByTagName("NCM")->item(0)->nodeValue : '';
2499
                $this->pdf->textBox($x, $y, $w3, $h, $texto, $aFont, 'T', 'C', 0, '');
2500
                $x += $w3;
2501
                //CST
2502
                if (isset($ICMS)) {
2503
                    $origem =  $this->getTagValue($ICMS, "orig");
2504
                    $cst =  $this->getTagValue($ICMS, "CST");
2505
                    $csosn =  $this->getTagValue($ICMS, "CSOSN");
2506
                    $texto = $origem.$cst.$csosn;
2507
                    $this->pdf->textBox($x, $y, $w4, $h, $texto, $aFont, 'T', 'C', 0, '');
2508
                }
2509
                //CFOP
2510
                $x += $w4;
2511
                $texto = $prod->getElementsByTagName("CFOP")->item(0)->nodeValue;
2512
                $this->pdf->textBox($x, $y, $w5, $h, $texto, $aFont, 'T', 'C', 0, '');
2513
                //Unidade
2514
                $x += $w5;
2515
                $texto = $prod->getElementsByTagName("uCom")->item(0)->nodeValue;
2516
                $this->pdf->textBox($x, $y, $w6, $h, $texto, $aFont, 'T', 'C', 0, '');
2517
                $x += $w6;
2518
                if ($this->orientacao == 'P') {
2519
                    $alinhamento = 'R';
2520
                } else {
2521
                    $alinhamento = 'R';
2522
                }
2523
                // QTDADE
2524
                $texto = number_format($prod->getElementsByTagName("qCom")->item(0)->nodeValue, 4, ",", ".");
2525
                $this->pdf->textBox($x, $y, $w7, $h, $texto, $aFont, 'T', $alinhamento, 0, '');
2526
                $x += $w7;
2527
                // Valor Unitário
2528
                $texto = number_format($prod->getElementsByTagName("vUnCom")->item(0)->nodeValue, 4, ",", ".");
2529
                $this->pdf->textBox($x, $y, $w8, $h, $texto, $aFont, 'T', $alinhamento, 0, '');
2530
                $x += $w8;
2531
                // Valor do Produto
2532
                $texto = "";
2533
                if (is_numeric($prod->getElementsByTagName("vProd")->item(0)->nodeValue)) {
2534
                    $texto = number_format($prod->getElementsByTagName("vProd")->item(0)->nodeValue, 2, ",", ".");
2535
                }
2536
                $this->pdf->textBox($x, $y, $w9, $h, $texto, $aFont, 'T', $alinhamento, 0, '');
2537
                //Valor da Base de calculo
2538
                $x += $w9;
2539
                if (isset($ICMS)) {
2540
                    $texto = ! empty($ICMS->getElementsByTagName("vBC")->item(0)->nodeValue) ?
2541
                            number_format(
2542
                                $ICMS->getElementsByTagName("vBC")->item(0)->nodeValue,
2543
                                2,
2544
                                ",",
2545
                                "."
2546
                            ) : '0, 00';
2547
                    $this->pdf->textBox($x, $y, $w10, $h, $texto, $aFont, 'T', $alinhamento, 0, '');
2548
                }
2549
                //Valor do ICMS
2550
                $x += $w10;
2551
                if (isset($ICMS)) {
2552
                    $texto = ! empty($ICMS->getElementsByTagName("vICMS")->item(0)->nodeValue) ?
2553
                            number_format(
2554
                                $ICMS->getElementsByTagName("vICMS")->item(0)->nodeValue,
2555
                                2,
2556
                                ",",
2557
                                "."
2558
                            ) : '0, 00';
2559
                    $this->pdf->textBox($x, $y, $w11, $h, $texto, $aFont, 'T', $alinhamento, 0, '');
2560
                }
2561
                //Valor do IPI
2562
                $x += $w11;
2563
                if (isset($IPI)) {
2564
                    $texto = ! empty($IPI->getElementsByTagName("vIPI")->item(0)->nodeValue) ?
2565
                            number_format($IPI->getElementsByTagName("vIPI")->item(0)->nodeValue, 2, ",", ".") :'';
2566
                } else {
2567
                    $texto = '';
2568
                }
2569
                $this->pdf->textBox($x, $y, $w12, $h, $texto, $aFont, 'T', $alinhamento, 0, '');
2570
                // %ICMS
2571
                $x += $w12;
2572
                if (isset($ICMS)) {
2573
                    $texto = ! empty($ICMS->getElementsByTagName("pICMS")->item(0)->nodeValue) ?
2574
                            number_format(
2575
                                $ICMS->getElementsByTagName("pICMS")->item(0)->nodeValue,
2576
                                2,
2577
                                ",",
2578
                                "."
2579
                            ) : '0, 00';
2580
                    $this->pdf->textBox($x, $y, $w13, $h, $texto, $aFont, 'T', 'C', 0, '');
2581
                }
2582
                //%IPI
2583
                $x += $w13;
2584
                if (isset($IPI)) {
2585
                    $texto = ! empty($IPI->getElementsByTagName("pIPI")->item(0)->nodeValue) ?
2586
                            number_format($IPI->getElementsByTagName("pIPI")->item(0)->nodeValue, 2, ",", ".") : '';
2587
                } else {
2588
                    $texto = '';
2589
                }
2590
                $this->pdf->textBox($x, $y, $w14, $h, $texto, $aFont, 'T', 'C', 0, '');
2591
2592
2593
                // Dados do Veiculo Somente para veiculo 0 Km
2594
                $veicProd = $prod->getElementsByTagName("veicProd")->item(0);
2595
                // Tag somente é gerada para veiculo 0k, e só é permitido um veiculo por NF-e por conta do detran
2596
                // Verifica se a Tag existe
2597
                if (!empty($veicProd)) {
2598
                    $this->dadosItenVeiculoDANFE($oldX, $y, $nInicio, $h, $prod);
2599
                }
2600
2601
2602
                $y += $h;
2603
                $i++;
2604
                //incrementa o controle dos itens processados.
2605
                $this->qtdeItensProc++;
2606
            } else {
2607
                $i++;
2608
            }
2609
        }
2610
        return $oldY+$hmax;
2611
    }
2612
2613
2614
    /**
2615
     * dadosItenVeiculoDANFE
2616
     * Coloca os dados do veiculo abaixo do item da NFe. (retrato e paisagem)
2617
     *
2618
     * @param float  $x    Posição horizontal
2619
     *                     canto esquerdo
2620
     * @param float  $y    Posição vertical
2621
     *                     canto superior
2622
     * @param        $nInicio
2623
     * @param float  $h    altura do campo
2624
     * @param object $prod Contendo todos os dados do item
2625
     */
2626
2627
    protected function dadosItenVeiculoDANFE($x, $y, &$nInicio, $h, $prod)
2628
    {
2629
        $oldX = $x;
2630
        $oldY = $y;
2631
2632
        if ($this->orientacao == 'P') {
2633
            $w = $this->wPrint;
2634
        } else {
2635
            if ($nInicio < 2) { // primeira página
2636
                $w = $this->wPrint - $this->wCanhoto;
2637
            } else { // páginas seguintes
2638
                $w = $this->wPrint;
2639
            }
2640
        }
2641
2642
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
2643
2644
        $w1 = round($w*0.09, 0);
2645
2646
        // Tabela Renavam Combustivel
2647
        $renavamCombustivel = [
2648
            1=>'ALCOOL',
2649
            2=>'GASOLINA',
2650
            3=>'DIESEL',
2651
            4=>'GASOGENIO',
2652
            5=>'GAS METANO',
2653
            6=>'ELETRICO/FONTE INTERNA',
2654
            7=>'ELETRICO/FONTE EXTERNA',
2655
            8=>'GASOL/GAS NATURAL COMBUSTIVEL',
2656
            9=>'ALCOOL/GAS NATURAL COMBUSTIVEL',
2657
            10=>'DIESEL/GAS NATURAL COMBUSTIVEL',
2658
            11=>'VIDE/CAMPO/OBSERVACAO',
2659
            12=>'ALCOOL/GAS NATURAL VEICULAR',
2660
            13=>'GASOLINA/GAS NATURAL VEICULAR',
2661
            14=>'DIESEL/GAS NATURAL VEICULAR',
2662
            15=>'GAS NATURAL VEICULAR',
2663
            16=>'ALCOOL/GASOLINA',
2664
            17=>'GASOLINA/ALCOOL/GAS NATURAL',
2665
            18=>'GASOLINA/ELETRICO'
2666
        ];
2667
2668
        $renavamEspecie = [
2669
            1=>'PASSAGEIRO',
2670
            2=>'CARGA',
2671
            3=>'MISTO',
2672
            4=>'CORRIDA',
2673
            5=>'TRACAO',
2674
            6=>'ESPECIAL',
2675
            7=>'COLECAO'
2676
        ];
2677
2678
        $renavamTiposVeiculos = [
2679
            1=>'BICICLETA',
2680
            2=>'CICLOMOTOR',
2681
            3=>'MOTONETA',
2682
            4=>'MOTOCICLETA',
2683
            5=>'TRICICLO',
2684
            6=>'AUTOMOVEL',
2685
            7=>'MICROONIBUS',
2686
            8=>'ONIBUS',
2687
            9=>'BONDE',
2688
            10=>'REBOQUE',
2689
            11=>'SEMI-REBOQUE',
2690
            12=>'CHARRETE',
2691
            13=>'CAMIONETA',
2692
            14=>'CAMINHAO',
2693
            15=>'CARROCA',
2694
            16=>'CARRO DE MAO',
2695
            17=>'CAMINHAO TRATOR',
2696
            18=>'TRATOR DE RODAS',
2697
            19=>'TRATOR DE ESTEIRAS',
2698
            20=>'TRATOR MISTO',
2699
            21=>'QUADRICICLO',
2700
            22=>'CHASSI/PLATAFORMA',
2701
            23=>'CAMINHONETE',
2702
            24=>'SIDE-CAR',
2703
            25=>'UTILITARIO',
2704
            26=>'MOTOR-CASA'
2705
        ];
2706
2707
        $renavamTipoPintura = [
2708
            'F'=>'FOSCA',
2709
            'S'=>'SÓLIDA',
2710
            'P'=>'PEROLIZADA',
2711
            'M'=>'METALICA',
2712
        ];
2713
2714
        $veicProd = $prod->getElementsByTagName("veicProd")->item(0);
2715
2716
        $veiculoChassi = $veicProd->getElementsByTagName("chassi")->item(0)->nodeValue;
2717
        $veiculoCor = $veicProd->getElementsByTagName("xCor")->item(0)->nodeValue;
2718
        $veiculoCilindrada = $veicProd->getElementsByTagName("cilin")->item(0)->nodeValue;
2719
        $veiculoCmkg = $veicProd->getElementsByTagName("CMT")->item(0)->nodeValue;
2720
        $veiculoTipo = $veicProd->getElementsByTagName("tpVeic")->item(0)->nodeValue;
2721
2722
        $veiculoMotor = $veicProd->getElementsByTagName("nMotor")->item(0)->nodeValue;
2723
        $veiculoRenavam = $veicProd->getElementsByTagName("cMod")->item(0)->nodeValue;
2724
        $veiculoHp = $veicProd->getElementsByTagName("pot")->item(0)->nodeValue;
2725
        $veiculoPlaca = ''; //$veiculo->getElementsByTagName("CMT")->item(0)->nodeValue;
2726
        $veiculoTipoPintura = $veicProd->getElementsByTagName("tpPint")->item(0)->nodeValue;
2727
        $veiculoMarcaModelo = $prod->getElementsByTagName("xProd")->item(0)->nodeValue;
2728
        $veiculoEspecie = $veicProd->getElementsByTagName("espVeic")->item(0)->nodeValue;
2729
        $veiculoCombustivel = $veicProd->getElementsByTagName("tpComb")->item(0)->nodeValue;
2730
        $veiculoSerial = $veicProd->getElementsByTagName("nSerie")->item(0)->nodeValue;
2731
        $veiculoFabricacao = $veicProd->getElementsByTagName("anoFab")->item(0)->nodeValue;
2732
        $veiculoModelo = $veicProd->getElementsByTagName("anoMod")->item(0)->nodeValue;
2733
        $veiculoDistancia = $veicProd->getElementsByTagName("dist")->item(0)->nodeValue;
2734
2735
        $x = $oldX;
2736
2737
        $yVeic = $y + $h;
2738
        $texto = 'Chassi: ............: ' . $veiculoChassi;
2739
        $this->pdf->textBox($x, $yVeic, $w1+40, $h, $texto, $aFont, 'T', 'L', 0, '');
2740
        $yVeic += $h;
2741
        $texto = 'Cor...................: ' . $veiculoCor;
2742
        $this->pdf->textBox($x, $yVeic, $w1+40, $h, $texto, $aFont, 'T', 'L', 0, '');
2743
        $yVeic += $h;
2744
        $texto = 'Cilindrada........: ' . $veiculoCilindrada;
2745
        $this->pdf->textBox($x, $yVeic, $w1+40, $h, $texto, $aFont, 'T', 'L', 0, '');
2746
        $yVeic += $h;
2747
        $texto = 'Cmkg...............: ' . $veiculoCmkg;
2748
        $this->pdf->textBox($x, $yVeic, $w1+40, $h, $texto, $aFont, 'T', 'L', 0, '');
2749
        $yVeic += $h;
2750
        $texto = 'Tipo.................: ' . ($renavamTiposVeiculos[intval($veiculoTipo)] ?? $veiculoTipo);
2751
         $this->pdf->textBox($x, $yVeic, $w1+40, $h, $texto, $aFont, 'T', 'L', 0, '');
2752
        $yVeic = $y + $h;
2753
        $xVeic = $x + 65;
2754
        $texto = 'Nº Motor: .........: ' . $veiculoMotor;
2755
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2756
        $yVeic += $h;
2757
        $texto = 'Renavam...........: ' . $veiculoRenavam;
2758
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2759
        $yVeic += $h;
2760
        $texto = 'HP.....................: ' . $veiculoHp;
2761
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2762
        $yVeic += $h;
2763
        $texto = 'Placa.................: ' . $veiculoPlaca;
2764
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2765
        $yVeic += $h;
2766
        $texto = 'Tipo Pintura......: ' . ($renavamEspecie[intval($veiculoTipoPintura)] ?? $veiculoTipoPintura);
2767
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2768
        $yVeic = $y + $h;
2769
        $xVeic = $xVeic + 55;
2770
        $texto = 'Marca / Modelo.....: ' . $veiculoMarcaModelo;
2771
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2772
        $yVeic += $h;
2773
        $texto = 'Especie..................: ' . ($renavamEspecie[intval($veiculoEspecie)] ?? $veiculoEspecie);
2774
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2775
        $yVeic += $h;
2776
        $texto = 'Combustivel..........: ' . ($renavamCombustivel[intval($veiculoCombustivel)] ?? $veiculoCombustivel);
2777
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2778
        $yVeic += $h;
2779
        $texto = 'Serial.....................: ' . $veiculoSerial;
2780
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2781
        $yVeic += $h;
2782
        $texto = 'Ano Fab/Mod........: '. $veiculoFabricacao . '/' . $veiculoModelo;
2783
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2784
        $yVeic += $h;
2785
        $texto = 'Distancia Entre Eixos(mm)..: '. $veiculoDistancia;
2786
        $this->pdf->textBox($xVeic, $yVeic, $w1+50, $h, $texto, $aFont, 'T', 'L', 0, '');
2787
    }
2788
2789
    /**
2790
     * issqn
2791
     * Monta o campo de serviços do DANFE
2792
     *
2793
     * @name   issqn (retrato e paisagem)
2794
     * @param  float $x Posição horizontal canto esquerdo
2795
     * @param  float $y Posição vertical canto superior
2796
     * @return float Posição vertical final
2797
     */
2798
    protected function issqn($x, $y)
2799
    {
2800
        $oldX = $x;
2801
        //#####################################################################
2802
        //CÁLCULO DO ISSQN
2803
        $texto = "CÁLCULO DO ISSQN";
2804
        $w = $this->wPrint;
2805
        $h = 7;
2806
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
2807
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 0, '');
2808
        //INSCRIÇÃO MUNICIPAL
2809
        $y += 3;
2810
        $w = round($this->wPrint*0.23, 0);
2811
        $texto = 'INSCRIÇÃO MUNICIPAL';
2812
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2813
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2814
        //inscrição municipal
2815
        $texto = ! empty($this->emit->getElementsByTagName("IM")->item(0)->nodeValue) ?
2816
                $this->emit->getElementsByTagName("IM")->item(0)->nodeValue : '';
2817
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2818
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'L', 0, '');
2819
        //VALOR TOTAL DOS SERVIÇOS
2820
        $x += $w;
2821
        $texto = 'VALOR TOTAL DOS SERVIÇOS';
2822
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2823
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2824
        if (isset($this->ISSQNtot)) {
2825
            $texto = ! empty($this->ISSQNtot->getElementsByTagName("vServ")->item(0)->nodeValue) ?
2826
                    $this->ISSQNtot->getElementsByTagName("vServ")->item(0)->nodeValue : '';
2827
            $texto = number_format($texto, 2, ",", ".");
2828
        } else {
2829
            $texto = '';
2830
        }
2831
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2832
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'R', 0, '');
2833
        //BASE DE CÁLCULO DO ISSQN
2834
        $x += $w;
2835
        $texto = 'BASE DE CÁLCULO DO ISSQN';
2836
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2837
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2838
        if (isset($this->ISSQNtot)) {
2839
            $texto = ! empty($this->ISSQNtot->getElementsByTagName("vBC")->item(0)->nodeValue) ?
2840
                    $this->ISSQNtot->getElementsByTagName("vBC")->item(0)->nodeValue : '';
2841
            $texto = ! empty($texto) ? number_format($texto, 2, ",", ".") : '';
2842
        } else {
2843
            $texto = '';
2844
        }
2845
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2846
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'R', 0, '');
2847
        //VALOR TOTAL DO ISSQN
2848
        $x += $w;
2849
        if ($this->orientacao == 'P') {
2850
            $w = $this->wPrint - (3 * $w);
2851
        } else {
2852
            $w = $this->wPrint - (3 * $w)-$this->wCanhoto;
2853
        }
2854
        $texto = 'VALOR TOTAL DO ISSQN';
2855
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
2856
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2857
        if (isset($this->ISSQNtot)) {
2858
            $texto = ! empty($this->ISSQNtot->getElementsByTagName("vISS")->item(0)->nodeValue) ?
2859
                    $this->ISSQNtot->getElementsByTagName("vISS")->item(0)->nodeValue : '';
2860
            $texto = ! empty($texto) ? number_format($texto, 2, ",", ".") : '';
2861
        } else {
2862
            $texto = '';
2863
        }
2864
        $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
2865
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'B', 'R', 0, '');
2866
        return ($y+$h+1);
2867
    }
2868
2869
    /**
2870
     *dadosAdicionais
2871
     * Coloca o grupo de dados adicionais da NFe. (retrato e paisagem)
2872
     *
2873
     * @name   dadosAdicionais
2874
     * @param  float $x Posição horizontal canto esquerdo
2875
     * @param  float $y Posição vertical canto superior
2876
     * @param  float $h altura do campo
2877
     * @return float Posição vertical final (eixo Y)
2878
     */
2879
    protected function dadosAdicionais($x, $y, $h)
2880
    {
2881
        //##################################################################################
2882
        //DADOS ADICIONAIS
2883
        $texto = "DADOS ADICIONAIS";
2884
        if ($this->orientacao == 'P') {
2885
              $w = $this->wPrint;
2886
        } else {
2887
              $w = $this->wPrint-$this->wCanhoto;
2888
        }
2889
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>'B'];
2890
        $this->pdf->textBox($x, $y, $w, 8, $texto, $aFont, 'T', 'L', 0, '');
2891
        //INFORMAÇÕES COMPLEMENTARES
2892
        $texto = "INFORMAÇÕES COMPLEMENTARES";
2893
        $y += 3;
2894
        $w = $this->wAdic;
2895
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>'B'];
2896
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2897
        //o texto com os dados adicionais foi obtido na função montaDANFE
2898
        //e carregado em uma propriedade privada da classe
2899
        //$this->wAdic com a largura do campo
2900
        //$this->textoAdic com o texto completo do campo
2901
        $y += 1;
2902
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
2903
        $this->pdf->textBox($x, $y+2, $w-2, $h-3, $this->textoAdic, $aFont, 'T', 'L', 0, '', false);
2904
        //RESERVADO AO FISCO
2905
        $texto = "RESERVADO AO FISCO";
2906
        $x += $w;
2907
        $y -= 1;
2908
        if ($this->orientacao == 'P') {
2909
            $w = $this->wPrint-$w;
2910
        } else {
2911
            $w = $this->wPrint-$w-$this->wCanhoto;
2912
        }
2913
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>'B'];
2914
        $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'T', 'L', 1, '');
2915
        //inserir texto informando caso de contingência
2916
        // 1 - Normal - emissão normal;
2917
        // 2 - Contingência FS - emissão em contingência com impressão do DANFE em Formulário de Segurança;
2918
        // 3 - Contingência SCAN - emissão em contingência no Sistema de Contingência do Ambiente Nacional;
2919
        // 4 - Contingência DPEC - emissão em contingência com envio da Declaração
2920
        //     Prévia de Emissão em Contingência;
2921
        // 5 - Contingência FS-DA - emissão em contingência com impressão do DANFE em Formulário de
2922
        //     Segurança para Impressão de Documento Auxiliar de Documento Fiscal Eletrônico (FS-DA);
2923
        // 6 - Contingência SVC-AN
2924
        // 7 - Contingência SVC-RS
2925
        $xJust = $this->getTagValue($this->ide, 'xJust', 'Justificativa: ');
2926
        $dhCont = $this->getTagValue($this->ide, 'dhCont', ' Entrada em contingência : ');
2927
        $texto = '';
2928
        switch ($this->tpEmis) {
2929
            case 2:
2930
                $texto = 'CONTINGÊNCIA FS' . $dhCont . $xJust;
2931
                break;
2932
            case 3:
2933
                $texto = 'CONTINGÊNCIA SCAN' . $dhCont . $xJust;
2934
                break;
2935
            case 4:
2936
                $texto = 'CONTINGÊNCIA DPEC' . $dhCont . $xJust;
2937
                break;
2938
            case 5:
2939
                $texto = 'CONTINGÊNCIA FSDA' . $dhCont . $xJust;
2940
                break;
2941
            case 6:
2942
                $texto = 'CONTINGÊNCIA SVC-AN' . $dhCont . $xJust;
2943
                break;
2944
            case 7:
2945
                $texto = 'CONTINGÊNCIA SVC-RS' . $dhCont . $xJust;
2946
                break;
2947
        }
2948
        $y += 2;
2949
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
2950
        $this->pdf->textBox($x, $y, $w-2, $h-3, $texto, $aFont, 'T', 'L', 0, '', false);
2951
        return $y+$h;
2952
    }
2953
2954
    /**
2955
     * rodape
2956
     * Monta o rodapé no final da DANFE com a data/hora de impressão e informações
2957
     * sobre a API NfePHP
2958
     *
2959
     * @param  float $x  Posição horizontal canto esquerdo
2960
     *
2961
     * @return void
2962
     */
2963
    protected function rodape($x)
2964
    {
2965
        
2966
        $y = $this->maxH - 4;
2967
        if ($this->orientacao == 'P') {
2968
              $w = $this->wPrint;
2969
        } else {
2970
              $w = $this->wPrint-$this->wCanhoto;
2971
              $x = $this->wCanhoto;
2972
        }
2973
        $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>'I'];
2974
        $texto = "Impresso em ". date('d/m/Y') . " as " . date('H:i:s');
2975
        $this->pdf->textBox($x, $y, $w, 0, $texto, $aFont, 'T', 'L', false);
2976
        $texto = $this->creditos .  "  Powered by NFePHP®";
2977
        $this->pdf->textBox($x, $y, $w, 0, $texto, $aFont, 'T', 'R', false, '');
2978
    }
2979
2980
    /**
2981
     * pCcanhotoDANFE
2982
     * Monta o canhoto da DANFE (retrato e paisagem)
2983
     *
2984
     * @name   canhotoDANFE
2985
     * @param  number $x Posição horizontal canto esquerdo
2986
     * @param  number $y Posição vertical canto superior
2987
     * @return number Posição vertical final
2988
     *
2989
     * TODO 21/07/14 fmertins: quando orientação L-paisagem, o canhoto está sendo gerado incorretamente
2990
     */
2991
    protected function canhoto($x, $y)
2992
    {
2993
        $oldX = $x;
2994
        $oldY = $y;
2995
        //#################################################################################
2996
        //canhoto
2997
        //identificação do tipo de nf entrada ou saida
2998
        $tpNF = $this->ide->getElementsByTagName('tpNF')->item(0)->nodeValue;
2999
        if ($tpNF == '0') {
3000
            //NFe de Entrada
3001
            $emitente = '';
3002
            $emitente .= $this->dest->getElementsByTagName("xNome")->item(0)->nodeValue . " - ";
3003
            $emitente .= $this->enderDest->getElementsByTagName("xLgr")->item(0)->nodeValue . ", ";
3004
            $emitente .= $this->enderDest->getElementsByTagName("nro")->item(0)->nodeValue . " - ";
3005
            $emitente .= $this->getTagValue($this->enderDest, "xCpl", " - ", " ");
3006
            $emitente .= $this->enderDest->getElementsByTagName("xBairro")->item(0)->nodeValue . " ";
3007
            $emitente .= $this->enderDest->getElementsByTagName("xMun")->item(0)->nodeValue . "-";
3008
            $emitente .= $this->enderDest->getElementsByTagName("UF")->item(0)->nodeValue . "";
3009
            $destinatario = $this->emit->getElementsByTagName("xNome")->item(0)->nodeValue . " ";
3010
        } else {
3011
            //NFe de Saída
3012
            $emitente = $this->emit->getElementsByTagName("xNome")->item(0)->nodeValue . " ";
3013
            $destinatario = '';
3014
            $destinatario .= $this->dest->getElementsByTagName("xNome")->item(0)->nodeValue . " - ";
3015
            $destinatario .= $this->enderDest->getElementsByTagName("xLgr")->item(0)->nodeValue . ", ";
3016
            $destinatario .= $this->enderDest->getElementsByTagName("nro")->item(0)->nodeValue . " ";
3017
            $destinatario .= $this->getTagValue($this->enderDest, "xCpl", " - ", " ");
3018
            $destinatario .= $this->enderDest->getElementsByTagName("xBairro")->item(0)->nodeValue . " ";
3019
            $destinatario .= $this->enderDest->getElementsByTagName("xMun")->item(0)->nodeValue . "-";
3020
            $destinatario .= $this->enderDest->getElementsByTagName("UF")->item(0)->nodeValue . " ";
3021
        }
3022
        //identificação do sistema emissor
3023
        //linha separadora do canhoto
3024
        if ($this->orientacao == 'P') {
3025
            $w = round($this->wPrint * 0.81, 0);
3026
        } else {
3027
            //linha separadora do canhoto - 238
3028
            //posicao altura
3029
            $y = $this->wPrint-85;
3030
            //altura
3031
            $w = $this->wPrint-85-24;
3032
        }
3033
        $h = 10;
3034
        //desenha caixa
3035
        $texto = '';
3036
        $aFont = ['font'=>$this->fontePadrao, 'size'=>7, 'style'=>''];
3037
        $aFontSmall = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
3038
        if ($this->orientacao == 'P') {
3039
            $this->pdf->textBox($x, $y, $w, $h, $texto, $aFont, 'C', 'L', 1, '', false);
3040
        } else {
3041
            $this->pdf->textBox90($x, $y, $w, $h, $texto, $aFont, 'C', 'L', 1, '', false);
3042
        }
3043
        $numNF = str_pad($this->ide->getElementsByTagName('nNF')->item(0)->nodeValue, 9, "0", STR_PAD_LEFT);
3044
        $serie = str_pad($this->ide->getElementsByTagName('serie')->item(0)->nodeValue, 3, "0", STR_PAD_LEFT);
3045
        $texto = "RECEBEMOS DE ";
3046
        $texto .= $emitente;
3047
        $texto .= " OS PRODUTOS E/OU SERVIÇOS CONSTANTES DA NOTA FISCAL ELETRÔNICA INDICADA ";
3048
        if ($this->orientacao == 'P') {
3049
            $texto .= "ABAIXO";
3050
        } else {
3051
            $texto .= "AO LADO";
3052
        }
3053
        $texto .= ". EMISSÃO: ";
3054
        $dEmi = ! empty($this->ide->getElementsByTagName("dEmi")->item(0)->nodeValue) ?
3055
                $this->ide->getElementsByTagName("dEmi")->item(0)->nodeValue : '';
3056
        if ($dEmi == '') {
3057
            $dEmi = ! empty($this->ide->getElementsByTagName("dhEmi")->item(0)->nodeValue) ?
3058
                    $this->ide->getElementsByTagName("dhEmi")->item(0)->nodeValue : '';
3059
            $aDemi = explode('T', $dEmi);
3060
            $dEmi = $aDemi[0];
3061
        }
3062
        $texto .= $this->ymdTodmy($dEmi) ." ";
3063
        $texto .= "VALOR TOTAL: R$ ";
3064
        $texto .= number_format($this->ICMSTot->getElementsByTagName("vNF")->item(0)->nodeValue, 2, ",", ".") . " ";
3065
        $texto .= "DESTINATÁRIO: ";
3066
        $texto .= $destinatario;
3067
        if ($this->orientacao == 'P') {
3068
            $this->pdf->textBox($x, $y, $w-1, $h, $texto, $aFont, 'C', 'L', 0, '', false);
3069
            $x1 = $x + $w;
3070
            $w1 = $this->wPrint - $w;
3071
            $texto = "NF-e";
3072
            $aFont = ['font'=>$this->fontePadrao, 'size'=>14, 'style'=>'B'];
3073
            $this->pdf->textBox($x1, $y, $w1, 18, $texto, $aFont, 'T', 'C', 0, '');
3074
            $texto = "Nº. " . $this->formatField($numNF, "###.###.###") . " \n";
3075
            $texto .= "Série $serie";
3076
            $aFont = ['font'=>$this->fontePadrao, 'size'=>10, 'style'=>'B'];
3077
            $this->pdf->textBox($x1, $y, $w1, 18, $texto, $aFont, 'C', 'C', 1, '');
3078
            //DATA DE RECEBIMENTO
3079
            $texto = "DATA DE RECEBIMENTO";
3080
            $y += $h;
3081
            $w2 = round($this->wPrint*0.17, 0); //35;
3082
            $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
3083
            $this->pdf->textBox($x, $y, $w2, 8, $texto, $aFont, 'T', 'L', 1, '');
3084
            //IDENTIFICAÇÃO E ASSINATURA DO RECEBEDOR
3085
            $x += $w2;
3086
            $w3 = $w-$w2;
3087
            $texto = "IDENTIFICAÇÃO E ASSINATURA DO RECEBEDOR";
3088
            $this->pdf->textBox($x, $y, $w3, 8, $texto, $aFont, 'T', 'L', 1, '');
3089
            $x = $oldX;
3090
            $y += 9;
3091
            $this->pdf->dashedHLine($x, $y, $this->wPrint, 0.1, 80);
3092
            $y += 2;
3093
            return $y;
3094
        } else {
3095
            $x--;
3096
            $x = $this->pdf->textBox90($x, $y, $w-1, $h, $texto, $aFontSmall, 'C', 'L', 0, '', false);
3097
            //NUMERO DA NOTA FISCAL LOGO NFE
3098
            $w1 = 18;
3099
            $x1 = $oldX;
3100
            $y = $oldY;
3101
            $texto = "NF-e";
3102
            $aFont = ['font'=>$this->fontePadrao, 'size'=>14, 'style'=>'B'];
3103
            $this->pdf->textBox($x1, $y, $w1, 18, $texto, $aFont, 'T', 'C', 0, '');
3104
            $texto = "Nº.\n" . $this->formatField($numNF, "###.###.###") . " \n";
3105
            $texto .= "Série $serie";
3106
            $aFont = ['font'=>$this->fontePadrao, 'size'=>8, 'style'=>'B'];
3107
            $this->pdf->textBox($x1, $y, $w1, 18, $texto, $aFont, 'C', 'C', 1, '');
3108
            //DATA DO RECEBIMENTO
3109
            $texto = "DATA DO RECEBIMENTO";
3110
            $y = $this->wPrint-85;
3111
            $x = 12;
3112
            $w2 = round($this->wPrint*0.17, 0); //35;
3113
            $aFont = ['font'=>$this->fontePadrao, 'size'=>6, 'style'=>''];
3114
            $this->pdf->textBox90($x, $y, $w2, 8, $texto, $aFont, 'T', 'L', 1, '');
3115
            //IDENTIFICAÇÃO E ASSINATURA DO RECEBEDOR
3116
            $y -= $w2;
3117
            $w3 = $w-$w2;
3118
            $texto = "IDENTIFICAÇÃO E ASSINATURA DO RECEBEDOR";
3119
            $aFont = ['font'=>$this->fontePadrao, 'size'=>5.7, 'style'=>''];
3120
            $x = $this->pdf->textBox90($x, $y, $w3, 8, $texto, $aFont, 'T', 'L', 1, '');
3121
            $this->pdf->DashedVLine(23, $oldY, 0.1, $this->wPrint-20, 67);
3122
            return $x;
3123
        }
3124
    }
3125
3126
    /**
3127
     * geraInformacoesDaTagCompra
3128
     * Devolve uma string contendo informação sobre as tag <compra><xNEmp>, <xPed> e <xCont> ou string vazia.
3129
     * Aviso: Esta função não leva em consideração dados na tag xPed do item.
3130
     *
3131
     * @name   pGeraInformacoesDaTagCompra
3132
     * @return string com as informacoes dos pedidos.
3133
     */
3134
    protected function geraInformacoesDaTagCompra()
3135
    {
3136
        $saida = "";
3137
        if (isset($this->compra)) {
3138
            if (! empty($this->compra->getElementsByTagName("xNEmp")->item(0)->nodeValue)) {
3139
                $saida .= " Nota de Empenho: " . $this->compra->getElementsByTagName("xNEmp")->item(0)->nodeValue;
3140
            }
3141
            if (! empty($this->compra->getElementsByTagName("xPed")->item(0)->nodeValue)) {
3142
                $saida .= " Pedido: " . $this->compra->getElementsByTagName("xPed")->item(0)->nodeValue;
3143
            }
3144
            if (! empty($this->compra->getElementsByTagName("xCont")->item(0)->nodeValue)) {
3145
                $saida .= " Contrato: " . $this->compra->getElementsByTagName("xCont")->item(0)->nodeValue;
3146
            }
3147
        }
3148
        return $saida;
3149
    }
3150
3151
    /**
3152
     * geraChaveAdicionalDeContingencia
3153
     *
3154
     * @name   geraChaveAdicionalDeContingencia
3155
     * @return string chave
3156
     */
3157
    protected function geraChaveAdicionalDeContingencia()
3158
    {
3159
        //cUF tpEmis CNPJ vNF ICMSp ICMSs DD  DV
3160
        // Quantidade de caracteres  02   01      14  14    01    01  02 01
3161
        $forma  = "%02d%d%s%014d%01d%01d%02d";
3162
        $cUF    = $this->ide->getElementsByTagName('cUF')->item(0)->nodeValue;
3163
        $CNPJ   = "00000000000000" . $this->emit->getElementsByTagName('CNPJ')->item(0)->nodeValue;
3164
        $CNPJ   = substr($CNPJ, -14);
3165
        $vNF    = $this->ICMSTot->getElementsByTagName("vNF")->item(0)->nodeValue * 100;
3166
        $vICMS  = $this->ICMSTot->getElementsByTagName("vICMS")->item(0)->nodeValue;
3167
        if ($vICMS > 0) {
3168
            $vICMS = 1;
3169
        }
3170
        $icmss  = $this->ICMSTot->getElementsByTagName("vBC")->item(0)->nodeValue;
3171
        if ($icmss > 0) {
3172
            $icmss = 1;
3173
        }
3174
        $dEmi = ! empty($this->ide->getElementsByTagName("dEmi")->item(0)->nodeValue) ?
3175
                $this->ide->getElementsByTagName("dEmi")->item(0)->nodeValue : '';
3176
        if ($dEmi == '') {
3177
            $dEmi = ! empty($this->ide->getElementsByTagName("dhEmi")->item(0)->nodeValue) ?
3178
                    $this->ide->getElementsByTagName("dhEmi")->item(0)->nodeValue : '';
3179
            $aDemi = explode('T', $dEmi);
3180
            $dEmi = $aDemi[0];
3181
        }
3182
        $dd  = $dEmi;
3183
        $rpos = strrpos($dd, '-');
3184
        $dd  = substr($dd, $rpos +1);
3185
        $chave = sprintf($forma, $cUF, $this->tpEmis, $CNPJ, $vNF, $vICMS, $icmss, $dd);
3186
        $chave = $chave . $this->modulo11($chave);
3187
        return $chave;
3188
    }
3189
3190
    /**
3191
     *  geraInformacoesDasNotasReferenciadas
3192
     * Devolve uma string contendo informação sobre as notas referenciadas. Suporta N notas, eletrônicas ou não
3193
     * Exemplo: NFe Ref.: série: 01 número: 01 emit: 11.111.111/0001-01
3194
     * em 10/2010 [0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000]
3195
     *
3196
     * @return string Informacoes a serem adicionadas no rodapé sobre notas referenciadas.
3197
     */
3198
    protected function geraInformacoesDasNotasReferenciadas()
3199
    {
3200
        $formaNfeRef = "\r\nNFe Ref.: série:%d número:%d emit:%s em %s [%s]";
3201
        $formaCTeRef = "\r\nCTe Ref.: série:%d número:%d emit:%s em %s [%s]";
3202
        $formaNfRef = "\r\nNF  Ref.: série:%d numero:%d emit:%s em %s modelo: %d";
3203
        $formaECFRef = "\r\nECF Ref.: modelo: %s ECF:%d COO:%d";
3204
        $formaNfpRef = "\r\nNFP Ref.: série:%d número:%d emit:%s em %s modelo: %d IE:%s";
3205
        $saida='';
3206
        $nfRefs = $this->ide->getElementsByTagName('NFref');
3207
        if (0 === $nfRefs->length) {
3208
            return $saida;
3209
        }
3210
        if ($nfRefs->length > 2) {
3211
            return 'Existem mais de 2 NF/NFe/ECF/NFP/CTe referenciadas, não serão exibidas na DANFE.';
3212
        }
3213
        foreach ($nfRefs as $nfRef) {
3214
            if (empty($nfRef)) {
3215
                continue;
3216
            }
3217
            $refNFe = $nfRef->getElementsByTagName('refNFe');
3218
            foreach ($refNFe as $chave_acessoRef) {
3219
                $chave_acesso = $chave_acessoRef->nodeValue;
3220
                $chave_acessoF = $this->formatField($chave_acesso, $this->formatoChave);
3221
                $data = substr($chave_acesso, 4, 2)."/20".substr($chave_acesso, 2, 2);
3222
                $cnpj = $this->formatField(substr($chave_acesso, 6, 14), "##.###.###/####-##");
3223
                $serie  = substr($chave_acesso, 22, 3);
3224
                $numero = substr($chave_acesso, 25, 9);
3225
                $saida .= sprintf($formaNfeRef, $serie, $numero, $cnpj, $data, $chave_acessoF);
3226
            }
3227
            $refNF = $nfRef->getElementsByTagName('refNF');
3228
            foreach ($refNF as $umaRefNFe) {
3229
                $data = $umaRefNFe->getElementsByTagName('AAMM')->item(0)->nodeValue;
3230
                $cnpj = $umaRefNFe->getElementsByTagName('CNPJ')->item(0)->nodeValue;
3231
                $mod = $umaRefNFe->getElementsByTagName('mod')->item(0)->nodeValue;
3232
                $serie = $umaRefNFe->getElementsByTagName('serie')->item(0)->nodeValue;
3233
                $numero = $umaRefNFe->getElementsByTagName('nNF')->item(0)->nodeValue;
3234
                $data = substr($data, 2, 2) . "/20" . substr($data, 0, 2);
3235
                $cnpj = $this->formatField($cnpj, "##.###.###/####-##");
3236
                $saida .= sprintf($formaNfRef, $serie, $numero, $cnpj, $data, $mod);
3237
            }
3238
            $refCTe = $nfRef->getElementsByTagName('refCTe');
3239
            foreach ($refCTe as $chave_acessoRef) {
3240
                $chave_acesso = $chave_acessoRef->nodeValue;
3241
                $chave_acessoF = $this->formatField($chave_acesso, $this->formatoChave);
3242
                $data = substr($chave_acesso, 4, 2)."/20".substr($chave_acesso, 2, 2);
3243
                $cnpj = $this->formatField(substr($chave_acesso, 6, 14), "##.###.###/####-##");
3244
                $serie  = substr($chave_acesso, 22, 3);
3245
                $numero = substr($chave_acesso, 25, 9);
3246
                $saida .= sprintf($formaCTeRef, $serie, $numero, $cnpj, $data, $chave_acessoF);
3247
            }
3248
            $refECF = $nfRef->getElementsByTagName('refECF');
3249
            foreach ($refECF as $umaRefNFe) {
3250
                $mod    = $umaRefNFe->getElementsByTagName('mod')->item(0)->nodeValue;
3251
                $nECF   = $umaRefNFe->getElementsByTagName('nECF')->item(0)->nodeValue;
3252
                $nCOO   = $umaRefNFe->getElementsByTagName('nCOO')->item(0)->nodeValue;
3253
                $saida .= sprintf($formaECFRef, $mod, $nECF, $nCOO);
3254
            }
3255
            $refNFP = $nfRef->getElementsByTagName('refNFP');
3256
            foreach ($refNFP as $umaRefNFe) {
3257
                $data = $umaRefNFe->getElementsByTagName('AAMM')->item(0)->nodeValue;
3258
                $cnpj = ! empty($umaRefNFe->getElementsByTagName('CNPJ')->item(0)->nodeValue) ?
3259
                    $umaRefNFe->getElementsByTagName('CNPJ')->item(0)->nodeValue :
3260
                    '';
3261
                $cpf = ! empty($umaRefNFe->getElementsByTagName('CPF')->item(0)->nodeValue) ?
3262
                        $umaRefNFe->getElementsByTagName('CPF')->item(0)->nodeValue : '';
3263
                $mod = $umaRefNFe->getElementsByTagName('mod')->item(0)->nodeValue;
3264
                $serie = $umaRefNFe->getElementsByTagName('serie')->item(0)->nodeValue;
3265
                $numero = $umaRefNFe->getElementsByTagName('nNF')->item(0)->nodeValue;
3266
                $ie = $umaRefNFe->getElementsByTagName('IE')->item(0)->nodeValue;
3267
                $data = substr($data, 2, 2) . "/20" . substr($data, 0, 2);
3268
                if ($cnpj == '') {
3269
                    $cpf_cnpj = $this->formatField($cpf, "###.###.###-##");
3270
                } else {
3271
                    $cpf_cnpj = $this->formatField($cnpj, "##.###.###/####-##");
3272
                }
3273
                $saida .= sprintf($formaNfpRef, $serie, $numero, $cpf_cnpj, $data, $mod, $ie);
3274
            }
3275
        }
3276
        return $saida;
3277
    }
3278
    
3279
    private function loadDoc($xml)
3280
    {
3281
        $this->xml = $xml;
3282
        if (!empty($xml)) {
3283
            $this->dom = new Dom();
3284
            $this->dom->loadXML($this->xml);
3285
            if (empty($this->dom->getElementsByTagName("infNFe")->item(0))) {
3286
                throw new \Exception('Isso não é um NFe.');
3287
            }
3288
            $this->nfeProc = $this->dom->getElementsByTagName("nfeProc")->item(0);
3289
            $this->infNFe = $this->dom->getElementsByTagName("infNFe")->item(0);
3290
            $this->ide = $this->dom->getElementsByTagName("ide")->item(0);
3291
            if ($this->getTagValue($this->ide, "mod") != '55') {
3292
                throw new \Exception("O xml deve ser NF-e modelo 55.");
3293
            }
3294
            $this->entrega = $this->dom->getElementsByTagName("entrega")->item(0);
3295
            $this->retirada = $this->dom->getElementsByTagName("retirada")->item(0);
3296
            $this->emit = $this->dom->getElementsByTagName("emit")->item(0);
3297
            $this->dest = $this->dom->getElementsByTagName("dest")->item(0);
3298
            $this->enderEmit = $this->dom->getElementsByTagName("enderEmit")->item(0);
3299
            $this->enderDest = $this->dom->getElementsByTagName("enderDest")->item(0);
3300
            $this->det = $this->dom->getElementsByTagName("det");
3301
            $this->cobr = $this->dom->getElementsByTagName("cobr")->item(0);
3302
            $this->dup = $this->dom->getElementsByTagName('dup');
3303
            $this->ICMSTot = $this->dom->getElementsByTagName("ICMSTot")->item(0);
3304
            $this->ISSQNtot = $this->dom->getElementsByTagName("ISSQNtot")->item(0);
3305
            $this->transp = $this->dom->getElementsByTagName("transp")->item(0);
3306
            $this->transporta = $this->dom->getElementsByTagName("transporta")->item(0);
3307
            $this->veicTransp = $this->dom->getElementsByTagName("veicTransp")->item(0);
3308
            $this->reboque = $this->dom->getElementsByTagName("reboque")->item(0);
3309
            $this->infAdic = $this->dom->getElementsByTagName("infAdic")->item(0);
3310
            $this->compra = $this->dom->getElementsByTagName("compra")->item(0);
3311
            $this->tpEmis = $this->getTagValue($this->ide, "tpEmis");
3312
            $this->tpImp = $this->getTagValue($this->ide, "tpImp");
3313
            $this->infProt = $this->dom->getElementsByTagName("infProt")->item(0);
3314
        }
3315
    }
3316
    
3317
    private function imagePNGtoJPG($original)
3318
    {
3319
        $image = imagecreatefrompng($original);
3320
        ob_start();
3321
        imagejpeg($image, null, 100);
3322
        imagedestroy($image);
3323
        $stringdata = ob_get_contents(); // read from buffer
3324
        ob_end_clean();
3325
        return 'data://text/plain;base64,'.base64_encode($stringdata);
3326
    }
3327
}
3328