PHP code example of nfse-br / danfse

1. Go to this page and download the library: Download nfse-br/danfse library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nfse-br / danfse example snippets


use NfseDanfse\Validator\NfseXsdValidator;

$validator = new NfseXsdValidator('/caminho/para/NFSe_v1.00.xsd');
$validator->validateXml($xmlString);


NfseDanfse\Danfse;

$xml = file_get_contents(__DIR__ . '/nfse.xml');
$pdfBinary = (new Danfse())->gerar($xml);

file_put_contents(__DIR__ . '/danfse.pdf', $pdfBinary);

use NfseDanfse\Parser\DanfseXmlParser;
use NfseDanfse\Pdf\DanfsePdfRenderer;
use NfseDanfse\Validator\NfseXsdValidator;

$xml = file_get_contents(__DIR__ . '/nfse.xml');

(new NfseXsdValidator())->validateXml($xml);

$data = DanfseXmlParser::fromXmlString($xml)->parse();

$pdfBinary = (new DanfsePdfRenderer())->renderToString($data);



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use NfseDanfse\Danfse;

class DanfseController extends Controller {
    public function gerar(Request $request) {
        $request->validate([
            'xml' => ['      'Content-Disposition' => 'attachment; filename=\"danfse.pdf\"',
        ]);
    }
}



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use NfseDanfse\Danfse;

class DanfseController extends Controller {
    public function gerar(Request $request) {
        $request->validate([
            'xml' => ['utputPdf = $outputDir . '/danfse-' . now()->format('YmdHis') . '.pdf';
        (new Danfse())->gerarParaArquivo($xml, $outputPdf);

        return response()->download($outputPdf)->deleteFileAfterSend(true);
    }
}



namespace App\Console\Commands;

use Illuminate\Console\Command;
use NfseDanfse\Danfse;

class GerarDanfse extends Command {
    protected $signature = 'danfse:gerar {xml : Caminho do XML} {--out= : Caminho do PDF de saída}';
    protected $description = 'Gera DANFSe (PDF) a partir de um XML de NFS-e Nacional';

    public function handle(): int {
        $xmlPath = $this->argument('xml');
        $outputPdf = $this->option('out') ?: storage_path('app/danfse.pdf');

        (new Danfse())->gerarDeArquivo($xmlPath, $outputPdf);

        $this->info('PDF gerado em: ' . $outputPdf);
        return self::SUCCESS;
    }
}
bash
php examples/gerar-danfse.php