Пример #1
0
        private CFDi getCFDiFromReader(SqlDataReader rdr)
        {
            var fac = new CFDi();

            fac.idFolio                            = rdr.GetInt32(0);
            fac.serie                              = rdr.GetValue(1).ToString();
            fac.folio                              = rdr.GetInt32(2);
            fac.estadoFolio                        = rdr.GetValue(3).ToString();
            fac.tipoCompra                         = rdr.GetValue(4).ToString();
            fac.emisor                             = new Emisor();
            fac.emisor.unidadOperativa             = new UnidadOperativa();
            fac.emisor.unidadOperativa.razonSocial = new RazonSocial
            {
                razonSocial = rdr.GetValue(5).ToString(),
                rfc         = rdr.GetValue(6).ToString()
            };
            fac.receptor = new Receptor {
                informacionFiscal = new InformacionFiscal
                {
                    razonSocial = rdr.GetValue(7).ToString(),
                    rfc         = rdr.GetValue(8).ToString()
                }
            };
            fac.subtotal            = double.Parse(rdr.GetValue(9).ToString());
            fac.totalImp            = double.Parse(rdr.GetValue(10).ToString());
            fac.total               = double.Parse(rdr.GetValue(11).ToString());
            fac.folioFiscal         = rdr.GetString(12);
            fac.fechaCert           = rdr.GetDateTime(13);
            fac.fecha               = rdr.GetDateTime(14);
            fac.NoCertificadoEmisor = rdr.GetString(15);
            return(fac);
        }
Пример #2
0
        public void cancelarTimbre(CFDi cfdi)
        {
            SqlConnection cnn = DBConnectionFactory.GetOpenConnection();
            SqlCommand    cmd = new SqlCommand("PG_UP_CANCELAR_FACTURA", cnn);

            cmd.Transaction = cnn.BeginTransaction("CfdiTransaction");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PP_L_DEBUG", 0);
            cmd.Parameters.AddWithValue("@PP_K_SISTEMA_EXE", 1);
            cmd.Parameters.AddWithValue("@PP_K_USUARIO", 0);
            /////////////////////////////////////////////////
            cmd.Parameters.AddWithValue("@PP_SERIE", cfdi.serie);
            cmd.Parameters.AddWithValue("@PP_FOLIO", cfdi.folio);
            try
            {
                SqlDataReader reader = cmd.ExecuteReader();
                reader.Close();
                cmd.Transaction.Commit();
            }
            catch (Exception e)
            {
                logger.Error(e);
                cmd.Transaction.Rollback();
                throw e;
            }
            finally
            {
                cnn.Dispose();
                cmd.Dispose();
            }
        }
Пример #3
0
        public CFDi GetFactura(int idFactura)
        {
            SqlConnection cnn = DBConnectionFactory.GetOpenConnection();
            SqlCommand    cmd = new SqlCommand("PG_SK_FACTURA_DETALLE", cnn);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PP_ID_FACTURA", idFactura);
            SqlDataReader rdr = cmd.ExecuteReader();
            var           fac = new CFDi();

            try
            {
                if (!rdr.HasRows)
                {
                    throw new NotFoundException("No se han encontrado facturas");
                }
                while (rdr.Read())
                {
                    fac = getCFDiFromReader(rdr);
                }
                return(fac);
            }
            catch (Exception e)
            {
                logger.Error(e, e.Message);
                throw e;
            }
            finally
            {
                rdr.Close();
                cmd.Dispose();
                cnn.Close();
            }
        }
