Ejemplo n.º 1
0
        public void Boleto_Caixa()
        {
            // Exemplo 100% de acordo com a documentação usando os parametros mínimos
            // https://github.com/impactro/Boleto-ASP.NET/files/44866/ESPCODBARR_SICOB.pdf
            // Página 8, item 5.1.1

            /* Dados usados para cálculo:
             *   104 Banco ...............................Posição: 01 - 03
             *     9 Moeda ...............................Posição: 04 - 04
             * 1099(10/10/2000) Fator de Vencimento .................Posição: 06 - 09
             * 160,00 Valor ...............................Posição: 10 - 19
             * 9001200200 Nosso Número (sem DV) ...............Posição: 20 - 29
             * 001287000000012 Código do Cedente no SICOB(sem DV) ..Posição: 30 - 44 */

            // Dados do Recebedor
            CedenteInfo c = new CedenteInfo()
            {
                Banco      = "104-0",
                CodCedente = "001287000000012"
            };

            // Dados do Pagador
            SacadoInfo s = new SacadoInfo();

            // Informações do Boleto
            BoletoInfo b = new BoletoInfo()
            {
                DataVencimento = DateTime.Parse("10/10/2000"),
                ValorDocumento = 160,
                NossoNumero    = "9001200200" // Exemplo do caso especial onde o Dv dá Zero (caso critico)
            };

            // Cria uma instancia do objeto que calcula e monta um boleto
            Boleto bol = new Boleto();

            // Seta as variáveis (parametros) com os dados do recebedor (c), pagador (s), e as informações do boleto (b)
            bol.MakeBoleto(c, s, b);

            // Calcula efetivamente o boleto
            bol.CalculaBoleto();

            // Imprime a linha digitável no console e alguns outros dados para conferencia
            Console.WriteLine("Linha Digitável: " + bol.LinhaDigitavel);
            Console.WriteLine("Agência/Conta: " + bol.AgenciaConta);
            Console.WriteLine("Nosso Número: " + bol.NossoNumeroExibicao);
            Console.WriteLine("Fator Vencimento: " + CobUtil.CalcFatVenc(bol.DataVencimento));

            // De acordo com a página 13 deve gerar exatamente a linha abaixo
            Assert.IsTrue(bol.LinhaDigitavel == "10499.00127 00200.001287 70000.000128 1 10990000016000");

            // Outro exemplo qualquer:
            b.NossoNumero = "9000003225";
            bol.MakeBoleto(c, s, b);                                  // atualizo os dados (não é recomendado, mas para simplificar funciona)
            bol.CalculaBoleto();                                      // se não chamar esta rotina, virá comos resultados calculados anteriormente
            Console.WriteLine("Exemplo Livre: Nosso Número: " + bol.NossoNumeroExibicao);
            Assert.IsTrue(bol.NossoNumeroExibicao == "9000003225-0"); // no caso o sistema sempre preenche com os digitos zeros a esquerda

            // Salva a imagem do boleto para conferencia visual
            bol.Save("boleto.png");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Adiciona um boleto e seu respectivo sacado (será armazenado uma cópia (cole) destas instancias
        /// </summary>
        public void Add(BoletoInfo bol, SacadoInfo sac)
        {
            BoletoInfo boleto = bol.Clone(); // é feita uma cópia do boleto com os dados adicionais para não alterar o original

            boleto.SacadoInit((SacadoInfo)CobUtil.Clone(sac));
            cnab.Boletos.Add(boleto);
#if TEST_LOG
            cnab.Log += "\r\n +" + boleto.NossoNumero + " QTD: " + cnab.Boletos.Count + "\r\n";
            BoletoInfo b;
            foreach (string n in Boletos.NossoNumeros)
            {
                b         = Boletos[n];
                cnab.Log += string.Format("'{0}' '{1}' / ", n, b.NossoNumero);
            }
            //cnab.Log += " - bi - ";
            //foreach (string n in bi.Keys)
            //{
            //    b = null;
            //    if (bi.TryGetValue(n, out b))
            //        cnab.Log += string.Format("'{0}' '{1}' / ", n, b.NossoNumero);
            //    else
            //        cnab.Log += n + "! ";
            //}
#endif
        }
Ejemplo n.º 3
0
        public void CampoLivre_Banestes()
        {
            // Leia mais sobre esse teste: https://github.com/impactro/Boleto-Test/wiki/Criando-Layouts/_edit
            Boleto blt = new Boleto();
            string cl  = Banco_Banestes.CampoLivre(blt, Cedente.CodCedente, Cedente.Modalidade, "178");

            Console.WriteLine("Linha Digitável Formatada: " + CobUtil.CampoLivreFormatado(cl, new int[] { 8, 11, 1, 3, 1, 1 }));  // maximo 25 digitos
            Assert.IsTrue(cl == "0000017800006573315402141", "Linha invalida");
            // Veja página 31 e 38 da documentação
        }
Ejemplo n.º 4
0
        public void RemoveAcentos()
        {
            string c1 = "Acentos Atenção 1ºSei lá; ok";

            Console.WriteLine(c1);

            string c2 = CobUtil.RemoveAcentos(c1);

            Console.WriteLine(c2);

            Assert.IsTrue(c1.Length == c2.Length);
        }
Ejemplo n.º 5
0
        public void CampoLivre_Caixa()
        {
            Boleto blt = new Boleto();
            string cl;

            // Logica 1
            cl = Banco_Caixa.CampoLivre(blt, "", "123456789012345", "", "", "9876543210");
            Console.WriteLine(
                "Campo Livre para código do cedente de 15 digitos: " + cl +
                " Agencia/Conta: " + blt.AgenciaConta +
                " Nosso Número: " + blt.NossoNumeroExibicao);
            Assert.IsTrue(cl == "9876543210123456789012345");

            // Logica 2
            cl = Banco_Caixa.CampoLivre(blt, "5555", "123456", "2", "3", "543210987654321");
            Console.WriteLine(
                "Campo Livre para código de cededente de 6 digitos: " + cl +
                " Agencia/Conta: " + blt.AgenciaConta +
                " Nosso Número: " + blt.NossoNumeroExibicao);
            Assert.IsTrue(cl == "1234560543321049876543219");

            // Logica 3
            cl = Banco_Caixa.CampoLivre(blt, "", "12345", "7777", "8", "7654321");
            Console.WriteLine(
                "Campo Livre para carteira 8 ara código de cedente de 5 posições: " + cl +
                " Agencia/Conta: " + blt.AgenciaConta +
                " Nosso Número: " + blt.NossoNumeroExibicao);
            Assert.IsTrue(cl == "1234577778700000007654321");

            // Logica 4
            cl = Banco_Caixa.CampoLivre(blt, "", "333333", "", "1", "76543210987654321");
            Console.WriteLine(
                "Campo Livre para caso generico: " + cl +
                " Agencia/Conta: " + blt.AgenciaConta +
                " Nosso Número: " + blt.NossoNumeroExibicao);
            Assert.IsTrue(cl == "3333337543121049876543214");

            // Teste Livre
            cl = Banco_Caixa.CampoLivre(blt, "", "123456789012345", "", "", "9000003225");              // o DV do Nosso numero tem que dar Zero!
            Console.WriteLine(
                "Linha Digitável Formatada: " + CobUtil.CampoLivreFormatado(cl, new int[] { 10, 15 }) + // maximo 25 digitos
                " Agencia/Conta: " + blt.AgenciaConta +
                " Nosso Número: " + blt.NossoNumeroExibicao);

            // Linha Digitável Formatada: 9000003225.123456789012345
            // ---------------------------1234567890
            // Agencia / Conta: 1234.567.89012345.2
            // Nosso Número: 9000003225 - 0
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Cria uma nova instancia do WebControl do Boleto
        /// </summary>
        public BoletoWeb()
        {
            try
            {
                blt = new Boleto();

                // Lê do web.config a opção padrão de renderização HTML/IMAGEM
                // <add key = "BoletoRenderImage" value = "true" />
                if (cRenderImage == null)
                {
                    RenderCountImage = CobUtil.GetInt(System.Configuration.ConfigurationManager.AppSettings["BoletoRenderImage"]);
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 7
0
    /// <summary>
    /// Rotina de Geração do Campo livre usado no Código de Barras para formar o IPTE
    /// </summary>
    /// <param name="blt">Intancia da Classe de Boleto</param>
    /// <returns>String de 25 caractere que representa 'Campo Livre'</returns>
    public static string MeuCampoLivre(Boleto blt, string cAgenciaNumero, string cContaNumero, string cNossoNumero)
    {
        cAgenciaNumero = CobUtil.Right(cAgenciaNumero, 4);
        cContaNumero   = CobUtil.Right(cContaNumero, 7);
        cNossoNumero   = CobUtil.Right(cNossoNumero, 13);

        string cDAC = CobUtil.Modulo10(cNossoNumero + cAgenciaNumero + cContaNumero).ToString();

        string cLivre = cAgenciaNumero +
                        cContaNumero +
                        cDAC +
                        cNossoNumero;

        blt.AgenciaConta        = cAgenciaNumero + "/" + cContaNumero + "-" + cDAC;
        blt.NossoNumeroExibicao = cNossoNumero;

        return(cLivre);
    }
Ejemplo n.º 8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Apenas para achar o posicionamento do conteudo padrão: Banco/Vencimento/Valor 44 - 25 = 19 posiçoes iniciais
            // ------------------------1234567890123456789_______CAMPO_LIVRE_______
            // ------------------------_BANCO_VENC_VALOR__1234567890123456789012345
            string cCodBarrasCoreto = "03392642100000001009717792500000019720301101";
            // Comparativo...........: 03392642100000001009717792500000019720301101
            logOut.InnerText = "iniciando\r\n";

            // Usa uma rotina pré existente para montar só o campo livre
            string cCampoLivre = Banco_Banespa.CampoLivre(new Boleto(), "97177925000", "1972030");
            CampoLivre.Text = cCampoLivre;

            // Se a ideia é validar o campo livre pose-se pegar direto o inicio da código de barras direto sem o digito verificador
            string cCodBarras =
                cCodBarrasCoreto.Substring(0, 4) +
                cCodBarrasCoreto.Substring(5, 14) +
                cCampoLivre;
            //cCodBarrasCoreto.Substring(19, 25);

            string cDV = CobUtil.Modulo11Padrao(cCodBarras, 9).ToString(); // Só a Caixa calcula direfente!
            cCodBarras = cCodBarras.Substring(0, 4) + cDV + cCodBarras.Substring(4);

            // Exibe o Código de barras
            CodigoBarras.Text = CobUtil.CodigoBarrasFormatado(cCodBarras, new int[] { 25 });

            // Veja o Exemplo: BoletoCustomizado.aspx
            LinhaDigitavel.Text = CobUtil.CalcLinDigitavel(cCodBarras);

            // Gera o Código de barras no padrão: pf, pl, bf, bl (preto fino, preto largo, branco fino branco largo)
            Barras.Text = CobUtil.BarCode(cCodBarras)
                          .Replace("bf", "<img src='imagens/b.gif' width=1 height=50>")
                          .Replace("bl", "<img src='imagens/b.gif' width=3 height=50>")
                          .Replace("pf", "<img src='imagens/p.gif' width=1 height=50>")
                          .Replace("pl", "<img src='imagens/p.gif' width=3 height=50>");
        }
        catch (Exception ex)
        {
            logOut.InnerText += "\r\n<b>" + ex.Message + "</b>\r\n" + ex.StackTrace;
        }
    }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bltFrm"></param>
        public void Gera(Infra.Entidades.Boleto bltFrm, string Mora)
        {
            reportViewer1.LocalReport.ReportPath           = HttpContext.Current.Server.MapPath("~/App_Data/Report/Boleto.rdlc");
            reportViewer1.LocalReport.EnableExternalImages = true;
            string tituloPrefeitura = string.Empty;

            if (File.Exists(HttpContext.Current.Server.MapPath("~/App_Data/BoletosPDF/CodigoDeBarras.jpg")))
            {
                File.Delete(HttpContext.Current.Server.MapPath("~/App_Data/BoletosPDF/CodigoDeBarras.jpg"));
            }
            CobUtil.BarCodeImage(bltFrm.Observacao).Save(HttpContext.Current.Server.MapPath("~/App_Data/BoletosPDF/CodigoDeBarras.jpg"));
            string teste = HttpContext.Current.Server.MapPath("~/App_Data/BoletosPDF/CodigoDeBarras.jpg");

            reportViewer1.LocalReport.SetParameters(new ReportParameter[]
            {
                AdicionaParametro("LogoAgencia", "logobras"),
                AdicionaParametro("CaminhoCodigoBarras", bltFrm.Observacao),
                AdicionaParametro("AutenticacaoCodigo", bltFrm.AutenticacaoCodigo),
                AdicionaParametro("CedenteNome", bltFrm.Cedente),
                AdicionaParametro("SacadoNome", bltFrm.Sacado),
                AdicionaParametro("NumeroDocumento", bltFrm.NumeroDocumento),
                AdicionaParametro("EspecieMoeda", bltFrm.EspecieMoeda),
                AdicionaParametro("AgenciaCodCedente", bltFrm.Agencia),
                AdicionaParametro("NossoNumero", bltFrm.NossoNumero),
                AdicionaParametro("ValorDocumento", bltFrm.ValorBoleto.ToString()),
                AdicionaParametro("DataProcessamento", bltFrm.DataEmissao.ToShortDateString()),
                AdicionaParametro("localPagamento", bltFrm.localPagamento),
                AdicionaParametro("Agencia", bltFrm.CodigoBanco),
                AdicionaParametro("Aceite", bltFrm.Aceite),
                AdicionaParametro("Carteira", bltFrm.Carteira),
                AdicionaParametro("EspecieDocumento", "DM"),
                AdicionaParametro("Vencimento", bltFrm.DataVencimentoOriginal.ToShortDateString()),
                AdicionaParametro("Mora", Mora)
            });

            reportViewer1.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout);
            reportViewer1.RefreshReport();
            SavePDF(reportViewer1, bltFrm.NumeroDocumento + ".pdf");
        }
Ejemplo n.º 10
0
        public override string Remessa()
        {
            string[] cBanco = Cedente.Banco.Split('-');
            Bancos   banco  = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (banco != Bancos.SICREDI)
            {
                throw new Exception("Esta classe é valida apenas para o Banco Sicredi");
            }

            // Proximo item
            SequencialRegistro = 1;

            regArqHeader[CNAB400HeaderSicredi.CodCedente]    = Cedente.CodCedente;
            regArqHeader[CNAB400HeaderSicredi.CNPJ]          = Cedente.DocumentoNumeros;
            regArqHeader[CNAB400HeaderSicredi.Data]          = DataHoje;
            regArqHeader[CNAB400HeaderSicredi.NumeroRemessa] = NumeroLote;
            regArqHeader[CNAB400HeaderSicredi.Sequencia]     = SequencialRegistro++;
            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            // o sequencial do header é sempre 1 (FIXO)
            Add(regArqHeader);

            string     cAgenciaNumero = Cedente.Agencia.Split('-')[0];
            string     cModalidade    = Cedente.Modalidade;
            string     cCodCedente    = Cedente.CodCedente;
            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB400Remessa1Sicredi> regBoleto;

            foreach (string n in this.Boletos.NossoNumeros)
            {
                boleto = Boletos[n];
                sacado = boleto.Sacado;

                regBoleto = new Reg <CNAB400Remessa1Sicredi>();

                string cNossoNumero = boleto.NossoNumero;
                Banco_Sicredi.MontaNossoNumero(ref cNossoNumero, ref cAgenciaNumero, ref cModalidade, ref cCodCedente);

                regBoleto[CNAB400Remessa1Sicredi.NossoNumero]     = cNossoNumero;
                regBoleto[CNAB400Remessa1Sicredi.NumeroDocumento] = boleto.NumeroDocumento;
                regBoleto[CNAB400Remessa1Sicredi.DataVencimento]  = boleto.DataVencimento;
                regBoleto[CNAB400Remessa1Sicredi.ValorDocumento]  = boleto.ValorDocumento;
                regBoleto[CNAB400Remessa1Sicredi.Especie]         = EspecieSicred(boleto.Especie);
                regBoleto[CNAB400Remessa1Sicredi.Aceite]          = boleto.Aceite == "A" ? "S" : "N";
                regBoleto[CNAB400Remessa1Sicredi.Data]            = boleto.DataDocumento;
                regBoleto[CNAB400Remessa1Sicredi.DataEmissao]     = boleto.DataDocumento;
                if (boleto.ParcelaTotal > 0)
                {
                    regBoleto[CNAB400Remessa1Sicredi.TipoImpressao] = "B";
                    regBoleto[CNAB400Remessa1Sicredi.ParcelaNumero] = boleto.ParcelaNumero;
                    regBoleto[CNAB400Remessa1Sicredi.ParcelaTotal]  = boleto.ParcelaTotal;
                }
                regBoleto[CNAB400Remessa1Sicredi.Instrucao]       = boleto.Instrucao1;
                regBoleto[CNAB400Remessa1Sicredi.Protesto]        = boleto.DiasProtesto > 6 ? "06":"00";
                regBoleto[CNAB400Remessa1Sicredi.DiasProtesto]    = boleto.DiasProtesto;
                regBoleto[CNAB400Remessa1Sicredi.PercentualMora]  = boleto.PercentualMora;
                regBoleto[CNAB400Remessa1Sicredi.DataDesconto]    = boleto.DataDesconto;
                regBoleto[CNAB400Remessa1Sicredi.ValorDesconto]   = boleto.ValorDesconto;
                regBoleto[CNAB400Remessa1Sicredi.SacadoTipo]      = sacado.Tipo;
                regBoleto[CNAB400Remessa1Sicredi.SacadoDocumento] = sacado.DocumentoNumeros;
                regBoleto[CNAB400Remessa1Sicredi.Sacado]          = sacado.Sacado;
                regBoleto[CNAB400Remessa1Sicredi.Endereco]        = sacado.Endereco;
                regBoleto[CNAB400Remessa1Sicredi.Cooperativa]     = "00000";
                regBoleto[CNAB400Remessa1Sicredi.CEP]             = sacado.CepNumeros;
                regBoleto[CNAB400Remessa1Sicredi.Sequencia]       = SequencialRegistro++;

                // adiciona o boleto convertido em registro
                AddBoleto(regBoleto, boleto);

                AddOpcionais(boleto);
            }

            regArqTrailer[CNAB400Trailer1Sicredi.Conta]     = CobUtil.GetInt(Cedente.Conta.Split('-')[0]);
            regArqTrailer[CNAB400Trailer1Sicredi.Sequencia] = SequencialRegistro;
            Add(regArqTrailer);

            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Inicializa o gerador de layouts de acordo com o cedente, usando a instancia apropriada para cada banco
        /// </summary>
        public void Init(CedenteInfo cedente)
        {
            string[] cBanco = cedente.Banco.Split('-');
            Bancos   banco  = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (banco == Bancos.SANTANDER || banco == Bancos.BANESPA_SANTANDER)
            {
                if (cedente.Layout == LayoutTipo.CNAB240)
                {
                    cnab = new CNAB240Santander();
                }
                else
                {
                    cnab = new CNAB400Santander();
                }
            }
            else if (banco == Bancos.BRADESCO)
            {
                cnab = new CNAB400Bradesco();
            }
            else if (banco == Bancos.ITAU)
            {
                cnab = new CNAB400Itau();
            }
            else if (banco == Bancos.BANCO_DO_BRASIL)
            {
                cnab = new CNAB400BB();
            }
            else if (banco == Bancos.SICREDI)
            {
                cnab = new CNAB400Sicredi();
            }
            else if (banco == Bancos.UniCred)
            {
                cnab = new CNAB400UniCred();
            }
            else if (banco == Bancos.BANESTES) // Em homologação
            {
                cnab = new CNAB400Banestes();
            }
            else if (banco == Bancos.BRB) // Em homologação
            {
                cnab = new CNAB400BRB();
            }
            else if (banco == Bancos.CAIXA_ECONOMICA_FEDERAL)
            {
                if (cedente.Layout == LayoutTipo.Auto || cedente.Layout == LayoutTipo.CNAB240)
                {
                    cnab = new CNAB240Caixa();
                }
            }
            else if (banco == Bancos.SICOOB)
            {
                cnab = new CNAB240Sicoob();
            }

            if (cnab == null)
            {
                throw new Exception("Banco " + banco.ToString() + " não implementado para layout " + cedente.Layout);
            }

            cnab.Cedente = CobUtil.Clone(cedente) as CedenteInfo;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gera o aquivo baseado nas coleção de todas informações passada até o momento
        /// </summary>
        /// <returns></returns>
        public override string Remessa()
        {
            // Existe algum BUG na executação de template e reflection com ActiveX que  dentro do doreach de conteudo da classe e layout acaba por não gerar o arquivo final.
            // Então, cada linha já será gerada imediatamente em uma String Builder, liberando assim a necessidade de memorizar os itens que iriam conter no arquivo.

            string[] cBanco = Cedente.Banco.Split('-');
            string[] cAgDig = Cedente.Agencia.Split('-');
            string[] cCCDig = Cedente.Conta.Split('-');

            Bancos banco = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (banco != Bancos.BRB)
            {
                throw new Exception("Esta classe é valida apenas para o BRB");
            }

            regArqHeader[CNAB400BRBHeader.Agencia]  = cAgDig[0];
            regArqHeader[CNAB400BRBHeader.Conta]    = cCCDig[0];
            regArqHeader[CNAB400BRBHeader.DataHora] = DataHoje;

            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            // o sequencial do header é sempre 1 (FIXO)
            Add(regArqHeader);

            // Proximo item
            SequencialRegistro = 2;

            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB400BRBRemessa1> regBoleto;

            double nValor = 0;

#if TEST_LOG
            Log += "Remessa " + Boletos.Count + "!\r\n";
#endif
            foreach (string n in Boletos.NossoNumeros)
            {
                boleto  = Boletos[n];
                sacado  = boleto.Sacado;
                nValor += boleto.ValorDocumento;
#if TEST_LOG
                Log += string.Format("{0} {1} {2:C}", n, boleto.NossoNumero, boleto.ValorDocumento);
#endif
                regBoleto = new Reg <CNAB400BRBRemessa1>();

                regBoleto[CNAB400BRBRemessa1.Agencia]          = cAgDig[0];
                regBoleto[CNAB400BRBRemessa1.Conta]            = cCCDig[0];
                regBoleto[CNAB400BRBRemessa1.Sacado_Inscricao] = sacado.DocumentoNumeros;
                regBoleto[CNAB400BRBRemessa1.Nome]             = sacado.Sacado;
                regBoleto[CNAB400BRBRemessa1.Endereco]         = sacado.Endereco;
                regBoleto[CNAB400BRBRemessa1.Cidade]           = sacado.Cidade;
                regBoleto[CNAB400BRBRemessa1.UF]          = sacado.UF;
                regBoleto[CNAB400BRBRemessa1.CEP]         = sacado.CepNumeros;
                regBoleto[CNAB400BRBRemessa1.Sacado_Tipo] = sacado.Tipo;
                regBoleto[CNAB400BRBRemessa1.SeuNumero]   = boleto.BoletoID;
                regBoleto[CNAB400BRBRemessa1.NossoNumero] = boleto.NossoNumero;
                regBoleto[CNAB400BRBRemessa1.Emissao]     = boleto.DataDesconto;

                if (boleto.Especie == Especies.DM)
                {
                    regBoleto[CNAB400BRBRemessa1.Tipo_Documento] = 21;
                }
                else if (boleto.Especie == Especies.NP)
                {
                    regBoleto[CNAB400BRBRemessa1.Tipo_Documento] = 22;
                }
                else if (boleto.Especie == Especies.RC)
                {
                    regBoleto[CNAB400BRBRemessa1.Tipo_Documento] = 25;
                }
                else
                {
                    regBoleto[CNAB400BRBRemessa1.Tipo_Documento] = 39;
                }

                regBoleto[CNAB400BRBRemessa1.DataVencimento] = boleto.DataVencimento;
                regBoleto[CNAB400BRBRemessa1.Valor]          = boleto.ValorDocumento;

                regBoleto[CNAB400BRBRemessa1.Instrucao1] = boleto.Instrucao1;
                regBoleto[CNAB400BRBRemessa1.Instrucao2] = boleto.Instrucao2;

                SequencialRegistro++;

                // adiciona o boleto convertido em registro
                AddBoleto(regBoleto, boleto);

                AddOpcionais(boleto);
            }

            // Atualiza o Header com o numero total de registros
            regArqHeader[CNAB400BRBHeader.Sequencia] = SequencialRegistro - 1;

            //ShowDumpLine = true;
            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 13
0
    protected void btnGerar_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(txtArquivo.Text))
            {
                ltrOut.Text = "Informe o nome do arquivo com o layout CSV editado";
                return;
            }
            string cFile = MapPath(txtArquivo.Text);
            if (!File.Exists(cFile))
            {
                ltrOut.Text = "Arquivo não existe";
                return;
            }
            CSV csv = new CSV();
            csv.Load(cFile);

            DataTable tb = csv.data;
            if (tb.Columns.Count < 4)
            {
                ltrOut.Text = "É preciso ter ao menos 4 colunas";
                return;
            }

            StringBuilder sb = new StringBuilder();
            string        cCampo;
            string        cTamanho;
            string        cTipo;
            string        cRegFormat;
            int           nPos = 1;

            sb.AppendLine("[RegLayout(@\"^1\")]");
            sb.AppendLine("public enum GenerateLayout \n{");

            // local dos campos
            int nPosNome       = 1;
            int nPosComentario = 2;
            int nPosTamanho    = 0;
            int nPosTipo       = 3;

            foreach (DataRow row in tb.Rows)
            {
                // Campo1: Nome do campo
                cCampo = (string)row[nPosNome];
                if (!Regex.IsMatch(cCampo, @"[A-Za-z]\w+$"))
                {
                    ltrOut.Text = "Nome invalido na posição " + nPos + " - Campo: " + cCampo;
                    return;
                }
                // Campo2: Comentário descritivo do campo
                if (!string.IsNullOrEmpty((string)row[nPosComentario]))
                {
                    sb.AppendLine("\t/// &lt;summary&gt;\n\t/// " + row[nPosComentario] + " \n\t/// &lt;/summary&gt;");
                }

                // Campo3: Posição Inicial/final
                cRegFormat = "[RegFormat(RegType.P";
                // Colocar o numero da linha que define o tamanho
                cTamanho = (string)row[nPosTamanho];
                // Há documentações que é informado o tamanho e outros que é informado o numero de caracteres iniciais e final, aqui vou tratar os 2 casos
                string[] c = cTamanho.Replace(" a ", " ").Split(' ');
                if (c.Length >= 2)
                {
                    cTamanho = (CobUtil.GetInt(c[1]) - CobUtil.GetInt(c[0]) + 1).ToString();
                }

                else if (c.Length == 1)
                {
                    cTamanho = c[0];
                }

                else
                {
                    ltrOut.Text = "O tamanho não pode ser identificado '" + cTamanho + "' no Campo: " + cCampo;
                    return;
                }

                // Campo4: Tipo de Campo
                cTipo = (string)row[nPosTipo];           // Só será usado a primeira letra, edite no Excel/google doscs, o no CSV direto possíveis conversões de numeros para data ou valor
                cTipo = cTipo.Substring(0, 1).ToUpper(); // Desde a época do Cobol os tipos de dado e a forma de representa-los é muito parecido
                // 9 - Valores numéricos inteiros
                // V - Valores mão inteiros (double)
                // D - Datas
                // X - Textos
                // H - Hora
                if (!Regex.IsMatch(cTipo, "[9VDXHNA]"))
                {
                    ltrOut.Text = "Tipo Inválido '" + cTipo + "' no Campo: " + cCampo;
                    return;
                }
                if (cTipo == "N")
                {
                    cTipo = "9";
                }
                else if (cTipo == "A")
                {
                    cTipo = "X";
                }

                cRegFormat += cTipo; // Sendo que os tipos válidos são:
                cRegFormat += ", " + cTamanho;

                // Campo5: Valor padrão do campo (caso exista)
                //if (tb.Columns.Count > 4 && !string.IsNullOrEmpty((string)row[4]))
                //    cRegFormat += ", Default =\"" + row[4] + "\"";

                // Fecha o atributo e coloca um informativo dos tamanhos de posição atual
                cRegFormat += ")] // " + nPos;
                nPos       += CobUtil.GetInt(cTamanho);
                cRegFormat += "-" + (nPos - 1);

                // Por fim adiciona o campo
                sb.AppendLine("\t" + cRegFormat + "\n\t" + cCampo + ",\n");
            }
            sb.AppendLine("}");
            ltrOut.Text = "Copie e cole o código abaixo em um arquivo .CS<br/><hr/><pre>" + sb.ToString() + "</pre>";
        }
        catch (Exception ex)
        {
            ltrOut.Text = "<b>" + ex.Message + "</b><br/><pre>" + ex.StackTrace + "</pre>";
        }
    }
Ejemplo n.º 14
0
        /// <summary>
        /// Gera o aquivo baseado nas coleção de todas informações passada até o momento
        /// </summary>
        /// <returns></returns>
        public override string Remessa()
        {
            string[] cAgDig = Cedente.Agencia.Split('-');
            string[] cCCDig = Cedente.Conta.Split('-');
            string[] cBanco = Cedente.Banco.Split('-');

            Bancos banco = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (banco != Bancos.BANCO_DO_BRASIL)
            {
                throw new Exception("Esta classe é valida apenas para o Banco do Brasil");
            }
            else if (cAgDig.Length != 2)
            {
                throw new Exception("Informe a agência e digito no formato 9999-9");
            }
            else if (cCCDig.Length != 2)
            {
                throw new Exception("Informe a conta e digito no formato 99999999-9");
            }

            // Proximo item
            SequencialRegistro = 1;

            regArqHeader[CNAB400Header1BB.Agencia]         = cAgDig[0];
            regArqHeader[CNAB400Header1BB.AgenciaDV]       = cAgDig[1];
            regArqHeader[CNAB400Header1BB.ContaCorrente]   = cCCDig[0];
            regArqHeader[CNAB400Header1BB.ContaCorrenteDV] = cCCDig[1];
            regArqHeader[CNAB400Header1BB.Cedente]         = Cedente.Cedente;
            regArqHeader[CNAB400Header1BB.Data]            = DataHoje;
            regArqHeader[CNAB400Header1BB.Remessa]         = NumeroLote;
            regArqHeader[CNAB400Header1BB.ConvenioLider]   = Cedente.Convenio;
            regArqHeader[CNAB400Header1BB.Sequencia]       = SequencialRegistro++;
            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            // atualiza o lote
            //regArqHeader[CNAB400Header1Bradesco.Lote] = NumeroLote;

            // o sequencial do header é sempre 1 (FIXO)
            Add(regArqHeader);

            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB400Remessa1BB> regBoleto;

            foreach (string n in this.Boletos.NossoNumeros)
            {
                boleto = Boletos[n];
                sacado = boleto.Sacado;

                regBoleto = new Reg <CNAB400Remessa1BB>();

                regBoleto[CNAB400Remessa1BB.CedenteTipo]     = Cedente.Tipo;
                regBoleto[CNAB400Remessa1BB.Documento]       = Cedente.DocumentoNumeros;
                regBoleto[CNAB400Remessa1BB.Agencia]         = cAgDig[0];
                regBoleto[CNAB400Remessa1BB.AgenciaDV]       = cAgDig[1];
                regBoleto[CNAB400Remessa1BB.ContaCorrente]   = cCCDig[0];
                regBoleto[CNAB400Remessa1BB.ContaCorrenteDV] = cCCDig[1];
                regBoleto[CNAB400Remessa1BB.Convenio]        = Cedente.Convenio;
                regBoleto[CNAB400Remessa1BB.EmpresaCodigo]   = sacado.SacadoCodigo;
                regBoleto[CNAB400Remessa1BB.NossoNumero]     = Banco_do_Brasil.NossoNumero(Cedente.Convenio, Cedente.Modalidade, Cedente.Carteira, boleto.NossoNumero);
                regBoleto[CNAB400Remessa1BB.Indicativo]      = " "; // TODO: Fazer indicativo (informações adicionais de sacador/avalista)
                regBoleto[CNAB400Remessa1BB.Modalidade]      = Cedente.Modalidade;
                regBoleto[CNAB400Remessa1BB.Carteira]        = Cedente.Carteira;
                regBoleto[CNAB400Remessa1BB.Comando]         = boleto.Comando;
                regBoleto[CNAB400Remessa1BB.NumeroDocumento] = boleto.NumeroDocumento;
                regBoleto[CNAB400Remessa1BB.DataVencimento]  = boleto.DataVencimento;
                regBoleto[CNAB400Remessa1BB.ValorDocumento]  = boleto.ValorDocumento;
                regBoleto[CNAB400Remessa1BB.Especie]         = (int)boleto.Especie;
                regBoleto[CNAB400Remessa1BB.Aceite]          = boleto.Aceite;
                regBoleto[CNAB400Remessa1BB.DataDocumento]   = boleto.DataDocumento;
                regBoleto[CNAB400Remessa1BB.Instrucao1]      = boleto.Instrucao1;
                regBoleto[CNAB400Remessa1BB.Instrucao2]      = boleto.Instrucao2;
                regBoleto[CNAB400Remessa1BB.JurosValor]      = boleto.ValorMora;
                regBoleto[CNAB400Remessa1BB.DataDesconto]    = boleto.DataDesconto;
                regBoleto[CNAB400Remessa1BB.ValorDesconto]   = boleto.ValorDesconto;
                regBoleto[CNAB400Remessa1BB.SacadoTipo]      = sacado.Tipo;
                regBoleto[CNAB400Remessa1BB.SacadoDocumento] = sacado.DocumentoNumeros;
                regBoleto[CNAB400Remessa1BB.Sacado]          = sacado.Sacado;
                regBoleto[CNAB400Remessa1BB.Endereco]        = sacado.Endereco;
                regBoleto[CNAB400Remessa1BB.Bairro]          = sacado.Bairro;
                regBoleto[CNAB400Remessa1BB.CEP]             = sacado.CepNumeros;
                regBoleto[CNAB400Remessa1BB.Cidade]          = sacado.Cidade;
                regBoleto[CNAB400Remessa1BB.UF] = sacado.UF;
                regBoleto[CNAB400Remessa1BB.IndicativoValor] = ""; // TODO: valor de acordo com o indicativo
                if (boleto.DiasProtesto > 0)
                {
                    regBoleto[CNAB400Remessa1BB.DiasProtesto] = boleto.DiasProtesto;
                }

                regBoleto[CNAB400Remessa1BB.Sequencia] = SequencialRegistro++;

                // adiciona o boleto convertido em registro
                AddBoleto(regBoleto, boleto);

                AddOpcionais(boleto);
            }

            regArqTrailer[CNAB400ArquivoTrailer.Sequencia] = SequencialRegistro;
            Add(regArqTrailer);

            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Retorna no layout CNAB240
        /// </summary>
        public override string Remessa()
        {
            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            string[] cAgenciaDig = Cedente.Agencia.Split('-');

            // Header do Arquivo
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.InscricaoTipo]    = Cedente.Tipo;
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.InscricaoNumero]  = Cedente.DocumentoNumeros;
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.Agencia]          = cAgenciaDig[0];
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.AgenciaDAC]       = cAgenciaDig[1];
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.CodigoCedente]    = Cedente.CodCedente;
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.EmpresaNome]      = Cedente.Cedente;
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.Data]             = DataHoje;
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.NumeroLote]       = NumeroLote;
            regHeaderArquivo[CNAB240HeaderArquivoCaixa.ReservadoEmpresa] = Producao ? "REMESSA-PRODUÇÃO" : "REMESSA-TESTE";
            Add(regHeaderArquivo);

            // Header do lote
            regHeaderLote[CNAB240HeaderLoteCaixa.Lote]                 = SequencialLote;
            regHeaderLote[CNAB240HeaderLoteCaixa.InscricaoTipo]        = Cedente.Tipo;
            regHeaderLote[CNAB240HeaderLoteCaixa.CodigoConvenio]       = Cedente.Convenio;
            regHeaderLote[CNAB240HeaderLoteCaixa.InscricaoNumero]      = Cedente.DocumentoNumeros;
            regHeaderLote[CNAB240HeaderLoteCaixa.Agencia]              = cAgenciaDig[0];
            regHeaderLote[CNAB240HeaderLoteCaixa.AgenciaDAC]           = cAgenciaDig[1];
            regHeaderLote[CNAB240HeaderLoteCaixa.CodigoCedente]        = Cedente.CodCedente;
            regHeaderLote[CNAB240HeaderLoteCaixa.EmpresaNome]          = Cedente.Cedente;
            regHeaderLote[CNAB240HeaderLoteCaixa.NumeroRemessaRetorno] = NumeroLote;
            regHeaderLote[CNAB240HeaderLoteCaixa.Data]                 = DataHoje;
            Add(regHeaderLote);

            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB240SegmentoPCaixa> regP;
            Reg <CNAB240SegmentoQCaixa> regQ;

            SequencialRegistro = 1;
            double ValorTotal = 0;

            foreach (string n in this.Boletos.NossoNumeros)
            {
                boleto = Boletos[n];
                sacado = boleto.Sacado;

                // Define as informações do segmento P
                regP = new Reg <CNAB240SegmentoPCaixa>();

                regP[CNAB240SegmentoPCaixa.Lote]               = SequencialLote;
                regP[CNAB240SegmentoPCaixa.Nregistro]          = SequencialRegistro++;
                regP[CNAB240SegmentoPCaixa.Agencia]            = cAgenciaDig[0];
                regP[CNAB240SegmentoPCaixa.AgenciaDAC]         = cAgenciaDig[1];
                regP[CNAB240SegmentoPCaixa.CodigoCedente]      = Cedente.CodCedente;
                regP[CNAB240SegmentoPCaixa.CarteiraModalidade] = Cedente.Modalidade;
                regP[CNAB240SegmentoPCaixa.NossoNumero]        = boleto.NossoNumero;
                regP[CNAB240SegmentoPCaixa.NumeroDocumento]    = boleto.NumeroDocumento;
                regP[CNAB240SegmentoPCaixa.Vencimento]         = boleto.DataVencimento;
                regP[CNAB240SegmentoPCaixa.ValorDocumento]     = boleto.ValorDocumento;
                if (boleto.ValorMora >= 0.01)
                {
                    regP[CNAB240SegmentoPCaixa.Juros]     = 1;
                    regP[CNAB240SegmentoPCaixa.JurosData] = boleto.DataVencimento.AddDays(1);
                    regP[CNAB240SegmentoPCaixa.JurosMora] = boleto.ValorMora;
                }
                else
                {
                    regP[CNAB240SegmentoPCaixa.Juros] = 3; // isento
                }
                regP[CNAB240SegmentoPCaixa.Especie]           = (int)boleto.Especie;
                regP[CNAB240SegmentoPCaixa.Aceite]            = boleto.Aceite;
                regP[CNAB240SegmentoPCaixa.Emissao]           = boleto.DataDocumento;
                regP[CNAB240SegmentoPCaixa.UsoEmpresaCedente] = boleto.NossoNumero;
                int nDiasBaixa;
                if (boleto.DiasProtesto > 1)
                {
                    regP[CNAB240SegmentoPCaixa.ProtestoCodigo]       = 1;
                    regP[CNAB240SegmentoPCaixa.ProtestoPrazo]        = boleto.DiasProtesto;
                    regP[CNAB240SegmentoPCaixa.BaixaDevolucaoCodigo] = 2; // Não Baixar / Não Devolver
                    // Baixar em no minimo 8 dias apos o protesto baseado na data de geração do arquivo
                    nDiasBaixa = 0;                                       // boleto.DataVencimento.AddDays(boleto.DiasProtesto + 8).Subtract(DateTime.Now).Days;
                }
                else
                {
                    regP[CNAB240SegmentoPCaixa.ProtestoCodigo]       = 3;                            // não protestar
                    regP[CNAB240SegmentoPCaixa.BaixaDevolucaoCodigo] = boleto.DiasBaixa > 0 ? 1 : 2; // 1 => Baixar / Devolver
                    if (boleto.DiasBaixa > 0)
                    {
                        nDiasBaixa = boleto.DataVencimento.AddDays(boleto.DiasBaixa).Subtract(DataHoje).Days;
                    }
                    else
                    {
                        nDiasBaixa = 0;
                    }
                }
                if (nDiasBaixa <= 0)
                {
                    nDiasBaixa = 0;
                }
                else if (nDiasBaixa < 5)
                {
                    nDiasBaixa = 5;
                }
                else if (nDiasBaixa > 120)
                {
                    nDiasBaixa = 120;
                }

                regP[CNAB240SegmentoPCaixa.BaixaDevolucaoPrazo] = nDiasBaixa;
                ValorTotal += boleto.ValorDocumento;

                // Define as informações do segmento Q
                regQ = new Reg <CNAB240SegmentoQCaixa>();
                regQ[CNAB240SegmentoQCaixa.Lote]          = SequencialLote;
                regQ[CNAB240SegmentoQCaixa.Nregistro]     = SequencialRegistro++;
                regQ[CNAB240SegmentoQCaixa.Sacado_Tipo]   = boleto.Sacado.Tipo;
                regQ[CNAB240SegmentoQCaixa.Sacado_Numero] = CobUtil.GetLong(CobUtil.SoNumeros(boleto.Sacado.DocumentoNumeros));
                regQ[CNAB240SegmentoQCaixa.Nome]          = boleto.Sacado.Sacado;
                regQ[CNAB240SegmentoQCaixa.Endereco]      = boleto.Sacado.Endereco;
                regQ[CNAB240SegmentoQCaixa.Bairro]        = boleto.Sacado.Bairro;
                regQ[CNAB240SegmentoQCaixa.CEP]           = boleto.Sacado.CepNumeros;
                regQ[CNAB240SegmentoQCaixa.Cidade]        = boleto.Sacado.Cidade;
                regQ[CNAB240SegmentoQCaixa.UF]            = boleto.Sacado.UF;
                long avalista = CobUtil.GetLong(boleto.Sacado.AvalistaNumeros);
                if (avalista > 0)
                {
                    regQ[CNAB240SegmentoQCaixa.Avalista_Tipo]   = boleto.Sacado.AvalistaTipo;
                    regQ[CNAB240SegmentoQCaixa.Avalista_Numero] = avalista;
                    regQ[CNAB240SegmentoQCaixa.Avalista_Nome]   = boleto.Sacado.Avalista;
                }

                // adiciona o boleto convertido em registro
                // AddSegmentoPQ(regP, regQ);
                AddBoleto(regP, boleto);
                AddBoleto(regQ, boleto);

                AddOpcionais(boleto);
            }

            regTrailerLote[CNAB240TrailerLoteCaixa.Lote]          = SequencialLote;
            regTrailerLote[CNAB240TrailerLoteCaixa.QTD]           = SequencialRegistro + 1; // tem que incluir o header
            regTrailerLote[CNAB240TrailerLoteCaixa.CobrancaQTD]   = this.Boletos.Count;
            regTrailerLote[CNAB240TrailerLoteCaixa.CobrancaValor] = ValorTotal;
            Add(regTrailerLote);

            regTrailerArquivo[CNAB240TrailerArquivoCaixa.LotesQTD]     = 1;
            regTrailerArquivo[CNAB240TrailerArquivoCaixa.RegistrosQTD] = itens.Count + 1;
            Add(regTrailerArquivo);

            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gera o aquivo baseado nas coleção de todas informações passada até o momento
        /// </summary>
        /// <returns></returns>
        public override string Remessa()
        {
            // Existe algum BUG na executação de template e reflection com ActiveX que  dentro do doreach de conteudo da classe e layout acaba por não gerar o arquivo final.
            // Então, cada linha já será gerada imediatamente em uma String Builder, liberando assim a necessidade de memorizar os itens que iriam conter no arquivo.

            string[] cBanco        = Cedente.Banco.Split('-');
            string[] cAgDig        = Cedente.Agencia.Split('-');
            string   cContaDigitos = CobUtil.SoNumeros(Cedente.Conta);

            Bancos banco = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (!(banco == Bancos.SANTANDER || banco == Bancos.BANESPA_SANTANDER))
            {
                throw new Exception("Esta classe é valida apenas para o Santander");
            }
            else if (cContaDigitos.Length != 10)
            {
                throw new Exception("Erro na Conta não tem 10 dígitos");
            }
            else if (Cedente.CodCedente.Length != 7)
            {
                throw new Exception("Erro no CodCedente não tem 7 dígitos");
            }
            else if (Cedente.CedenteCOD.Length != 20)
            {
                throw new Exception("Erro no CedenteCOD não tem 20 dígitos");
            }
            else if (Cedente.Convenio.Length != 25)
            {
                throw new Exception("Erro no Convenio não tem 25 dígitos");
            }

            regArqHeader[CNAB400SantanderHeader.Empresa_Codigo] = Cedente.CedenteCOD;
            regArqHeader[CNAB400SantanderHeader.Empresa_Nome]   = Cedente.Cedente;
            regArqHeader[CNAB400SantanderHeader.Banco_Codigo]   = (int)banco;
            regArqHeader[CNAB400SantanderHeader.Data]           = DataHoje;

            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            // Inicia o contador Sequencial
            regArqHeader[CNAB400SantanderHeader.Sequencia] = SequencialRegistro = 1;

            // o sequencial do header é sempre 1 (FIXO)
            Add(regArqHeader);

            // Proximo item
            SequencialRegistro = 2;

            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB400SantanderRemessa1> regBoleto;

            double nValor = 0;

#if TEST_LOG
            Log += "Remessa " + Boletos.Count + "!\r\n";
#endif
            foreach (string n in Boletos.NossoNumeros)
            {
                boleto  = Boletos[n];
                sacado  = boleto.Sacado;
                nValor += boleto.ValorDocumento;
#if TEST_LOG
                Log += string.Format("{0} {1} {2:C}", n, boleto.NossoNumero, boleto.ValorDocumento);
#endif
                regBoleto = new Reg <CNAB400SantanderRemessa1>();

                regBoleto[CNAB400SantanderRemessa1.CedenteTipo]     = Cedente.Tipo;
                regBoleto[CNAB400SantanderRemessa1.CedenteCNPJ]     = Cedente.DocumentoNumeros;
                regBoleto[CNAB400SantanderRemessa1.CedenteCOD]      = Cedente.CedenteCOD;
                regBoleto[CNAB400SantanderRemessa1.CedenteControle] = Cedente.Convenio;
                regBoleto[CNAB400SantanderRemessa1.Banco]           = 33;
                regBoleto[CNAB400SantanderRemessa1.CarteiraTipo]    = Cedente.CarteiraTipo;
                regBoleto[CNAB400SantanderRemessa1.Agencia]         = Cedente.CarteiraTipo == "5" ? cAgDig[0] : "0";


                regBoleto[CNAB400SantanderRemessa1.NossoNumero] = boleto.NossoNumero;
#if TEST_LOG
                Log += string.Format(" ? {0} ? {1}\r\n", regBoleto[CNAB400SantanderRemessa1.NossoNumero], boleto.NossoNumero);
#endif
                regBoleto[CNAB400SantanderRemessa1.NossoNumeroDig]  = CobUtil.Modulo11Especial(boleto.NossoNumero, 9);
                regBoleto[CNAB400SantanderRemessa1.MultaTipo]       = boleto.PercentualMulta == 0 ? 0 : 4;
                regBoleto[CNAB400SantanderRemessa1.MultaPercentual] = boleto.PercentualMulta;
                regBoleto[CNAB400SantanderRemessa1.Ocorrencia]      = (int)boleto.Ocorrencia;
                regBoleto[CNAB400SantanderRemessa1.SeuNumero]       = boleto.BoletoID;
                regBoleto[CNAB400SantanderRemessa1.DataVencimento]  = boleto.DataVencimento;
                regBoleto[CNAB400SantanderRemessa1.Valor]           = boleto.ValorDocumento;
                regBoleto[CNAB400SantanderRemessa1.Especie]         = (int)boleto.Especie;
                regBoleto[CNAB400SantanderRemessa1.Aceite]          = boleto.Aceite;
                regBoleto[CNAB400SantanderRemessa1.DataDocumento]   = boleto.DataDocumento;

                int nInstrucao1 = boleto.Instrucao1;
                int nInstrucao2 = boleto.Instrucao2;

                if (nInstrucao1 == 0 && nInstrucao2 > 0)
                {
                    nInstrucao1 = nInstrucao2;
                    nInstrucao2 = 0;
                }

                // Prioriza protesto na instrução 1
                if (nInstrucao1 > 0)
                {
                    regBoleto[CNAB400SantanderRemessa1.Instrucao1] = nInstrucao1;
                    if (nInstrucao1 == 6)
                    {
                        if (boleto.DiasProtesto == 0)
                        {
                            throw new Exception("Não é possivel dar instrução de protesto sem 'DiasProtesto'");
                        }

                        regBoleto[CNAB400SantanderRemessa1.DiasProtesto] = boleto.DiasProtesto;
                    }
                }

                // Trata a mora na segunda instrução (Se tem Mora maior de 1 centavo adiciona a mora)
                if (boleto.ValorMora > 0.01)
                {
                    regBoleto[CNAB400SantanderRemessa1.Mora] = boleto.ValorMora;
                }
                else // Caso contrario não cobra
                {
                    if (nInstrucao1 == 0)
                    {
                        regBoleto[CNAB400SantanderRemessa1.Instrucao1] = 8;
                    }
                    else
                    {
                        regBoleto[CNAB400SantanderRemessa1.Instrucao2] = 8;
                    }
                }

                // Mas se a instrução 2 algo diferente adicona também, talvez sobrescrevendo...
                if (nInstrucao2 != 0)
                {
                    regBoleto[CNAB400SantanderRemessa1.Instrucao2] = nInstrucao2;
                }

                regBoleto[CNAB400SantanderRemessa1.DataDesconto]     = boleto.DataDesconto;
                regBoleto[CNAB400SantanderRemessa1.ValorIOF]         = boleto.ValorIOF;
                regBoleto[CNAB400SantanderRemessa1.ValorDesconto]    = boleto.ValorDesconto;
                regBoleto[CNAB400SantanderRemessa1.ValorAbatimento]  = boleto.ValorOutras < 0 ? -boleto.ValorOutras : 0;
                regBoleto[CNAB400SantanderRemessa1.Sacado_Tipo]      = sacado.Tipo;
                regBoleto[CNAB400SantanderRemessa1.Sacado_Inscricao] = sacado.DocumentoNumeros;
                regBoleto[CNAB400SantanderRemessa1.Nome]             = sacado.Sacado;
                regBoleto[CNAB400SantanderRemessa1.Endereco]         = sacado.Endereco;
                regBoleto[CNAB400SantanderRemessa1.Bairro]           = sacado.Bairro;
                regBoleto[CNAB400SantanderRemessa1.Cidade]           = sacado.Cidade;
                regBoleto[CNAB400SantanderRemessa1.UF]       = sacado.UF;
                regBoleto[CNAB400SantanderRemessa1.CEP]      = sacado.CepNumeros;
                regBoleto[CNAB400SantanderRemessa1.Avalista] = sacado.Avalista;

                regBoleto[CNAB400SantanderRemessa1.Complemento] = cContaDigitos.Substring(8, 2);
                regBoleto[CNAB400SantanderRemessa1.Sequencia]   = SequencialRegistro++;

                // adiciona o boleto convertido em registro
                AddBoleto(regBoleto, boleto);

                AddOpcionais(boleto);
            }

            regArqTrailer[CNAB400SantanderTrailer.Quantidade] = Boletos.NossoNumeros.Count;
            //regArqTrailer[CNAB400SantanderTrailer.Quantidade] = Boletos.NossoNumeros.Count + 2; // adicionando o proprio header e trailer
            regArqTrailer[CNAB400SantanderTrailer.Valor]     = nValor;
            regArqTrailer[CNAB400SantanderTrailer.Sequencia] = SequencialRegistro;

            Add(regArqTrailer);

            //ShowDumpLine = true;
            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 17
0
        public void Boleto_Banestes()
        {
            // Ainda de acordo com o exemplo em: https://github.com/impactro/Boleto-Test/wiki/Criando-Layouts/_edit

            // Dados do Pagador
            SacadoInfo s = new SacadoInfo()
            {
                Sacado = "Fabio Ferreira"
            };

            // Informações do Boleto
            BoletoInfo b = new BoletoInfo()
            {
                DataVencimento = DateTime.Parse("30/07/2000"),
                ValorDocumento = 75,
                NossoNumero    = "178"
            };

            // Cria uma instancia do objeto que calcula e monta um boleto
            Boleto bol = new Boleto();

            // Seta as variáveis (parametros) com os dados do recebedor (c), pagador (s), e as informações do boleto (b)
            bol.MakeBoleto(Cedente, s, b);

            // Calcula efetivamente o boleto
            bol.CalculaBoleto();

            // Imprime a linha digitável no console e alguns outros dados para conferencia
            Console.WriteLine("Linha Digitável: " + bol.LinhaDigitavel);
            Console.WriteLine("Agência/Conta: " + bol.AgenciaConta);
            Console.WriteLine("Nosso Número: " + bol.NossoNumeroExibicao);
            Console.WriteLine("Fator Vencimento: " + CobUtil.CalcFatVenc(bol.DataVencimento));

            // De acordo com a página 13 deve gerar exatamente a linha abaixo
            Assert.IsTrue(bol.LinhaDigitavel == "02190.00007 17800.006573 33154.021415 7 10270000007500"); // Página 38 da documentação
                                                                                                           // 02190.00007 17800.006573 33154.021415 3 10270000007500    // O exemplo está com o digito errado!
                                                                                                           // Salva a imagem do boleto para conferencia visual
                                                                                                           //bol.Save("boleto.png");

            // Baseado no segundo exemplo da página 34 (só vou especificar o que é realmente necessário)
            Console.WriteLine();
            bol = new Boleto(); // reseta tudo!
            CedenteInfo c = new CedenteInfo()
            {
                Banco      = "021-3",
                CodCedente = "7730070",
                Modalidade = "4"
            };

            // E reaproveiro a instancia (Alterando)
            b.DataVencimento = DateTime.Parse("09/12/2000");
            b.ValorDocumento = 131.50;
            b.NossoNumero    = "10297";

            bol.MakeBoleto(c, s, b);

            // Calcula efetivamente o boleto
            bol.CalculaBoleto();

            // Imprime a linha digitável no console e alguns outros dados para conferencia
            Console.WriteLine("Linha Digitável: " + bol.LinhaDigitavel);
            Console.WriteLine("Agência/Conta: " + bol.AgenciaConta);
            Console.WriteLine("Nosso Número: " + bol.NossoNumeroExibicao);
            Console.WriteLine("Fator Vencimento: " + CobUtil.CalcFatVenc(bol.DataVencimento));

            // De acordo com a página 13 deve gerar exatamente a linha abaixo
            Assert.IsTrue(bol.LinhaDigitavel == "02190.00106 29700.007734 00704.021823 3 11590000013150");
            // Note que o digito verificador é 3... acho que houve confusão na digitação da documentação
            // E este número retorna exatamente o informado na página 32: 021.9.3.1159.0000013150-0001029700007730070402182
        }
Ejemplo n.º 18
0
    // Neste primeiro exemplo o boleto será inserido como imagem embutida no HTML em base64
    protected void Page_Init(object sender, EventArgs e)
    {
        // Definição dos dados do cedente, que será comum para todos os boletos
        CedenteInfo Cedente = new CedenteInfo();

        Cedente.Cedente    = "outro cedente!";
        Cedente.Banco      = "237";
        Cedente.Agencia    = "1234-5";
        Cedente.Conta      = "123456-7";
        Cedente.Carteira   = "06";
        Cedente.Modalidade = "11";

        // Cria uma tabela em memoria
        DataTable tbDados = new DataTable();

        // Estrutura da tabela
        tbDados.Columns.Add("Nome", typeof(string));
        tbDados.Columns.Add("Vencimento", typeof(DateTime));
        tbDados.Columns.Add("Valor", typeof(double));
        tbDados.Columns.Add("NossoNumero", typeof(int));

        // Insere os dados
        tbDados.Rows.Add("Fábio", new DateTime(2015, 12, 30), 123.45, 345678);
        tbDados.Rows.Add("Érika", new DateTime(2015, 7, 25), 60, 12332);
        tbDados.Rows.Add("Milena", new DateTime(2015, 10, 20), 10.30, 234);
        tbDados.Rows.Add("Cecília", new DateTime(2015, 3, 4), 20.53, 456445);
        tbDados.Rows.Add("Roberto", new DateTime(2015, 6, 5), 32.78, 47319);
        tbDados.Rows.Add("Marcelo", DateTime.MinValue, 20320.23, 18445);
        tbDados.Rows.Add("Ricardo", DateTime.MinValue, 97023.51, 2465445);
        tbDados.Rows.Add("Maria", new DateTime(2016, 9, 12), 7890.23, 61756);
        tbDados.Rows.Add("Samara", new DateTime(2015, 8, 12), 78.1, 656);
        tbDados.Rows.Add("Marcio", new DateTime(2015, 2, 10), 790.3, 5672);

        int nBoleto = 0;

        foreach (DataRow row in tbDados.Rows)
        {
            // Instancia do 'Boleto', não o 'BoletoWeb', pois a ideia é renderizar imagem
            // O BoletoWeb usa a classe 'Boleto' para fazer todos os calculos, e depois desenha em html o boleto
            Boleto blt = new Boleto();
            blt.Carne = true; // Formato de Carne, neste exemplo será colocardo 3 boletos por página

            // Definição dos dados do sacado
            SacadoInfo Sacado = new SacadoInfo();
            Sacado.Sacado = (string)row["Nome"];

            // Definição das Variáveis do boleto
            BoletoInfo Boleto = new BoletoInfo();
            Boleto.DataVencimento  = (DateTime)row["Vencimento"];
            Boleto.ValorDocumento  = (double)row["Valor"];
            Boleto.NossoNumero     = row["NossoNumero"].ToString();
            Boleto.NumeroDocumento = Boleto.NossoNumero;

            // Calcula os dados do boleto
            blt.MakeBoleto(Cedente, Sacado, Boleto);

            // Obtem a imagem do boleto
            Bitmap img = blt.ImageBoleto();

            // Adiciona a imagem do boleto em base64 no HTML
            form1.Controls.Add(new LiteralControl(CobUtil.ToBase64ImageTag(img, ImageFormat.Png)));

            // incrementa o contador de boletos
            nBoleto++;
            if (nBoleto % 3 == 0) // Mas aplicar muito zoom pode dar problema na leitura do código de barras
            // somente nos boletos pares a iniciar de 2 força uma quebra de linha
            {
                form1.Controls.Add(new LiteralControl("<div style='page-break-after: always'><br/></div>"));
            }
            else //  if (nBoleto<tbDados.Rows.Count) // caso não queira imprimir a ultima imagem de tesoura
                 // nos boletos impares adiciona a imagem de recorte, ou um HR
                 // form1.Controls.Add(new LiteralControl("<img src='imagens/corte.gif' style='margin: 5px 0 5px 0;'/>"));
            {
                form1.Controls.Add(new LiteralControl("<hr size='1' style='color: gray; margin: 5px 0 5px 0;'/>"));
            }
        }
    }
Ejemplo n.º 19
0
        // Copiado diretamente
        public static Bitmap BarCodeImage(string NumTexto, int nScale, float resolucao = 600f)
        {
            // Transforma o numero em uma string padrão de barras
            string cCodBar = CobUtil.BarCode(NumTexto);

            if (nScale < 3)
            {
                throw new Exception("Escala minima é 3");
            }

            // Ajusta a Escala padrão
            //nScale /= 3; // Atenção, o ideal para a escala é ser multiplo de 3

            int wSF = nScale / 3;
            int wSL = nScale;

            // Codigo de Barras 2 por 5  =>  2 digitos são representados por 5 Barras PBPBP largas ou finas
            int nWidth = NumTexto.Length * 4 * nScale;

            Bitmap bmp = new Bitmap(nWidth, 50);

            bmp.SetResolution(resolucao, resolucao);
            Graphics g = Graphics.FromImage(bmp);

            g.Clear(Color.White);

            // Posição da linha atualmente desenhada (cursor)
            int nX = 0;

            for (int n = 0; n < cCodBar.Length; n += 2)
            {
                switch (cCodBar.Substring(n, 2))
                {
                case "bf":
                    g.FillRectangle(Brushes.White, nX, 0, wSF, 50);
                    nX += wSF;
                    break;

                case "pf":
                    g.FillRectangle(Brushes.Black, nX, 0, wSF, 50);
                    nX += wSF;
                    break;

                case "bl":
                    g.FillRectangle(Brushes.White, nX, 0, wSL, 50);
                    nX += wSL;
                    break;

                case "pl":
                    g.FillRectangle(Brushes.Black, nX, 0, wSL, 50);
                    nX += wSL;
                    break;
                }
            }

            // Extrai apenas a imagem 100% util
            Bitmap bmp2 = new Bitmap(nX, 50);

            bmp2.SetResolution(resolucao, resolucao);
            g = Graphics.FromImage(bmp2);
            g.DrawImage(bmp, 0, 0);

            return(bmp2);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gera o aquivo baseado nas coleção de todas informações passada até o momento
        /// </summary>
        /// <returns></returns>
        public override string Remessa()
        {
            string[] cAgDig = Cedente.Agencia.Split('-');
            string[] cCCDig = Cedente.Conta.Split('-');
            string[] cBanco = Cedente.Banco.Split('-');

            Bancos banco = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (banco != Bancos.BRADESCO)
            {
                throw new Exception("Esta classe é valida apenas para o Bradesco");
            }

            //if (Cedente.CedenteCOD.Length != 20)
            //    throw new Exception("Erro nas definições do Código da Empresa ('" + Cedente.CedenteCOD + "') verifique os dados do Cedente: Banco, Agencia, Conta, Cod.Cedente");

            // Adicionado por Alexandre Savelli Bencz
            if (Cedente.CodCedente.Length != 20)
            {
                Cedente.CodCedente = Cedente.CodCedente.PadLeft(20, '0');
            }

            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            // Proximo item
            SequencialRegistro = 1;

            regArqHeader[CNAB400Header1Bradesco.Empresa_Codigo] = Cedente.CedenteCOD;
            regArqHeader[CNAB400Header1Bradesco.Empresa_Nome]   = Cedente.Cedente;
            regArqHeader[CNAB400Header1Bradesco.Data]           = DataHoje;
            regArqHeader[CNAB400Header1Bradesco.Lote]           = NumeroLote; // atualiza o lote
            regArqHeader[CNAB400Header1Bradesco.Sequencia]      = SequencialRegistro++;

            // o sequencial do header é sempre 1 (FIXO)
            Add(regArqHeader);

            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB400Remessa1Bradesco> regBoleto;
            Reg <CNAB400Remessa2Bradesco> regBoleto2; // Adicionado por Alexandre Savelli Bencz

            foreach (string n in this.Boletos.NossoNumeros)
            {
                boleto = Boletos[n];
                sacado = boleto.Sacado;

                regBoleto = new Reg <CNAB400Remessa1Bradesco>();

                // 21-37: Identificação da Empresa Cedente no Banco
                regBoleto[CNAB400Remessa1Bradesco.Carteira] = Cedente.Carteira;
                regBoleto[CNAB400Remessa1Bradesco.Agencia]  = cAgDig[0];
                regBoleto[CNAB400Remessa1Bradesco.Conta]    = cCCDig[0];
                regBoleto[CNAB400Remessa1Bradesco.ContaDAC] = cCCDig[1];

                if (boleto.BoletoID > 0) // 38-62
                {
                    regBoleto[CNAB400Remessa1Bradesco.Identificacao] = boleto.BoletoID;
                }

                regBoleto[CNAB400Remessa1Bradesco.MultaTipo]       = boleto.PercentualMulta == 0 ? 0 : 2; // 66
                regBoleto[CNAB400Remessa1Bradesco.MultaPercentual] = boleto.PercentualMulta;              // 67

                // 71-82
                string cModalidade  = Cedente.Modalidade;
                string cNossoNumero = boleto.NossoNumero; // Primeiro prepara e calcula o DV para ajustar o nosso numero de acordo com a modalidade e carteira
                regBoleto[CNAB400Remessa1Bradesco.NossoNumeroDig] = Banco_Bradesco.NossoNumero(Cedente.Carteira, ref cModalidade, ref cNossoNumero);
                regBoleto[CNAB400Remessa1Bradesco.NossoNumero]    = cModalidade + cNossoNumero;

                regBoleto[CNAB400Remessa1Bradesco.Ocorrencia]      = (int)boleto.Ocorrencia;    // 109 - 01-Remessa
                regBoleto[CNAB400Remessa1Bradesco.NumeroDocumento] = boleto.NumeroDocumento;    // 111
                regBoleto[CNAB400Remessa1Bradesco.Vencimento]      = boleto.DataVencimento;     // 121
                regBoleto[CNAB400Remessa1Bradesco.ValorDocumento]  = boleto.ValorDocumento;     // 127
                regBoleto[CNAB400Remessa1Bradesco.Especie]         = (int)boleto.Especie;       // 148 - 01 - Duplicata Mercantil
                regBoleto[CNAB400Remessa1Bradesco.Aceite]          = boleto.Aceite;             // 150 - 'N' padrão
                regBoleto[CNAB400Remessa1Bradesco.Emissao]         = boleto.DataDocumento;      // 151
                regBoleto[CNAB400Remessa1Bradesco.Instrucao1]      = boleto.Instrucao1;         // 157
                regBoleto[CNAB400Remessa1Bradesco.Instrucao2]      = boleto.Instrucao2;         // 159
                regBoleto[CNAB400Remessa1Bradesco.Juros]           = boleto.ValorMora;          // 161
                if (boleto.ValorDesconto > 0)
                {
                    regBoleto[CNAB400Remessa1Bradesco.DescontoData]  = boleto.DataDesconto;                            // 174
                    regBoleto[CNAB400Remessa1Bradesco.DescontoValor] = boleto.ValorDesconto;                           // 180
                }
                regBoleto[CNAB400Remessa1Bradesco.Abatimento]      = boleto.ValorOutras < 0 ? -boleto.ValorOutras : 0; // 206
                regBoleto[CNAB400Remessa1Bradesco.SacadoTipo]      = sacado.Tipo;                                      // 219
                regBoleto[CNAB400Remessa1Bradesco.SacadoInscricao] = sacado.DocumentoNumeros;                          // 221
                regBoleto[CNAB400Remessa1Bradesco.Nome]            = sacado.Sacado;                                    // 235
                regBoleto[CNAB400Remessa1Bradesco.Endereco]        = sacado.Endereco;                                  // 275
                regBoleto[CNAB400Remessa1Bradesco.CEP]             = sacado.CepNumeros;                                // 332
                regBoleto[CNAB400Remessa1Bradesco.Avalista]        = sacado.Avalista;                                  // 335
                regBoleto[CNAB400Remessa1Bradesco.Sequencia]       = SequencialRegistro++;

                // adiciona o boleto convertido em registro
                AddBoleto(regBoleto, boleto);

                // Em breve por, padrão esse registro opcional será definido externamente

                // Adicionado por Alexandre Savelli Bencz
                // Gera o registro tipo 2 na remessa
                if (!string.IsNullOrEmpty(boleto.Instrucoes) ||
                    boleto.ValorDesconto2 != 0 ||
                    boleto.ValorDesconto3 != 0)
                {
                    var mensagens = new string[4] {
                        "", "", "", ""
                    };

                    var msgs = boleto.Instrucoes.Replace("\r", "").Replace("<br/>", "\n").Replace("<br>", "\n").Split('\n');
                    for (int i = 0; i < msgs.Length; i++)
                    {
                        mensagens[i] = msgs[i].Trim();
                    }

                    regBoleto2 = new Reg <CNAB400Remessa2Bradesco>();

                    regBoleto2[CNAB400Remessa2Bradesco.Mensagem1]           = mensagens[0];
                    regBoleto2[CNAB400Remessa2Bradesco.Mensagem2]           = mensagens[1];
                    regBoleto2[CNAB400Remessa2Bradesco.Mensagem3]           = mensagens[2];
                    regBoleto2[CNAB400Remessa2Bradesco.Mensagem4]           = mensagens[3];
                    regBoleto2[CNAB400Remessa2Bradesco.DataLimiteDesconto2] = boleto.DataLimiteDesconto2;
                    regBoleto2[CNAB400Remessa2Bradesco.ValorDesconto2]      = boleto.ValorDesconto2;
                    regBoleto2[CNAB400Remessa2Bradesco.DataLimiteDesconto3] = boleto.DataLimiteDesconto3;
                    regBoleto2[CNAB400Remessa2Bradesco.ValorDesconto3]      = boleto.ValorDesconto3;

                    regBoleto2[CNAB400Remessa2Bradesco.Carteira] = Cedente.Carteira;
                    regBoleto2[CNAB400Remessa2Bradesco.Agencia]  = cAgDig[0];
                    regBoleto2[CNAB400Remessa2Bradesco.Conta]    = cCCDig[0];
                    regBoleto2[CNAB400Remessa2Bradesco.ContaDAC] = cCCDig[1];

                    regBoleto2[CNAB400Remessa2Bradesco.NossoNumero]    = cModalidade + cNossoNumero;
                    regBoleto2[CNAB400Remessa2Bradesco.NossoNumeroDig] = Banco_Bradesco.NossoNumero(Cedente.Carteira, ref cModalidade, ref cNossoNumero);

                    regBoleto2[CNAB400Remessa2Bradesco.Sequencia] = SequencialRegistro++;

                    AddBoleto(regBoleto2, boleto);
                }

                AddOpcionais(boleto);
            }

            regArqTrailer[CNAB400ArquivoTrailer.Sequencia] = SequencialRegistro;
            Add(regArqTrailer);

            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 21
0
    protected void btnRun_Click(object sender, EventArgs e)
    {
        try
        {
            string[]  linhas = txtLayout.Text.Replace("\r", "").Split('\n');
            DataTable tb = new DataTable();
            int       n, c;
            DataRow   row;
            if (rblTipo.SelectedValue == "l")
            {
                int nColunas = CobUtil.GetInt(txtPrm.Text);
                if (nColunas < 4)
                {
                    ltrOut.Text = "É preciso ter pelo menos 4 campos: Nome, Comentário, Tamanho/Posições, Tipo";
                    return;
                }
                if (linhas.Length / nColunas < 3)
                {
                    ltrOut.Text = "O arquivo precisa conter pelo menos 3 registros alem do cabeçalho";
                    return;
                }

                for (n = 0; n < nColunas; n++)
                {
                    tb.Columns.Add(linhas[n], typeof(string));
                }

                row = tb.NewRow();
                n   = nColunas;
                c   = 0;
                while (n < linhas.Length)
                {
                    row[c] = linhas[n].Trim();
                    n++;
                    c++;
                    if (c == nColunas)
                    {
                        c = 0;
                        tb.Rows.Add(row);
                        row = tb.NewRow();
                    }
                }
                ltrOut.Text      = "OK";
                gvCSV.DataSource = tb;
                gvCSV.DataBind();

                string cFile = "layout-" + rblTipo.SelectedValue + ".csv";
                ltrOut.Text = "OK arquivo gerado: <a href='" + cFile + "' download>" + cFile + "</a>";
                string cCSV = CSV.TableCSV(tb, "|");
                File.WriteAllText(MapPath(cFile), cCSV);
            }
            else // por separador ... tipo csv...
            {
                if (linhas.Length < 3)
                {
                    ltrOut.Text = "O arquivo precisa conter pelo menos 3 registros alem do cabeçalho";
                    return;
                }

                char     sep      = txtPrm.Text[0];
                string[] col      = linhas[0].Split(sep);
                int      nColunas = col.Length;
                if (nColunas < 4)
                {
                    ltrOut.Text = "É preciso haver pelo menos os 4 campos basicos";
                    return;
                }

                for (c = 0; c < nColunas; c++)
                {
                    tb.Columns.Add(col[c], typeof(string));
                }

                n = 1;
                while (n < linhas.Length)
                {
                    col = CSV.SepararCampos(linhas[n], sep);
                    row = tb.NewRow();
                    for (c = 0; c < nColunas && c < col.Length; c++)
                    {
                        row[c] = col[c];
                    }

                    n++;
                    tb.Rows.Add(row);
                }
                ltrOut.Text      = "OK";
                gvCSV.DataSource = tb;
                gvCSV.DataBind();

                string cFile = "layout-" + rblTipo.SelectedValue + ".csv";
                ltrOut.Text = "OK arquivo gerado: <a href='" + cFile + "' download>" + cFile + "</a>";
                string cCSV = CSV.TableCSV(tb, "|");
                File.WriteAllText(MapPath(cFile), cCSV);
            }
        }
        catch (Exception ex)
        {
            ltrOut.Text = "<b>" + ex.Message + "</b><br/><pre>" + ex.StackTrace + "</pre>";
        }
    }
Ejemplo n.º 22
0
        public override string Remessa()
        {
            string[] cBanco = Cedente.Banco.Split('-');
            Bancos   banco  = (Bancos)CobUtil.GetInt(cBanco[0]);

            if (banco != Bancos.UniCred)
            {
                throw new Exception("Esta classe é valida apenas para o Banco UniCred");
            }

            // Proximo item
            SequencialRegistro = 1;

            regArqHeader[CNAB400HeaderUniCred.Conta]            = Cedente.CodCedente;
            regArqHeader[CNAB400HeaderUniCred.Empresa]          = Cedente.Cedente;
            regArqHeader[CNAB400HeaderUniCred.Data]             = DataHoje;
            regArqHeader[CNAB400HeaderUniCred.SequenciaArquivo] = NumeroLote;
            regArqHeader[CNAB400HeaderUniCred.Sequencia]        = SequencialRegistro++;
            // Limpa os objetos de saida/entrada
            Data.Clear();
            Clear();

            // o sequencial do header é sempre 1 (FIXO)
            Add(regArqHeader);

            string     cAgenciaNumero = Cedente.Agencia.Split('-')[0];
            string     cModalidade    = Cedente.Modalidade;
            string     cCodCedente    = Cedente.CodCedente;
            BoletoInfo boleto;
            SacadoInfo sacado;
            Reg <CNAB400Remessa1UniCred> regBoleto;

            foreach (string n in this.Boletos.NossoNumeros)
            {
                boleto = Boletos[n];
                sacado = boleto.Sacado;

                regBoleto = new Reg <CNAB400Remessa1UniCred>();

                string cNossoNumero = boleto.NossoNumero;
                //Banco_UniCred.MontaNossoNumero(ref cNossoNumero, ref cAgenciaNumero, ref cModalidade, ref cCodCedente, boleto.DataVencimento);

                regBoleto[CNAB400Remessa1UniCred.NumeroDocumento] = boleto.NumeroDocumento;
                regBoleto[CNAB400Remessa1UniCred.NossoNumero]     = cNossoNumero;
                regBoleto[CNAB400Remessa1UniCred.DataVencimento]  = boleto.DataVencimento;
                regBoleto[CNAB400Remessa1UniCred.ValorDocumento]  = boleto.ValorDocumento;
                regBoleto[CNAB400Remessa1UniCred.DataEmissao]     = boleto.DataDocumento;

                regBoleto[CNAB400Remessa1UniCred.Instrucao1]      = boleto.Instrucao1;
                regBoleto[CNAB400Remessa1UniCred.DataDesconto]    = boleto.DataDesconto;
                regBoleto[CNAB400Remessa1UniCred.ValorDesconto]   = boleto.ValorDesconto;
                regBoleto[CNAB400Remessa1UniCred.SacadoTipo]      = sacado.Tipo;
                regBoleto[CNAB400Remessa1UniCred.SacadoDocumento] = sacado.DocumentoNumeros;
                regBoleto[CNAB400Remessa1UniCred.Sacado]          = sacado.Sacado;
                regBoleto[CNAB400Remessa1UniCred.Endereco]        = sacado.Endereco;
                regBoleto[CNAB400Remessa1UniCred.CEP]             = sacado.CepNumeros;
                regBoleto[CNAB400Remessa1UniCred.Bairro]          = sacado.Bairro;
                regBoleto[CNAB400Remessa1UniCred.Cidade]          = sacado.Cidade;
                regBoleto[CNAB400Remessa1UniCred.UF]        = sacado.UF;
                regBoleto[CNAB400Remessa1UniCred.Sequencia] = SequencialRegistro++;

                // adiciona o boleto convertido em registro
                AddBoleto(regBoleto, boleto);

                AddOpcionais(boleto);
            }

            regArqTrailer[CNAB400Trailer1UniCred.Sequencia] = SequencialRegistro;
            Add(regArqTrailer);

            // Gera o Texto de saida da forma padrão
            return(this.Conteudo);
        }
Ejemplo n.º 23
0
        protected override void Render(HtmlTextWriter output)
        {
            if (RenderCountImage > 0)
            {
                output.Write("<center><div style='width: 650px;'>");

                Bitmap   img = Boleto.ImageBoleto();
                Graphics g;
                if (RenderCountImage == 1)
                {
                    output.Write(CobUtil.ToBase64ImageTag(img, ImageFormat.Png));
                }
                else
                {
                    Bitmap img1 = new Bitmap(img.Width / 2, img.Height);
                    g = Graphics.FromImage(img1);
                    g.DrawImage(img, 0, 0);
                    output.Write(CobUtil.ToBase64ImageTag(img1, ImageFormat.Png));

                    Bitmap img2 = new Bitmap(img.Width / 2, img.Height);
                    g = Graphics.FromImage(img2);
                    g.DrawImage(img, 0, 0, new Rectangle(img.Width / 2, 0, img.Width / 2, img.Height), GraphicsUnit.Pixel);
                    output.Write(CobUtil.ToBase64ImageTag(img2, ImageFormat.Png));
                }

                output.Write("</div></center>");
                return;
            }

            if (this.CssField == null)
            {
                this.CssField = "";
            }
            if (this.CssCell == null)
            {
                this.CssCell = "";
            }

            // blt.CalculaBoleto();

            string cLinhaDigitavel = blt.LinhaDigitavel;
            string cBarras         = CobUtil.BarCode(blt.CodigoBarras);

            // compatibilidade XHTML
            output.WriteLine("<div class='BoletoWeb'>");

            TableRow  row;
            TableCell cell;

            #region "Linha digitavel"

            Table tbLinha = new Table();
            tbLinha.CellPadding = 0;
            tbLinha.CellSpacing = 0;
            tbLinha.Width       = new Unit("640");

            row = new TableRow();

            cell = new TableCell();
            if (imageLogo == "")
            {
                cell.Text = String.Format("<img src='{0}' style='width:149px;height:38px;margin:1px'/>", GetImage(ImageGetType.Banco));
            }
            else
            {
                cell.Text = String.Format("<img src='{0}{1}' class='BoletoWebLogo' />", this.ImagePath, this.imageLogo);
            }
            cell.ColumnSpan = 3;
            row.Cells.Add(cell);

            cell               = new TableCell();
            cell.Text          = String.Format("<img src='{0}' width='2' height='30' align='right' />", GetImage(ImageGetType.p));
            cell.VerticalAlign = VerticalAlign.Bottom;
            row.Cells.Add(cell);

            cell = new TableCell();
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.VerticalAlign   = VerticalAlign.Bottom;
            cell.Style.Add("padding-bottom", "5px;");
            cell.Style.Add("font-size", "7pt");
            cell.Style.Add("font-family", "Verdana,Arial");
            cell.Text = "Banco<br/><font style='font-size: 11pt; font-weight: bold; font-family: Arial;'>" + blt.BancoCodigo + "</font>";
            row.Cells.Add(cell);

            cell = new TableCell();
            cell.VerticalAlign = VerticalAlign.Bottom;
            cell.Text          = String.Format("<img src='{0}' width='2' height='30' />", GetImage(ImageGetType.p));
            cell.Width         = new Unit("2px");
            row.Cells.Add(cell);

            cell                 = new TableCell();
            cell.CssClass        = this.CssField;
            cell.HorizontalAlign = HorizontalAlign.Right;
            cell.VerticalAlign   = VerticalAlign.Bottom;
            cell.Style.Add("padding-bottom", "5px;");
            cell.Wrap       = false;
            cell.Width      = new Unit("400");
            cell.ColumnSpan = 8;
            row.Cells.Add(cell);

            tbLinha.Rows.Add(row);

            if (blt.ExibeReciboLinhaDigitavel)
            {
                tbLinha.Rows[0].Cells[4].Text = BoletoTextos.Recibo + "<br/><font style='font-size: 11pt; font-weight: bold; font-family: Arial;'>" + cLinhaDigitavel + "</font>";
            }
            else
            {
                tbLinha.Rows[0].Cells[4].Text = BoletoTextos.Recibo;
            }

            #endregion

            // Recibo do Sacado
            #region "Boleto parte 1"

            if (blt.ExibeReciboSacado)
            {
                tbLinha.RenderControl(output);

                Table tbBol1 = new Table();
                tbBol1.Width = new Unit("640");
                if (ConfigureTable == null)
                {
                    tbBol1.BorderWidth = new Unit("1");
                    tbBol1.BorderStyle = BorderStyle.Solid;
                    tbBol1.GridLines   = GridLines.Both;
                    tbBol1.BorderColor = Color.Black;
                    tbBol1.CellPadding = 1;
                    tbBol1.CellSpacing = 0;
                }
                else
                {
                    ConfigureTable(tbBol1);
                }
#if NET2 || NET4
                tbBol1.Attributes.Add("bordercolordark", "#000000");
                tbBol1.Attributes.Add("bordercolorlight", "#000000");
#endif
                // Linha 1

                row = new TableRow();

                cell            = new TableCell();
                cell.ColumnSpan = 4;
                cell.Width      = new Unit("350");;
                cell.CssClass   = CssCell;
                cell.Text       = BoletoTextos.Cedente + ":<br/>" +
                                  "<font class=" + CssField + ">&nbsp;" +
                                  blt.Cedente +
                                  (" - " + blt.CedenteDocumento) +
                                  ("</font><br/><font class=" + CssCell + ">Endereço: </font><font class=" + CssField + ">" + blt.CedenteEndereco) + "</font>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.Width    = new Unit("160");;
                cell.Wrap     = false;
                cell.CssClass = CssCell;
                cell.Text     = BoletoTextos.CedenteConta + "<br/>" + "<div align=center class=" + CssField + ">&nbsp;" +
                                blt.AgenciaConta + "</div>";
                row.Cells.Add(cell);

                cell           = new TableCell();
                cell.Width     = new Unit("130");
                cell.CssClass  = CssCell;
                cell.BackColor = _CellEspecialColor;
                cell.Text      = "Vencimento<br>" + "<div align='right' class='" + CssField + "'";
                if (_CellEspecialSize > 0)
                {
                    cell.Text += "style='font-size:" + _CellEspecialSize.ToString() + "pt;'";
                }

                cell.Text += string.Format(">{0:dd/MM/yyyy}", blt.DataVencimento) + "</div>";
                row.Cells.Add(cell);

                tbBol1.Rows.Add(row);

                // Linha 2

                row = new TableRow();

                cell            = new TableCell();
                cell.CssClass   = CssCell;
                cell.ColumnSpan = 4;
                if (ExibeEnderecoReciboSacado)
                {
                    cell.Text = BoletoTextos.Sacado + "<br/>" + "<font class=" + CssField + ">" +
                                blt.SacadoCOD + (blt.SacadoCOD == "" ? "" : ": ") + blt.Sacado + " " + blt.SacadoDocumento + "<br>" +
                                blt.SacadoEndereco + "<br>" +
                                blt.Bairro + " - " + blt.Cidade + "<br>" +
                                "CEP: " + blt.Cep + " - " + blt.UF + "</font>";
                }
                else
                {
                    cell.Text = BoletoTextos.Sacado + "<br/>" + "<font class=" + CssField + ">&nbsp;" +
                                blt.Sacado + "</font>";
                }

                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "Nº Documento<br/>" + "<div align=center class=" + CssField + ">" +
                                blt.NumeroDocumento + "</div>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Wrap     = false;
                cell.Text     = "Nosso Número<br/>" + "<div align=right class=" + CssField + ">" +
                                blt.NossoNumeroExibicao + "</div>";
                row.Cells.Add(cell);

                tbBol1.Rows.Add(row);

                // Linha 3

                row = new TableRow();

                cell           = new TableCell();
                cell.CssClass  = CssCell;
                cell.BackColor = _CellEspecialColor;
                cell.Text      = "Espécie Moeda<br>" + "<font class=" + CssField + ">&nbsp;" +
                                 blt.MoedaEspecie + "</font>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "Parcela<br>" + "<div align=center class=" + CssField + ">&nbsp;" +
                                ((blt.ParcelaNumero == 0) ? "" : blt.ParcelaNumero.ToString() +
                                 ((blt.ParcelaTotal == 0) ? "" : " / " + blt.ParcelaTotal.ToString())) + "</div>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "Qtde Moeda<br>" + "<div align=center class=" + CssField + ">&nbsp;" +
                                ((blt.Quantidade == 0) ? "" : blt.Quantidade.ToString()) + "</div>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "(x)Valor<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                                ((blt.ValorUnitario == 0) ? "" : String.Format("{0:C}", blt.ValorUnitario)) + "</div>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "(-)Descontos/Abatim.<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                                ((blt.ValorDesconto == 0) ? "" : String.Format("{0:C}", blt.ValorDesconto)) + "</div>";
                row.Cells.Add(cell);

                cell           = new TableCell();
                cell.CssClass  = CssCell;
                cell.BackColor = _CellEspecialColor;
                cell.Text      = "(=)Valor Documento<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                                 String.Format("{0:C}", blt.ValorDocumento) + "</div>";
                row.Cells.Add(cell);

                tbBol1.Rows.Add(row);

                // Linha 5

                row = new TableRow();

                cell               = new TableCell();
                cell.CssClass      = CssCell;
                cell.VerticalAlign = VerticalAlign.Bottom;
                cell.ColumnSpan    = 4;
                cell.Text          = "Demonstrativo";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "(+)Outros Acréscimos<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                                ((blt.ValorAcrescimo == 0) ? "" : String.Format("{0:C}", blt.ValorAcrescimo)) + "</div>";
                row.Cells.Add(cell);

                cell          = new TableCell();
                cell.CssClass = CssCell;
                cell.Text     = "(=)Valor Cobrado<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                                ((blt.ValorCobrado == 0) ? "" : String.Format("{0:C}", blt.ValorCobrado)) + "</div>";
                row.Cells.Add(cell);

                tbBol1.Rows.Add(row);

                // Linha 6

                row = new TableRow();

                cell               = new TableCell();
                cell.CssClass      = CssCell;
                cell.VerticalAlign = VerticalAlign.Top;
                if (string.IsNullOrEmpty(blt.Demonstrativo))
                {
                    cell.Height = new Unit("20");
                }
                if (string.IsNullOrEmpty(blt.Demonstrativo))
                {
                    cell.Height = new Unit("50");
                }
                cell.ColumnSpan = 6;
                if (blt.Demonstrativo != null)
                {
                    cell.Text = "<div class=" + CssField + ">" + blt.Demonstrativo.Replace("\r\n", "<br/>") + "</div>";
                }
                row.Cells.Add(cell);

                tbBol1.Rows.Add(row);

                if (!string.IsNullOrEmpty(blt.Informacoes))
                {
                    row = new TableRow();

                    cell               = new TableCell();
                    cell.CssClass      = CssCell;
                    cell.VerticalAlign = VerticalAlign.Top;
                    cell.Height        = new Unit("50");
                    cell.ColumnSpan    = 6;
                    if (blt.Demonstrativo != null)
                    {
                        cell.Text = "<div class=" + CssField + " align='center'>" + blt.Informacoes.Replace("\r\n", "<br>") + "</div>";
                    }
                    row.Cells.Add(cell);

                    tbBol1.Rows.Add(row);
                }

                tbBol1.RenderControl(output);

                if (this.ImageCorte != "")
                {
                    output.Write("<img src='" + this.ImagePath + this.ImageCorte + "' class='BoletoWebCorte'>");
                }
                else
                {
                    output.Write("<img src='" + GetImage(ImageGetType.corte) + "' class='BoletoWebCorte'>");
                }

                output.Write("<br><br>");
            }

            #endregion

            tbLinha.Rows[0].Cells[0].Text = String.Format("<img src='{0}' style='width:149px;height:38px;margin:1px'/>", GetImage(ImageGetType.Banco));
            tbLinha.Rows[0].Cells[4].Text = "<font style='font-size: 11pt; font-weight: bold; font-family: Arial;'>" + cLinhaDigitavel + "</font>";
            tbLinha.RenderControl(output);

            // Boleto Padrão IPTE

            #region "Boleto Parte 2"

            Table tbBol2 = new Table();
            tbBol2.Width = new Unit("640");
            if (ConfigureTable == null)
            {
                tbBol2.BorderWidth = new Unit("1");
                tbBol2.BorderStyle = BorderStyle.Solid;
                tbBol2.GridLines   = GridLines.Both;
                tbBol2.BorderColor = Color.Black;
#if NET2 || NET4
                tbBol2.Attributes.Add("bordercolordark", "#000000");
                tbBol2.Attributes.Add("bordercolorlight", "#000000");
#endif
                tbBol2.CellPadding = 1;
                tbBol2.CellSpacing = 0;
            }
            else
            {
                ConfigureTable(tbBol2);
            }

            // Linha 1
            row = new TableRow();

            cell            = new TableCell();
            cell.CssClass   = CssCell;
            cell.Width      = new Unit("480");
            cell.ColumnSpan = 6;
            cell.Text       = "Local de pagamento<br>" + "<font class=" + CssField + ">&nbsp;" +
                              blt.LocalPagamento + "</font>";
            row.Cells.Add(cell);

            cell           = new TableCell();
            cell.CssClass  = CssCell;
            cell.Width     = new Unit("130");
            cell.BackColor = _CellEspecialColor;
            cell.Text      = "Vencimento<br>" + "<div align='right' class='" + CssField + "'";
            if (_CellEspecialSize > 0)
            {
                cell.Text += "style='font-size:" + _CellEspecialSize.ToString() + "pt;'";
            }

            cell.Text += string.Format(">{0:dd/MM/yyyy}", blt.DataVencimento) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 2
            row = new TableRow();

            cell            = new TableCell();
            cell.CssClass   = CssCell;
            cell.ColumnSpan = 6;
            cell.Text       = BoletoTextos.Cedente + ":<br/>" +
                              "<font class=" + CssField + ">&nbsp;" +
                              blt.Cedente +
                              (" - " + blt.CedenteDocumento) +
                              ("</font><br/><font class=" + CssCell + ">Endereço: </font><font class=" + CssField + ">" + blt.CedenteEndereco) + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Wrap     = false;
            cell.Text     = BoletoTextos.CedenteConta + "<br/>" + "<div align=right class=" + CssField + ">" +
                            blt.AgenciaConta + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 3

            row = new TableRow();

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Width    = new Unit("120");
            cell.Text     = "Data Documento<br>" + "<font class=" + CssField + ">&nbsp;" +
                            string.Format("{0:dd/MM/yyyy}", blt.DataDocumento) + "</font>";
            row.Cells.Add(cell);

            cell            = new TableCell();
            cell.CssClass   = CssCell;
            cell.Width      = new Unit("120");
            cell.ColumnSpan = 2;
            cell.Text       = "Nº Documento<br>" + "<font class=" + CssField + ">&nbsp;" +
                              blt.NumeroDocumento + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = BoletoTextos.EspecieDoc + "<br/>" + "<font class=" + CssField + ">&nbsp;" +
                            Boleto.Especie + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "Aceite<br>" + "<font class=" + CssField + ">&nbsp;" +
                            Boleto.Aceite + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Width    = new Unit("110");
            cell.Text     = _TextoDataProcessamento + "<br>" + "<font class=" + CssField + ">&nbsp;" +
                            string.Format("{0:dd/MM/yyyy}", blt.DataProcessamento) + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Wrap     = false;
            cell.Text     = "Nosso Número<br>" + "<div align=right class=" + CssField + ">" +
                            blt.NossoNumeroExibicao + "</div>";
            row.Cells.Add(cell);
            tbBol2.Rows.Add(row);

            // Linha 4

            row = new TableRow();

            cell          = new TableCell();
            cell.CssClass = CssCell;
            if (blt.CIP != "") // quando houve o campo
            {
                cell.Text = "Uso do Banco<br>" + "<font class=" + CssField + ">&nbsp;" +
                            blt.UsoBanco + " CIP: " + blt.CIP + "</font>";
                row.Cells.Add(cell);
                cell = new TableCell();
            }
            else
            {
                cell            = new TableCell();
                cell.ColumnSpan = 2;
            }
            cell.CssClass = CssCell;
            cell.Text     = "Carteira<br>" + "<font class=" + CssField + ">&nbsp;" +
                            blt.CarteiraExibicao + "</font>";
            row.Cells.Add(cell);

            cell           = new TableCell();
            cell.CssClass  = CssCell;
            cell.BackColor = _CellEspecialColor;
            cell.Text      = "Espécie<br>" + "<font class=" + CssField + ">&nbsp;" +
                             blt.MoedaEspecie + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "Parcela<br>" + "<div align=center class=" + CssField + ">&nbsp;" +
                            ((blt.ParcelaNumero == 0) ? "" : blt.ParcelaNumero.ToString() +
                             ((blt.ParcelaTotal == 0) ? "" : " / " + blt.ParcelaTotal.ToString())) + "</div>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "Qtde Moeda<br>" + "<font class=" + CssField + ">&nbsp;" +
                            ((blt.Quantidade == 0) ? "" : blt.Quantidade.ToString()) + "</font>";
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "(x)Valor<br>" + "<font class=" + CssField + ">&nbsp;" +
                            ((blt.ValorUnitario == 0) ? "" : String.Format("{0:C}", blt.ValorUnitario)) + "</font>";
            row.Cells.Add(cell);

            cell           = new TableCell();
            cell.CssClass  = CssCell;
            cell.BackColor = _CellEspecialColor;
            cell.Text      = "(=)Valor Documento<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                             String.Format("{0:C}", blt.ValorDocumento) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 5

            row = new TableRow();

            cell               = new TableCell();
            cell.CssClass      = CssCell;
            cell.ColumnSpan    = 6;
            cell.RowSpan       = 5;
            cell.VerticalAlign = VerticalAlign.Top;
            if (blt.Instrucoes != null)
            {
                cell.Text = BoletoTextos.Instrucoes + "<br/>" + "<font class=" + CssField + ">" +
                            blt.Instrucoes.Replace("\r\n", "<br/>") + "</font>";
            }
            row.Cells.Add(cell);

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "(-)Descontos/Abatim.<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                            ((blt.ValorDesconto == 0) ? "" : String.Format("{0:C}", blt.ValorDesconto)) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 6

            row = new TableRow();

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "(-)Outras Deduções<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                            ((blt.ValorOutras == 0) ? "" : String.Format("{0:C}", blt.ValorOutras)) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 7

            row = new TableRow();

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "(+)Mora/Multa<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                            ((blt.ValorMoraMulta == 0) ? "" : String.Format("{0:C}", blt.ValorMoraMulta)) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 8

            row = new TableRow();

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "(+)Outros Acréscimos<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                            ((blt.ValorAcrescimo == 0) ? "" : String.Format("{0:C}", blt.ValorAcrescimo)) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 9

            row = new TableRow();

            cell          = new TableCell();
            cell.CssClass = CssCell;
            cell.Text     = "(=)Valor Cobrado<br>" + "<div align=right class=" + CssField + ">&nbsp;" +
                            ((blt.ValorCobrado == 0) ? "" : String.Format("{0:C}", blt.ValorCobrado)) + "</div>";
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            // Linha 9

            row = new TableRow();

            cell               = new TableCell();
            cell.CssClass      = CssCell;
            cell.Height        = new Unit("70");
            cell.ColumnSpan    = 7;
            cell.VerticalAlign = VerticalAlign.Top;
            if (blt.SacadoEndereco == "")
            {
                cell.Text = BoletoTextos.Sacado + "<br/>" + "<font class=" + CssField + ">" +
                            blt.SacadoCOD + (blt.SacadoCOD == "" ? "" : ": ") + blt.Sacado + " " + blt.SacadoDocumento + "</font>";
            }
            else
            {
                cell.Text = BoletoTextos.Sacado + "<br/>" + "<font class=" + CssField + ">" +
                            blt.SacadoCOD + (blt.SacadoCOD == "" ? "" : ": ") + blt.Sacado + " " + blt.SacadoDocumento + "<br>" +
                            blt.SacadoEndereco + "<br>" +
                            blt.Bairro + " - " + blt.Cidade + "<br>" +
                            "CEP: " + blt.Cep + " - " + blt.UF + "</font>";
            }
            row.Cells.Add(cell);

            tbBol2.Rows.Add(row);

            tbBol2.RenderControl(output);

            #endregion

            // Código de Barras

            #region "Separador / Autenticação"

            Table tbFicha = new Table();
            tbFicha.CellPadding = 0;
            tbFicha.CellSpacing = 0;
            tbFicha.Width       = new Unit("640");

            row = new TableRow();

            cell          = new TableCell();
            cell.Text     = (blt.Avalista == "") ? "" : (BoletoTextos.Avalista + ": ") + blt.Avalista;
            cell.CssClass = this.cssCell;
            row.Cells.Add(cell);

            cell                 = new TableCell();
            cell.Text            = "Autenticação Mecânica - FICHA DE COMPENSAÇÃO";
            cell.CssClass        = this.cssCell;
            cell.HorizontalAlign = HorizontalAlign.Right;
            row.Cells.Add(cell);

            tbFicha.Rows.Add(row);
            tbFicha.RenderControl(output);

            //output.Write("<table border=1 width='640'><tr><td class='" + this.CssCell + "'>" +
            //    ((blt.Avalista == "") ? "" : (BoletoTextos.Avalista + ": ") + blt.Avalista) +
            //    "</td><td align=right class=" + this.CssCell + ">");
            //output.Write("Autenticação Mecânica - FICHA DE COMPENSAÇÃO</td></tr></table>");
            //output.Write("<table border=1 width='640'><tr><td>");

            #endregion

            #region "Código de barras"

            Table tbcodBar = new Table();
            tbcodBar.CellPadding = 0;
            tbcodBar.CellSpacing = 0;
            tbcodBar.Width       = new Unit("640");

            row  = new TableRow();
            cell = new TableCell();

            if (_BarCod == "")
            {
                StringBuilder sb = new StringBuilder();
                string        cP = GetImage(ImageGetType.p);
                string        cB = GetImage(ImageGetType.b);
                for (int i = 0; i < cBarras.Length; i += 2)
                {
                    switch (cBarras.Substring(i, 2))
                    {
                    case "bf":
                        if (imgCodBar)
                        {
                            sb.Append("<img src='" + cB + "' border='0' height='50' width='1' />");
                        }
                        else
                        {
                            sb.Append("<div style='display:inline-block;height:50px;width:1px;background-color:fff;'></div>");
                        }
                        break;

                    case "pf":
                        if (imgCodBar)
                        {
                            sb.Append("<img src='" + cP + "' border='0' height='50' width='1' />");
                        }
                        else
                        {
                            sb.Append("<div style='display:inline-block;height:50px;width:1px;background-color:000;'></div>");
                        }
                        break;

                    case "bl":
                        if (imgCodBar)
                        {
                            sb.Append("<img src='" + cB + "' border='0' height='50' width='3' />");
                        }
                        else
                        {
                            sb.Append("<div style='display:inline-block;height:50px;width:3px;background-color:fff;'></div>");
                        }
                        break;

                    case "pl":
                        if (imgCodBar)
                        {
                            sb.Append("<img src='" + cP + "' border='0' height='50' width='3' />");
                        }
                        else
                        {
                            sb.Append("<div style='display:inline-block;height:50px;width:3px;background-color:000;'></div>");
                        }
                        break;
                    }
                }
                cell.Text = sb.ToString();
            }
            else
            {
                cell.Text = string.Format("<img src='{0}' border='0' />", _BarCod);
            }

            row.Cells.Add(cell);
            tbcodBar.Rows.Add(row);

            if (!string.IsNullOrEmpty(blt.Informacoes))
            {
                //    output.Write("<tr><td align='center'>" + blt.Informacoes + "</td></tr>");

                row                  = new TableRow();
                cell                 = new TableCell();
                cell.CssClass        = CssField;
                cell.HorizontalAlign = HorizontalAlign.Center;

                cell.Text = blt.Informacoes;
                row.Cells.Add(cell);
                tbcodBar.Rows.Add(row);
            }

            //output.Write("</table>");

            tbcodBar.RenderControl(output);

            #endregion

            output.WriteLine("</div>");
        }