npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ninepay/nfse-pdf-generator

v1.0.7

Published

Gerador de PDF para NFS-e Nacional (Nota Fiscal de Serviços Eletrônica) seguindo o padrão da Nota Fiscal Nacional

Downloads

737

Readme

NFS-e PDF Generator

Gerador de PDF para NFS-e Nacional (Nota Fiscal de Serviços Eletrônica) seguindo o padrão da Nota Fiscal Brasil.

📦 Instalação

npm install @ninepay/nfse-pdf-generator

🚀 Uso Básico

import { NfsePdfGenerator } from '@ninepay/nfse-pdf-generator';
import fs from 'fs';

async function gerarPDF() {
  // Criar instância do gerador
  const generator = new NfsePdfGenerator();
  
  // Configurar dados do município (opcional)
  generator.setMunicipality({
    name: 'Prefeitura Municipal',
    department: 'Secretaria de Fazenda',
    phone: '(11) 1234-5678',
    email: '[email protected]',
    imageBase64: 'data:image/png;base64,iVBORw0KGgoAAAANS...' // opcional
  });
  
  // Fazer parse do XML (string)
  const xmlContent = fs.readFileSync('./nfse.xml', 'utf-8');
  generator.parseXml(xmlContent);
  
  // Gerar PDF
  const pdfDoc = await generator.generate();
  
  // Salvar em arquivo
  pdfDoc.pipe(fs.createWriteStream('nota-fiscal.pdf'));
  pdfDoc.end();
}

gerarPDF();

📖 Exemplo Completo

import { NfsePdfGenerator } from '@ninepay/nfse-pdf-generator';
import fs from 'fs';

async function main() {
  try {
    // Ler o conteúdo XML
    const xmlContent = fs.readFileSync('./nfse-exemplo.xml', 'utf-8');
    
    // Converter logo do município para base64
    const brasaoMunicipio = fs.readFileSync('./brasao-sp.png').toString('base64');
    
    const generator = new NfsePdfGenerator(
      'Minha Empresa', // author
      'Sistema de NFS-e', // creator
      'Documento Auxiliar da NFS-e' // subject
    );
    
    // Configurar dados do município (opcional)
    generator.setMunicipality({
      name: 'Prefeitura de São Paulo',
      department: 'Secretaria Municipal de Fazenda',
      phone: '(11) 3113-9000',
      email: '[email protected]',
      imageBase64: `data:image/png;base64,${brasaoMunicipio}`
    });
    
    // Parse do conteúdo XML da NFS-e
    generator.parseXml(xmlContent);
    
    // Gerar PDF
    const pdf = await generator.generate();
    
    // Salvar arquivo
    const outputPath = './output/nfse-gerada.pdf';
    pdf.pipe(fs.createWriteStream(outputPath));
    pdf.end();
    
    console.log(`✅ PDF gerado com sucesso: ${outputPath}`);
  } catch (error) {
    console.error('❌ Erro ao gerar PDF:', error);
  }
}

main();

🎨 Personalização

Cabeçalho (Header)

O cabeçalho da NFS-e possui valores fixos e internos que aparecem automaticamente em todas as notas:

  • Logo da NFS-e Nacional
  • Texto "DANFSE - Documento Auxiliar da Nota Fiscal de Serviços Eletrônica"
  • Título "NFS-e Nacional"

Esses elementos não precisam (e não podem) ser configurados, garantindo padronização.

Dados do Município

generator.setMunicipality({
  name?: string,         // Nome do município/prefeitura
  department?: string,   // Departamento/secretaria
  phone?: string,        // Telefone de contato
  email?: string,        // Email de contato
  imageBase64?: string   // Brasão/logo em Data URI ou base64 puro (opcional)
                         // Formato: 'data:image/png;base64,iVBORw0KGg...' ou 'iVBORw0KGg...'
});

🖼️ Formato de Imagens

Logo NFS-e

A logo da NFS-e é interna e fixa, carregada automaticamente pelo gerador. Não é necessário fornecê-la.

Logo do Município

A logo do município aceita Data URI ou base64 puro:

// Opção 1: Data URI
const imageBuffer = fs.readFileSync('./brasao.png');
const base64 = imageBuffer.toString('base64');
const dataUri = `data:image/png;base64,${base64}`;

generator.setMunicipality({
  imageBase64: dataUri
});

// Opção 2: Base64 puro
generator.setMunicipality({
  imageBase64: base64
});

Formatos suportados: png, jpg, jpeg

📁 Estrutura do XML

O gerador aceita o conteúdo XML no padrão NFS-e Nacional como string. Exemplo de estrutura mínima:

<?xml version="1.0" encoding="UTF-8"?>
<NFSe>
  <infNFSe Id="NFS12345678901234567890123456789012345678901234">
    <nNFSe>123456</nNFSe>
    <dhProc>2024-01-15T10:30:00-03:00</dhProc>
    <emit>
      <CNPJ>12345678000190</CNPJ>
      <xNome>Empresa Prestadora LTDA</xNome>
      <!-- mais campos do emitente -->
    </emit>
    <DPS>
      <infDPS>
        <toma>
          <CNPJ>98765432000100</CNPJ>
          <xNome>Cliente Tomador LTDA</xNome>
          <!-- mais campos do tomador -->
        </toma>
        <serv>
          <!-- dados do serviço -->
        </serv>
        <valores>
          <!-- valores da nota -->
        </valores>
      </infDPS>
    </DPS>
  </infNFSe>
</NFSe>

🔧 API

new NfsePdfGenerator(author?, creator?, subject?)

Cria uma nova instância do gerador.

setMunicipality(data: MunicipalityHeaderData): this

Define os dados do município.

Parâmetros:

{
  name?: string;
  department?: string;
  phone?: string;
  email?: string;
  imageBase64?: string; // Data URI ou base64 puro
}

parseXml(xmlContent: string): this

Faz o parse do conteúdo XML da NFS-e.

Parâmetros:

  • xmlContent: String contendo o conteúdo XML da NFS-e

Retorna: this (para encadeamento)

Lança: Error se o XML for inválido

Exemplo:

const xmlContent = fs.readFileSync('./nfse.xml', 'utf-8');
generator.parseXml(xmlContent);

async generate(): Promise<PDFKit.PDFDocument>

Gera o documento PDF.

Retorna: Promise com o documento PDFKit

Lança: Error se parseXml() não foi chamado antes

Exemplo:

const pdf = await generator.generate();
pdf.pipe(fs.createWriteStream('output.pdf'));
pdf.end();

📋 Requisitos

  • Node.js >= 14
  • TypeScript >= 4.5 (se usar TypeScript)

🤝 Contribuindo

Contribuições são bem-vindas! Por favor:

  1. Faça um fork do projeto
  2. Crie uma branch para sua feature (git checkout -b feature/MinhaFeature)
  3. Commit suas mudanças (git commit -m 'Adiciona MinhaFeature')
  4. Push para a branch (git push origin feature/MinhaFeature)
  5. Abra um Pull Request

📝 Licença

MIT

👤 Autor

Arthur Fonseca

🐛 Reportar Bugs

Encontrou um bug? Por favor abra uma issue.

⭐ Mostre seu apoio

Dê uma ⭐️ se este projeto ajudou você!