Пример #4
0
        private void createCFDI(CFDi cfdi)
        {
            //logger.Info("Proceso de timbrado iniciado. Emisor: " + cfdi.emisor.unidadOperativa.razonSocial.rfc + "; Receptor: " + cfdi.receptor.informacionFiscal.rfc);
            EmisorDAO    emisorDAO = new EmisorDAO();
            ConceptosDAO conDAO    = new ConceptosDAO();
            CFDiDAO      cfdiDAO   = new CFDiDAO();
            UsuarioDAO   uDAO      = new UsuarioDAO();
            Calculador   calc      = new Calculador();

            //if (cfdi.pagos != null && cfdi.pagos.doctoRelacionados != null && cfdi.pagos.doctoRelacionados.Length > 0)
            //{
            //    getDoctoRelacionados(cfdi.pagos.doctoRelacionados, cfdiDAO);
            //}
            cfdi.emisor = emisorDAO.GetIssuerInfo(cfdi.emisor.unidadOperativa.idUnidadOperativa,
                                                  cfdi.tipoCompra.Substring(0, 1));
            cfdi.emisor.certificado         = emisorDAO.GetIssuerCertInfo(cfdi.emisor.unidadOperativa.razonSocial.idRazonSocial);
            cfdi.receptor.usuario           = uDAO.getUsuario(cfdi.receptor.usuario.id);
            cfdi.receptor.informacionFiscal = uDAO.getUsuarioFiscales(cfdi.receptor.usuario.id);
            cfdi.conceptos = conDAO.getConceptos(cfdi.idMov, cfdi.emisor.unidadOperativa.idUnidadOperativa);
            //if(cfdi.conceptos[0].fecha.ToString("yyyy/MM/dd").Equals(DateTime.Now.ToString("yyyy/MM/dd")))
            //{
            //    throw new SameDayInvoiceException("No puedes hacer la factura el mismo día de la compra");
            //}
            //if(!cfdi.conceptos[0].fecha.ToString("yyyy/MM/dd").Equals(cfdi.fecha.ToString("yyyy/MM/dd")))
            //{
            //    throw new InvoiceDateMismatchException("La fecha que has ingresado no coincide con la fecha de la compra");
            //}
            //if(DateTime.Now.Subtract(cfdi.conceptos[0].fecha).TotalDays >= 15)
            //{
            //    throw new ExpiredInvoiceException("Solo puedes facturar hasta 15 dias después de la compra");
            //}
            //Validar si los conceptos no han sido facturados
            calc.calcularDescuentosConceptos(cfdi.conceptos);
            calc.calcularImpuestoConceptos(cfdi.conceptos, cfdi.emisor.unidadOperativa);
            calc.calcularTotal(cfdi);
            cfdi.importeLetra = ConvertidorImporte.enletras(cfdi.total, cfdi.moneda);
            cfdi.fechaCert    = DateTime.Now;
            cfdiDAO.saveCFDI(cfdi, true);
            if (cfdi.folio > 0)
            {
                CfdiXmlBuilder xmlBuilder = new CfdiXmlBuilder();
                cfdi.xml = xmlBuilder.BuildXml(cfdi);

                cfdiDAO.saveCFDI(cfdi, false);
                //timbrarFacturaWS(cfdi);
                //xmlBuilder.obtenerDatosTimbre(cfdi);
                cfdiDAO.saveCFDI(cfdi, false);
                logger.Info("Cadena original del complemento de certificacion digital del SAT: " + cfdi.cadenaCertificadoSat);
                sendMail(cfdi);
            }
            else
            {
                throw new InvalidCfdiDataException("No fue posible guardar los datos de la factura");
            }
        }
Пример #5
0
 public void Timbrar(CFDi cfdi)
 {
     cfdi.mPago     = "PUE";
     cfdi.moneda    = "MXN";
     cfdi.tipoVenta = "DEBITO";
     cfdi.formaPago = "99";
     if (cfdi.emisor.serie != null && cfdi.emisor.serie != "" && cfdi.folio > 0 && cfdi.idFolio > 0)
     {
         validateCFDI(cfdi);
     }
     else
     {
         createCFDI(cfdi);
     }
 }
Пример #6
0
        public CFDi cancelarTimbre(CFDi cfdi)
        {
            logger.Info("Proceso de cancelación de factura iniciado. Serie: " + cfdi.serie + "; Folio: " + cfdi.folio);
            CFDiDAO cfdiDAO = new CFDiDAO();

            if (!cfdiDAO.validateInvoiceStatus(cfdi.serie, cfdi.folio))
            {
                throw new InvalidInvoiceStatusException("El estatus actual de la factura no permite cancelar");
            }
            cfdi = cfdiDAO.getInvoiceInfo(cfdi.serie, cfdi.folio);
            CfdiXmlBuilder builder = new CfdiXmlBuilder();

            cfdi.xml = builder.BuildCancelacionXml(cfdi);
            //WS cancelar
            timbrarFacturaWS(cfdi);
            cfdiDAO.cancelarTimbre(cfdi);
            return(cfdi);
        }
