<%@ WebHandler Language="VB" Class="GenerarPDFFactura" %> Imports System Imports System.Web Imports System.Data Imports Newtonsoft.Json Imports Newtonsoft.Json.Linq Imports Extensiones Imports System.IO Imports Microsoft.Reporting.WebForms Public Class GenerarPDFFactura : Implements IHttpHandler Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Dim retorno As String = "no se encontro la variable" Try Dim datos As ParametroWS = Nothing If context.Request.Headers("Content-Type") IsNot Nothing AndAlso context.Request.Headers("Content-Type").Contains("json") AndAlso context.Request.InputStream IsNot Nothing Then context.Response.ContentType = "application/json" Using reader As New StreamReader(context.Request.InputStream) Dim json = reader.ReadToEnd() datos = JsonConvert.DeserializeObject(Of ParametroWS)(json) End Using End If If datos IsNot Nothing Then Dim ListaDS = New List(Of ReportDataSource) Dim Parametros As New List(Of ReportParameter) Dim Formato = context.Server.MapPath("/") + "Empresas/1/Report.rdlc" Parametros.Add(New ReportParameter("Empresa", datos.Empresa.Empresa)) Parametros.Add(New ReportParameter("RFC", datos.Empresa.RFC)) Parametros.Add(New ReportParameter("DomicilioExpedicion", datos.Empresa.DomicilioFiscal)) Parametros.Add(New ReportParameter("Serie", datos.Factura.Serie)) Parametros.Add(New ReportParameter("Folio", datos.Factura.Folio)) Parametros.Add(New ReportParameter("Fecha", datos.Factura.Fecha)) Parametros.Add(New ReportParameter("ClienteNombre", datos.Cliente.NombreComercial)) Parametros.Add(New ReportParameter("ClienteDireccion", datos.Cliente.Calle + " Colonia " + datos.Cliente.Colonia + " " + datos.Cliente.Ciudad + ", " + datos.Cliente.Estado)) Parametros.Add(New ReportParameter("ClienteLugar", datos.Cliente.Ciudad)) Parametros.Add(New ReportParameter("ClienteRFC", datos.Cliente.RFC)) Parametros.Add(New ReportParameter("ImporteLetra", datos.Factura.Total.Texto2Letras())) Parametros.Add(New ReportParameter("FormaPago", datos.Factura.FormaPago)) Parametros.Add(New ReportParameter("MetodoPago", datos.Factura.MetodoPago)) Parametros.Add(New ReportParameter("SelloCFDI", "")) Parametros.Add(New ReportParameter("SelloSAT", "")) Parametros.Add(New ReportParameter("CadenaOriginal", "")) Parametros.Add(New ReportParameter("FolioFiscal", datos.Factura.UUID)) Parametros.Add(New ReportParameter("SerieCertificadoSAT", "")) Parametros.Add(New ReportParameter("FechaCertificado", "")) Parametros.Add(New ReportParameter("CertificadoContribuyente", "")) Parametros.Add(New ReportParameter("UsoCFDI", datos.Factura.UsoCFDI)) Parametros.Add(New ReportParameter("Vencimiento", Now.AddDays(30))) Parametros.Add(New ReportParameter("SubTotal", datos.Factura.SubTotal)) Parametros.Add(New ReportParameter("IVA", datos.Factura.IVA)) Parametros.Add(New ReportParameter("IEPS", datos.Factura.IEPS)) Parametros.Add(New ReportParameter("Total", datos.Factura.Total)) Parametros.Add(New ReportParameter("QR", "")) Dim DtDatos As New DataTable DtDatos.Columns.Add(New DataColumn("Cantidad", GetType(Decimal))) DtDatos.Columns.Add(New DataColumn("UnidadMedida", GetType(String))) DtDatos.Columns.Add(New DataColumn("PS", GetType(String))) DtDatos.Columns.Add(New DataColumn("PU", GetType(Decimal))) DtDatos.Columns.Add(New DataColumn("IVA", GetType(Decimal))) DtDatos.Columns.Add(New DataColumn("IEPS", GetType(Decimal))) DtDatos.Columns.Add(New DataColumn("Total", GetType(Decimal))) For Each PS In datos.Factura.ListaProductos Dim Row = DtDatos.NewRow() Row("Cantidad") = PS.Cantidad Row("UnidadMedida") = PS.UnidadMedida Row("PS") = PS.CodigoPS Row("PU") = PS.PU Row("IVA") = PS.IVA Row("IEPS") = PS.IEPS Row("Total") = (PS.Cantidad * PS.PU) + PS.IVA + PS.IEPS DtDatos.Rows.Add(Row) Next ListaDS.Add(New ReportDataSource("DsProductos", DtDatos)) ImprimirbytesPDF(context, StreamPDF(context, Formato, ListaDS, Parametros), "test") End If Catch ex As Exception ex.GuardaLog(ex.ToString()) context.Response.Write(retorno) End Try End Sub Public Function StreamPDF(ByVal context As HttpContext, RutaReporte As String, DataSource As List(Of ReportDataSource), Parametros As List(Of ReportParameter), Optional NombreArchivo As String = "Reporte", Optional Formato As String = "PDF", Optional MR As ReportViewer = Nothing) As Byte() 'limpio ReportViwer Dim sw As New System.Diagnostics.Stopwatch() sw.Start() If IsNothing(MR) Then MR = New ReportViewer Dim Bytes As Byte() = Nothing Try ' MasterReporteador.LocalReport.DataSources.Clear() For Each RDS As ReportDataSource In DataSource MR.LocalReport.DataSources.Add(RDS) Next MR.LocalReport.ReportPath = RutaReporte MR.ProcessingMode = ProcessingMode.Local MR.LocalReport.EnableExternalImages = True MR.LocalReport.SetParameters(Parametros) MR.LocalReport.Refresh() Dim Warnings As Warning() = Nothing Dim StreamIds As String() = Nothing Dim MimeType As String = Nothing Dim Encoding As String = Nothing Dim Extension As String = Nothing Bytes = MR.LocalReport.Render(Formato, Nothing, MimeType, Encoding, Extension, StreamIds, Warnings) Catch ex As Microsoft.Reporting.WebForms.ScriptManagerNotFoundException GuardaLog($"Error: { If(ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, ex.Message) } | Descripcion: {If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException.Message IsNot Nothing, ex.InnerException.InnerException.Message, If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, "Sin descripcion"))} - Ruta {RutaReporte}") 'HAY QUE VALIDAR QUE LOS OBJETOS QUE SE USAN PARA GUARDAR LOG EXISTEN!!! IPP 14 AGOSTO 2017 'GuardaLog($"Error: {ex.InnerException.Message} | Descripcion: {If(ex.InnerException.InnerException IsNot Nothing, ex.InnerException.InnerException.Message, "Sin descripcion")} - Ruta {RutaReporte}") Catch ex As Exception GuardaLog($"Error: { If(ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, ex.Message) } | Descripcion: {If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException.Message IsNot Nothing, ex.InnerException.InnerException.Message, If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, "Sin descripcion"))} - Ruta {RutaReporte}") 'HAY QUE VALIDAR QUE LOS OBJETOS QUE SE USAN PARA GUARDAR LOG EXISTEN!!! IPP 14 AGOSTO 2017 'GuardaLog($"Error {ex.InnerException.Message} | Descripcion: {If(ex.InnerException.InnerException IsNot Nothing, ex.InnerException.InnerException.Message, "Sin descripcion")} - Ruta {RutaReporte}") End Try sw.Stop() If sw.Elapsed.TotalSeconds > 10 Then GuardaLog($"Reporte:{RutaReporte} | Tiempo Renderizado Milisegundos: {sw.ElapsedMilliseconds},Total Segundos: {sw.Elapsed.TotalSeconds} ") End If Return Bytes End Function Public Sub ImprimirbytesPDF(ByVal context As HttpContext, bytes As Byte(), Optional NombreArchivo As String = "Reporte", Optional Formato As String = "PDF", Optional Descarga As Boolean = False) 'limpio ReportViwer Dim mimeType As String = Nothing Dim extension As String = Nothing 'If Descarga Then ' Try ' bytes = bytes ' File.WriteAllBytes(String.Format("{0}PDF/whatever.gif", UsuarioActual.Empresa.Ruta), img) ' Catch ex As Exception ' If UsuarioActual.CveRol = 1 Then ' Alert(ex.Message, TipoMensaje.MsgAdvertencia) ' Else ' Alert("Ocurrió un error al generar la descarga. Favor de contactar a soporte tecnico cod'IMPDFclspag'", TipoMensaje.MsgAdvertencia) ' End If ' End Try 'End If Try bytes = bytes context.Response.Buffer = True context.Response.Clear() context.Response.ContentType = mimeType context.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}.{1}", NombreArchivo, If(Formato = "PDF", "pdf", "xls"))) context.Response.BinaryWrite(bytes) ' create the file context.Response.Flush() ' send it to the client to download context.Response.SuppressContent = True context.ApplicationInstance.CompleteRequest() context.Response.End() Catch ex As Exception End Try End Sub Public Class FacturaWS Public Property Id As Integer Public Property CveVenta As Integer Public Property CveCliente As Integer Public Property NombreCliente As String Public Property Fecha As DateTime Public Property CveSubCentroCosto As Integer Public Property CveTipoDocumento As Integer Public Property TipoDocumento As String Public Property Serie As String Public Property Folio As Integer Public Property CveVendedor As Integer Public Property CveUsuario As Integer Public Property CveEstatusVenta As Integer Public Property EstatusVenta As String Public Property UUID As String Public Property ListaProductos As List(Of ProductoWS) Public Property CveUsoCFDI As Integer Public Property UsoCFDI As String Public Property CveMetodoPago As Integer Public Property MetodoPago As String Public Property ClaveMetodoPagoSAT As String Public Property CveFormaPago As Integer Public Property FormaPago As String Public Property ClaveFormaPagoSAT As String Public Property Observaciones As String Public Property CveMoneda As Integer Public Property TipoCambio As Double Public Property FechaIng As DateTime Public Property CveEmpresa As Integer Public Property SubTotal As Double Public Property Descuentos As Double Public Property IVA As Double Public Property IEPS As Double Public Property Total As Double End Class Public Class ProductoWS Public Property Id As Integer Public Property CveVentaDetalle As Integer Public Property CveVenta As Integer Public Property CveProductoServicio As Integer Public Property CodigoPS As String Public Property CveUnidadMedida As Integer Public Property UnidadMedida As String Public Property Cantidad As Double Public Property Observacion As String Public Property PU As Double Public Property Descuento As Double Public Property IVA As Double Public Property IEPS As Double Public Property IVAPorcentaje As Double Public Property IEPSPorcentaje As Double Public Property CveSubCentroCosto As Integer Public Property SubCentroCosto As String End Class Public Class ClienteWS Public Property Id As Integer Public Property CveCliente As Integer Public Property RazonSocial As String Public Property NombreComercial As String Public Property RFC As String Public Property Codigo As String Public Property Calle As String Public Property NoExterior As String Public Property Colonia As String Public Property Ciudad As String Public Property Municipio As String Public Property Estado As String Public Property CodigoPostal As Integer Public Property Contacto As String Public Property ContactoTelefono As String Public Property Correo As String Public Property CveVendedor As Integer Public Property Estatus As Boolean Public Property CveUsuario As Integer Public Property CveEmpresa As Integer Public Property CveRegimenFiscal As Integer Public Property RegimenFiscal As String Public Property CodigoRegimenFiscal As String End Class Public Class EmpresaWS Public Property Id As Integer Public Property CveEmpresa As Integer Public Property Empresa As String Public Property RFC As String Public Property DomicilioFiscal As String Public Property ArchivoCER As String Public Property ArchivoKEY As String Public Property FieldPassword As String Public Property CveRegimenFiscal As Integer Public Property RegimenFiscal As String End Class Public Class ParametroWS Public Property Factura As FacturaWS Public Property Cliente As ClienteWS Public Property Empresa As EmpresaWS End Class End Class