Пример #7
0
        private void validateCFDI(CFDi cfdi)
        {
            CFDiDAO cfdiDAO = new CFDiDAO();

            cfdi.xml = cfdiDAO.getCFDIXml(cfdi.idFolio);
            if (cfdi.xml != null && cfdi.xml != "")
            {
                CfdiXmlBuilder xmlBuilder = new CfdiXmlBuilder();
                xmlBuilder.obtenerDatosTimbre(cfdi);
                if (cfdi.folioFiscal != null && cfdi.folioFiscal.Length == 36)
                {
                    sendMail(cfdi);
                }
                else
                {
                    createCFDI(cfdi);
                }
            }
        }
Пример #8
0
        public CFDi getInvoiceInfo(string serie, int folio)
        {
            CFDi          cfdi = new CFDi();
            SqlConnection cnn  = DBConnectionFactory.GetOpenConnection();
            SqlCommand    cmd  = new SqlCommand("PG_SK_FACTURA_INFO", cnn);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PP_L_DEBUG", 0);
            cmd.Parameters.AddWithValue("@PP_K_SISTEMA_EXE", 1);
            cmd.Parameters.AddWithValue("@PP_SERIE", serie);
            cmd.Parameters.AddWithValue("@PP_FOLIO", folio);
            SqlDataReader reader = cmd.ExecuteReader();

            if (!reader.HasRows)
            {
                throw new InvalidInvoiceNumberException("Serie y/o Folio invalidos");
            }
            reader.Read();
            cfdi.emisor = new Emisor
            {
                unidadOperativa = new UnidadOperativa
                {
                    razonSocial = new RazonSocial
                    {
                        rfc = reader.GetValue(0).ToString()
                    }
                }
            };
            cfdi.receptor = new Receptor
            {
                informacionFiscal = new InformacionFiscal
                {
                    rfc = reader.GetValue(1).ToString()
                }
            };
            cfdi.folioFiscal = reader.GetValue(2).ToString();
            cfdi.total       = double.Parse(reader.GetValue(3).ToString());
            cfdi.serie       = serie;
            cfdi.folio       = folio;
            cnn.Dispose();
            reader.Close();
            return(cfdi);
        }
Пример #9
0
        public void calcularTotal(CFDi cfdi)
        {
            double subtotal  = 0.0d;
            double totalDesc = 0.0d;
            double totalImp  = 0.0d;

            foreach (Concepto concepto in cfdi.conceptos)
            {
                subtotal  += concepto.importe;
                totalDesc += concepto.descuento;
                foreach (Impuesto impuesto in concepto.impuestos)
                {
                    totalImp += impuesto.importe;
                }
            }
            cfdi.subtotal = subtotal;
            cfdi.totalImp = totalImp;
            cfdi.total    = subtotal - totalDesc + totalImp;
        }
Пример #10
0
        public IActionResult Post(CFDi cfdi)
        {
            TimbradoService service = new TimbradoService();
            var             results = new Dictionary <string, Object>();

            try
            {
                cfdi = service.cancelarTimbre(cfdi);
                results.Add("cfdi", cfdi);
                return(Ok(results));
            }
            catch (Exception e)
            {
                if (e is CancellationException || e is InvalidInvoiceNumberException || e is WebServiceCommunicationException)
                {
                    results.Add("message", e.Message);
                    return(BadRequest(results));
                }
                results.Add("message", "Error en el servidor");
                return(StatusCode(500, results));
            }
        }
Пример #11
0
        public IActionResult Post(CFDi cfdi)
        {
            var results = new Dictionary <string, Object>();

            try
            {
                TimbradoService timService = new TimbradoService();
                timService.Timbrar(cfdi);
                results.Add("cfdi", cfdi);
                return(Ok(results));
            }
            catch (Exception e)
            {
                if (e is InvalidRFCException || e is NotFoundException)
                {
                    results.Add("message", e.Message);
                    return(NotFound(results));
                }
                if (e is CertificateException || e is InvoiceNumberAvailabilityException)
                {
                    results.Add("message", e.Message);
                    return(Conflict(results));
                }
                if (e is InvalidCfdiDataException || e is WebServiceValidationException ||
                    e is WebServiceCommunicationException || e is InvalidInvoiceTypeException ||
                    e is InvoiceAtZeroException || e is PaymentGreaterThanBalanceException ||
                    e is InvalidInvoiceTypeException || e is InvoiceAtZeroException ||
                    e is SameDayInvoiceException || e is InvoiceDateMismatchException ||
                    e is ExpiredInvoiceException)
                {
                    results.Add("message", e.Message);
                    return(BadRequest(results));
                }
                logger.Error(e.Message);
                results.Add("message", "Error en el servidor");
                return(StatusCode(500, results));
            }
        }
Пример #12
0
        public void timbrarFacturaWS(CFDi cfdi)
        {
            string xml      = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cfdi.xml));
            string user     = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("UserGTomzaWS"));
            string password = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("WSTomza20."));

            try
            {
                generaCFDIPortType generaCFDiService = new generaCFDIPortTypeClient();
                respuestaTimbrado  respuestaTimbre   = new respuestaTimbrado();

                respuestaTimbre = generaCFDiService.generaCFDIAsync(user, password, xml).GetAwaiter().GetResult();

                validarRespuesta(respuestaTimbre);

                cfdi.xml = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(respuestaTimbre.documentoProcesado));
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw new WebServiceCommunicationException("Error desconocido de comunicación");
            }
        }
Пример #13
0
        private void sendMail(CFDi cfdi)
        {
            Stream xmlStream = StreamBuilder.getStreamFromString(cfdi.xml);

            new PDFbuilder().PDFgenerate(cfdi);
            string pdfPath = File.Exists("C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.serie + cfdi.folio + ".pdf") ? "C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.serie + cfdi.folio + ".pdf" : null;

            //if (File.Exists("C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.emisor.unidadOperativa.razonSocial.rfc + ".pdf"))
            //{
            //    File.Delete("C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.emisor.unidadOperativa.razonSocial.rfc + ".pdf");
            //}
            cfdi.xml = null;
            cfdi.emisor.certificado = null;
            Thread mailingThread = new Thread(
                delegate()
            {
                MailSender.sendMail("Factura electrónica", new string[1] {
                    cfdi.receptor.usuario.correo
                }, xmlStream, pdfPath);
            }
                );

            mailingThread.Start();
        }
Пример #14
0
        public void saveCFDI(CFDi cfdi, bool guardarConceptos)
        {
            SqlConnection cnn = DBConnectionFactory.GetOpenConnection();
            SqlCommand    cmd = new SqlCommand("PG_SV_CERTCERTIFICADO_INFO", cnn);

            cmd.Transaction = cnn.BeginTransaction("CfdiTransaction");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PP_L_DEBUG", 0);
            cmd.Parameters.AddWithValue("@PP_K_SISTEMA_EXE", 1);
            cmd.Parameters.AddWithValue("@PP_K_USUARIO", 0);
            //////////////////////////////////////////////////////////////
            cmd.Parameters.AddWithValue("@PP_ID_FACTURA", cfdi.idFolio).Direction = ParameterDirection.InputOutput;
            cmd.Parameters.AddWithValue("@PP_FOLIO", cfdi.folio).Direction        = ParameterDirection.InputOutput;
            cmd.Parameters.AddWithValue("@PP_K_RAZON_SOCIAL", cfdi.emisor.unidadOperativa.razonSocial.idRazonSocial);
            cmd.Parameters.AddWithValue("@PP_K_UNIDAD_OPERATIVA", cfdi.emisor.unidadOperativa.idUnidadOperativa);
            cmd.Parameters.AddWithValue("@PP_FOLIO_FISCAL", cfdi.folioFiscal == null? "" : cfdi.folioFiscal);
            cmd.Parameters.AddWithValue("@PP_NOMBRE_RECEPTOR", cfdi.receptor.informacionFiscal.razonSocial);
            cmd.Parameters.AddWithValue("@PP_RFC_RECEPTOR", cfdi.receptor.informacionFiscal.rfc);
            cmd.Parameters.AddWithValue("@PP_EMAIL", cfdi.receptor.usuario.correo);
            cmd.Parameters.AddWithValue("@PP_TIPO_COMPROBANTE", "I");//cfdi.tipoCompra.Substring(0, 1));
            cmd.Parameters.AddWithValue("@PP_USO_CFDI", cfdi.usoCFDi);
            cmd.Parameters.AddWithValue("@PP_SERIE", cfdi.emisor.serie == null ? "" : cfdi.emisor.serie);
            cmd.Parameters.AddWithValue("@PP_K_ESTATUS_FACTURA", guardarConceptos? 1 : 3);
            cmd.Parameters.AddWithValue("@PP_FECHA_CERTIFICACION", cfdi.fechaCert);
            cmd.Parameters.AddWithValue("@PP_FECHA_EMISION", cfdi.fecha);
            cmd.Parameters.AddWithValue("@PP_NO_CERTIFICADO_SAT", cfdi.NoCertificadoSat == null ? "" : cfdi.NoCertificadoSat);
            cmd.Parameters.AddWithValue("@PP_FORMA_PAGO", "99");   //cfdi.formaPago);
            cmd.Parameters.AddWithValue("@PP_NO_CERTIFICADO_EMISOR", cfdi.NoCertificadoEmisor == null ? "" : cfdi.NoCertificadoEmisor);
            cmd.Parameters.AddWithValue("@PP_METODO_PAGO", "PUE"); //cfdi.mPago);
            cmd.Parameters.AddWithValue("@PP_SUB_TOTAL", cfdi.subtotal);
            cmd.Parameters.AddWithValue("@PP_SUBTOTAL_IVA", 0.0);
            cmd.Parameters.AddWithValue("@PP_TOTAL_IVA", cfdi.totalImp);
            cmd.Parameters.AddWithValue("@PP_TOTAL", cfdi.total);
            cmd.Parameters.AddWithValue("@PP_SALDO", 0.0d); //cfdi.mPago == "PPD" ? cfdi.total : 0.0d);
            cmd.Parameters.AddWithValue("@PP_IMPORTE_LETRA", cfdi.importeLetra);
            cmd.Parameters.AddWithValue("@PP_CADENA_CERTIFICADO_SAT", cfdi.cadenaCertificadoSat == null ? "" : cfdi.cadenaCertificadoSat);
            cmd.Parameters.AddWithValue("@PP_SELLO_DIGITAL_EMISOR", cfdi.selloEmisor == null ? "" : cfdi.selloEmisor);
            cmd.Parameters.AddWithValue("@PP_SELLO_DIGITAL_SAT", cfdi.selloSat == null ? "" : cfdi.selloSat);
            cmd.Parameters.AddWithValue("@PP_RFC_PROV_CERTIF", cfdi.RfcProvCertif == null ? "" : cfdi.RfcProvCertif);
            cmd.Parameters.AddWithValue("@PP_XML", cfdi.xml == null ? "" : cfdi.xml);
            try
            {
                SqlDataReader reader = cmd.ExecuteReader();
                cfdi.idFolio = (int)cmd.Parameters["@PP_ID_FACTURA"].Value;
                cfdi.folio   = (int)cmd.Parameters["@PP_FOLIO"].Value;
                if (cfdi.folio == -1)
                {
                    throw new InvoiceNumberAvailabilityException("No hay números de folio disponibles para timbrar");
                }
                reader.Close();
                if (cfdi.folio > 0 && guardarConceptos)
                {
                    if (cfdi.pagos != null && cfdi.pagos.doctoRelacionados != null && cfdi.pagos.doctoRelacionados.Length > 0)
                    {
                        savePagos(cfdi.pagos, cfdi.idFolio, cmd);
                    }
                    saveRelacionados(cfdi.relaciones, cfdi.idFolio, cmd);
                    saveConceptos(cfdi.conceptos, cfdi.idFolio, cmd);
                }
                if (cfdi.folio > 0 && !guardarConceptos && cfdi.pagos != null && cfdi.pagos.doctoRelacionados != null)
                {
                    foreach (DoctoRelacionado docRelacion in cfdi.pagos.doctoRelacionados)
                    {
                        updateInvoiceBalance(docRelacion, cmd);
                    }
                }
                cmd.Transaction.Commit();
            }
            catch (Exception e)
            {
                logger.Error(e);
                cmd.Transaction.Rollback();
                throw e;
            }
            finally
            {
                cnn.Dispose();
                cmd.Dispose();
            }
        }
Пример #15
0
        public void PDFgenerate(CFDi cfdi)
        {
            Document   doc = new Document(iTextSharp.text.PageSize.LETTER);
            PdfWriter  pw  = null;
            FileStream fs  = null;

            try
            {
                fs = new FileStream("C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.serie + cfdi.folio + ".pdf", FileMode.Create);
                pw = PdfWriter.GetInstance(doc, fs);
                doc.SetMargins(10f, 10f, 10f, 10f);

                doc.Open();

                //----FUENTES----//
                BaseFont             _titulo = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, true);
                iTextSharp.text.Font titulo  = new iTextSharp.text.Font(_titulo, 14f, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));

                BaseFont             _subtitulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
                iTextSharp.text.Font subtitulo  = new iTextSharp.text.Font(_subtitulo, 12f, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));

                BaseFont             _parrafo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
                iTextSharp.text.Font parrafo  = new iTextSharp.text.Font(_parrafo, 7f, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));

                BaseFont             _totales = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
                iTextSharp.text.Font totales  = new iTextSharp.text.Font(_parrafo, 7f, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));

                BaseFont             _titulo_blanco = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
                iTextSharp.text.Font titulo_blanco  = new iTextSharp.text.Font(_titulo_blanco, 7f, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(255, 255, 255));

                //-------------//

                //iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("C:/TOMZA.SYS/CERTIFICADOS_ERP/GASOMATICO S.A. DE C.V/logo_GAS710629HU3.jpg");
                iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(cfdi.emisor.certificado.rutaCert + "\\logo_" + cfdi.emisor.unidadOperativa.razonSocial.rfc + ".jpg");
                logo.ScaleAbsolute(90, 45);

                var tb1 = new PdfPTable(new float[] { 30f, 70f })
                {
                    WidthPercentage = 100f
                };
                tb1.AddCell(new PdfPCell(logo)
                {
                    Padding = 1.5f, Border = 0, Rowspan = 3, HorizontalAlignment = Element.ALIGN_LEFT
                });
                tb1.AddCell(new PdfPCell(new Phrase(cfdi.emisor.unidadOperativa.razonSocial.razonSocial, titulo))
                {
                    Border = 0
                });
                tb1.AddCell(new PdfPCell(new Phrase("RFC: " + cfdi.emisor.unidadOperativa.razonSocial.rfc, parrafo))
                {
                    Border = 0
                });
                tb1.AddCell(new PdfPCell(new Phrase("Regimen Fiscal: General de Ley Personas Morales", parrafo))
                {
                    Border = 0
                });

                tb1.AddCell(new PdfPCell(new Phrase("CLIENTE", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("LUGAR EXPEDICION: " + cfdi.emisor.unidadOperativa.codigoPostal, titulo_blanco))
                {
                    Padding = 3f, BorderColorLeft = new BaseColor(47, 54, 64), BorderColorBottom = new BaseColor(47, 54, 64), BorderWidthTop = 0, BorderWidthLeft = 100, BorderColorRight = new BaseColor(255, 255, 255), BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("GAS COMERCIAL DE VILLA AHUMADA", parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("RFC: " + cfdi.receptor.informacionFiscal.rfc, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                tb1.AddCell(new PdfPCell(new Phrase(""))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase(""))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                var tb2 = new PdfPTable(new float[] { 50f, 50f })
                {
                    WidthPercentage = 100f
                };
                tb2.AddCell(new PdfPCell(new Phrase("FOLIO FISCAL", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase("FACTURA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase(cfdi.folioFiscal, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase(cfdi.serie + " " + cfdi.folio, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                tb2.AddCell(new PdfPCell(new Phrase("FECHA DE CERTIFICACION", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase("FECHA EMISION", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase(cfdi.fechaCert.ToString(), parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase(cfdi.fecha.ToString(), parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                tb2.AddCell(new PdfPCell(new Phrase("No. CERTIFICADO SAT", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase("FORMA DE PAGO", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase("Por Defirnir", parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase("Por Defirnir", parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                tb2.AddCell(new PdfPCell(new Phrase("No. DE CERTIFICADO EMISOR", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase("METODO DE PAGO", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase(cfdi.NoCertificadoEmisor, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb2.AddCell(new PdfPCell(new Phrase(cfdi.mPago, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                var tb_principal = new PdfPTable(new float[] { 60f, 40f })
                {
                    WidthPercentage = 100f
                };
                tb_principal.AddCell(new PdfPCell(tb1)
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_LEFT
                });
                tb_principal.AddCell(new PdfPCell(tb2)
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT
                });
                tb_principal.AddCell(new PdfPCell(new Phrase("AAAAAAAAAAAAAAAA", titulo_blanco))
                {
                    Border = 0
                });
                tb_principal.AddCell(new PdfPCell(new Phrase("BBBBBBBBBBBBBBBB", titulo_blanco))
                {
                    Border = 0
                });

                tb_principal.DefaultCell.Border  = 0;
                tb_principal.DefaultCell.Padding = 10f;

                doc.Add(tb_principal);

                //ENCABEZADO//
                tb1 = new PdfPTable(new float[] { 15f, 15f, 40f, 15f, 15f })
                {
                    WidthPercentage = 100f, HorizontalAlignment = Element.ALIGN_LEFT
                };
                tb1.AddCell(new PdfPCell(new Phrase("CANTIDAD", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("U.MEDIDA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("DESCRIPCION DEL PRODUCTO", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("P.UNITARIO", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                int i = 0;
                foreach (var order in cfdi.conceptos)
                {
                    if (i % 2 == 0)
                    {
                        tb1.AddCell(new PdfPCell(new Phrase(order.cantidad.ToString("f2"), parrafo))
                        {
                            BackgroundColor = new BaseColor(255, 255, 255), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase(order.unidad, parrafo))
                        {
                            BackgroundColor = new BaseColor(255, 255, 255), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase(order.descripcion, parrafo))
                        {
                            BackgroundColor = new BaseColor(255, 255, 255), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase(order.valorUnitario.ToString("f2"), parrafo))
                        {
                            BackgroundColor = new BaseColor(255, 255, 255), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase("$" + order.importe.ToString("f2"), parrafo))
                        {
                            BackgroundColor = new BaseColor(255, 255, 255), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                    }
                    else
                    {
                        tb1.AddCell(new PdfPCell(new Phrase(order.cantidad.ToString("f2"), parrafo))
                        {
                            BackgroundColor = new BaseColor(204, 204, 204), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase(order.unidad, parrafo))
                        {
                            BackgroundColor = new BaseColor(204, 204, 204), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase(order.descripcion, parrafo))
                        {
                            BackgroundColor = new BaseColor(204, 204, 204), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase(order.valorUnitario.ToString("f2"), parrafo))
                        {
                            BackgroundColor = new BaseColor(204, 204, 204), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                        tb1.AddCell(new PdfPCell(new Phrase("$" + order.importe.ToString("f2"), parrafo))
                        {
                            BackgroundColor = new BaseColor(204, 204, 204), Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        });
                    }
                    i++;
                }


                doc.Add(tb1);

                var tb_totales = new PdfPTable(new float[] { 50f })
                {
                    WidthPercentage = 50f, HorizontalAlignment = Element.ALIGN_RIGHT
                };
                tb_totales.AddCell(new PdfPCell(new Phrase("AAAAAAAAAAAAAAAA", titulo_blanco))
                {
                    Border = 0
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("AAAAAAAAAAAAAAAA", titulo_blanco))
                {
                    Border = 0
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("TOTALES", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                doc.Add(tb_totales);

                tb_totales = new PdfPTable(new float[] { 50f, 50f })
                {
                    WidthPercentage = 50f, HorizontalAlignment = Element.ALIGN_RIGHT
                };
                tb_totales.AddCell(new PdfPCell(new Phrase("SUBTOTAL", totales))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("$" + cfdi.subtotal.ToString("f2"), parrafo))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("I.V.A", totales))
                {
                    BackgroundColor = new BaseColor(204, 204, 204), Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("$" + cfdi.totalImp.ToString("f2"), parrafo))
                {
                    BackgroundColor = new BaseColor(204, 204, 204), Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("TOTAL", totales))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb_totales.AddCell(new PdfPCell(new Phrase("$" + cfdi.total.ToString("f2"), parrafo))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                doc.Add(tb_totales);

                tb1 = new PdfPTable(new float[] { 100f })
                {
                    WidthPercentage = 100f
                };

                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE CON LETRA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE CON LETRA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE CON LETRA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase(cfdi.importeLetra, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("CADENA ORIGINAL DEL COMPLEMENTO DE CERTIFICACION DIGITAL DEL SAT ", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase(cfdi.cadenaCertificadoSat, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("SELLO DIGITAL DEL EMISOR", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase(cfdi.selloEmisor, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("SELLO DIGITAL DEL SAT", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase(cfdi.selloSat, parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                doc.Add(tb1);

                tb1 = new PdfPTable(new float[] { 100f })
                {
                    WidthPercentage = 100f
                };

                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE CON LETRA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE CON LETRA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("Conforme al artículo 364 del Código de Comercio, se reserva expesamente el derecho a los intereses moratorios pactados y las entregas a cuenta se imputaran en primer termino al pago de intereses moratorios si existen y después al capital debido. ", parrafo))
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                doc.Add(tb1);

                //CODIGO QR//
                tb1 = new PdfPTable(new float[] { 80f, 20f })
                {
                    WidthPercentage = 50f, HorizontalAlignment = Element.ALIGN_RIGHT
                };
                BarcodeQRCode barcodeQRCode = new BarcodeQRCode("https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx?re=" + cfdi.emisor.unidadOperativa.razonSocial.rfc + "&rr=" + cfdi.receptor.informacionFiscal.rfc + "&tt=" + cfdi.total + "&id=" + cfdi.folioFiscal + "&fe=" + cfdi.selloEmisor.Substring(cfdi.selloEmisor.Length - 9, 8), 1000, 1000, null);
                Image         codeQRImage   = barcodeQRCode.GetImage();
                codeQRImage.ScaleAbsolute(60, 60);

                tb1.AddCell(new PdfPCell(new Phrase("CONDICIONES DE PAGO: \n" + cfdi.tipoVenta, titulo))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("IMPORTE CON LETRA", titulo_blanco))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(new Phrase("ESTE RECIBO UNICAMENTE SERA\n VALIDO COMO PAGO SI PRESENTA\n EL COMPROBANTE QUE AMPARE\n EL IMPORTE DEL MISMO\n EFECTOS FISCALES DE PAGO.", parrafo))
                {
                    Padding = 3f, Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                tb1.AddCell(new PdfPCell(codeQRImage)
                {
                    Border = 0, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                doc.Add(tb1);

                tb1 = new PdfPTable(new float[] { 100f })
                {
                    WidthPercentage = 100f, HorizontalAlignment = Element.ALIGN_LEFT
                };
                tb1.AddCell(new PdfPCell(new Phrase("ESTE DOCUMENTO ES UNA REPRESENTACION IMPRESA DE UN CFDi V3.3", titulo_blanco))
                {
                    Padding = 3f, Border = 0, BackgroundColor = new BaseColor(47, 54, 64), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                doc.Add(tb1);
            }
            catch (Exception e)
            {
                logger.Error(e, e.Message);
                fs.Dispose();
                if (File.Exists("C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.serie + cfdi.folio + ".pdf"))
                {
                    File.Delete("C://TOMZA.SYS/cfdi/pdf/reporte" + cfdi.serie + cfdi.folio + ".pdf");
                }
            }
            finally
            {
                doc.Dispose();
                pw.Dispose();
            }
        }