Esempio n. 1
0
        public FileStreamResult GenerarReporte(string dniAlumno)
        {
            Document     document = new Document(PageSize.A4);
            MemoryStream stream   = new MemoryStream();

            // Datos necesarios
            var ex = _repository.Alumnos.GetAll();

            try
            {
                PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
                pdfWriter.CloseStream = false;

                document.Open();

                // Fonts
                Font title  = FontFactory.GetFont("Arial", 12, Font.BOLD);
                Font bold10 = FontFactory.GetFont("Arial", 10, Font.BOLD);
                Font body10 = FontFactory.GetFont("Arial", 10);

                // Membrete
                String baseUrl = _env.WebRootPath;
                Image  imagen  = Image.GetInstance(baseUrl + "/img/logo_trilce_reporte.png");
                imagen.ScaleAbsoluteWidth(150);
                document.Add(imagen);

                // Título del reporte
                Paragraph titulo = new Paragraph("\nBOLETA DE MATRÍCULA", title);
                titulo.Alignment = Element.ALIGN_CENTER;
                document.Add(titulo);

                var alumno     = _repository.Alumnos.GetByDni(dniAlumno);
                var nextGrado  = _repository.Alumnos.GetGrado(alumno.Id);
                var nextCursos = _repository.Grados.GetCursos(nextGrado.Id);
                // Fecha y hora
                Chunk  fechaCab = new Chunk("\nFECHA: ", bold10);
                Chunk  fecha    = new Chunk(DateTime.Now.ToString(), body10);
                Phrase pFecha   = new Phrase();
                pFecha.Add(fechaCab);
                pFecha.Add(fecha);

                // Datos del alumno
                Chunk  nombreCab = new Chunk("\nNOMBRE: ", bold10);
                Chunk  nombre    = new Chunk(alumno.ApellidoPaterno + " " + alumno.ApellidoMaterno + ", " + alumno.Nombres, body10);
                Phrase pNombre   = new Phrase();
                pNombre.Add(nombreCab);
                pNombre.Add(nombre);

                Chunk  dniCab = new Chunk("\nDNI: ", bold10);
                Chunk  dni    = new Chunk(alumno.Dni, body10);
                Phrase pDni   = new Phrase();
                pDni.Add(dniCab);
                pDni.Add(dni);

                Chunk  gradoCab = new Chunk("\nGRADO: ", bold10);
                Chunk  grado    = new Chunk(nextGrado.Nombre + " de " + nextGrado.Nivel.Nombre, body10);
                Phrase pGrado   = new Phrase();
                pGrado.Add(gradoCab);
                pGrado.Add(grado);

                Chunk  cursosCab = new Chunk("\nCURSOS:\n ", bold10);
                Phrase pCursos   = new Phrase();
                pCursos.Add(cursosCab);

                Paragraph pDatos = new Paragraph();
                pDatos.Add(pFecha);
                pDatos.Add(pNombre);
                pDatos.Add(pDni);
                pDatos.Add(pGrado);
                pDatos.Add(pCursos);

                document.Add(pDatos);

                PdfPTable table           = new PdfPTable(2);
                float[]   anchoDeColumnas = new float[] { 20f, 10f };
                table.SetWidths(anchoDeColumnas);
                table.WidthPercentage = 50;

                PdfPCell header1 = new PdfPCell(new Paragraph("NOMBRE", bold10));
                header1.HorizontalAlignment = (Element.ALIGN_CENTER);
                header1.BackgroundColor     = WebColors.GetRgbColor("#aaaaaa");
                table.AddCell(header1);

                PdfPCell header2 = new PdfPCell(new Paragraph("HORAS", bold10));
                header2.HorizontalAlignment = (Element.ALIGN_CENTER);
                header2.BackgroundColor     = WebColors.GetRgbColor("#aaaaaa");
                table.AddCell(header2);

                table.HeaderRows = 2;
                foreach (Curso curso in nextCursos)
                {
                    PdfPCell nombreCurso = new PdfPCell(new Paragraph(curso.Nombre, body10));
                    nombreCurso.HorizontalAlignment = (Element.ALIGN_LEFT);
                    table.AddCell(nombreCurso);

                    PdfPCell horasCurso = new PdfPCell(new Paragraph(curso.HorasAcademicas.ToString(), body10));
                    horasCurso.HorizontalAlignment = (Element.ALIGN_CENTER);
                    table.AddCell(horasCurso);
                }
                document.Add(table);
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }

            document.Close();

            stream.Flush();      //Always catches me out
            stream.Position = 0; //Not sure if this is required

            return(new FileStreamResult(stream, "application/pdf"));
        }
Esempio n. 2
0
        public bool GerarPdfOrcamento(int codigoOrcamento, bool removerColunaDesconto, string caminhoSaida, string caminhoWebRoot, out string mensagemErro)
        {
            mensagemErro = "";

            try
            {
                //Lista de produtos vendidos
                CabecalhoOrcamentoBLL cabecalhoOrcamentoBLL = new CabecalhoOrcamentoBLL();
                ItemOrcamentoBLL      itemOrcamentoBLL      = new ItemOrcamentoBLL();

                CabecalhoOrcamento   cabecalhoOrcamento = cabecalhoOrcamentoBLL.GetCabecalhoOrcamento(codigoOrcamento, out mensagemErro);
                List <ItemOrcamento> produtos           = itemOrcamentoBLL.getItensOrcamento(codigoOrcamento, null, out mensagemErro);

                using (MemoryStream myMemoryStream = new MemoryStream())
                {
                    Document doc = new Document(PageSize.A4);
                    doc.SetMargins(20, 20, 40, 80);
                    doc.AddCreationDate();

                    PdfWriter writer = PdfWriter.GetInstance(doc, myMemoryStream);

                    doc.Open();

                    string caminhoImagem = caminhoWebRoot + "/images/LogoCIA.png";

                    Image imagem = Image.GetInstance(caminhoImagem);
                    imagem.ScaleAbsolute(400, 200);
                    imagem.Alignment = 1;
                    doc.Add(imagem);

                    doc.Add(new Paragraph("\n"));

                    //Ajustar espaço entre a logo e a tabela

                    float[] columnWidths = { 2, 2, 1, 1 };

                    PdfPTable table = new PdfPTable(columnWidths);
                    table.HorizontalAlignment = 0;
                    table.TotalWidth          = 560f;
                    table.LockedWidth         = true;

                    PdfPCell cellMeta = new PdfPCell();
                    PdfPCell cellData = new PdfPCell();

                    //Dados do Cliente
                    cellMeta.Phrase      = new Phrase("Data:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = Rectangle.TOP_BORDER;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.DataCriacao.ToString("dd/MM/yyyy"));
                    cellData.Colspan     = 3;
                    cellData.Border      = Rectangle.TOP_BORDER;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta        = new PdfPCell();
                    cellMeta.Phrase = new Phrase("Razão Social:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border = 0;
                    table.AddCell(cellMeta);

                    cellData         = new PdfPCell();
                    cellData.Phrase  = new Phrase(cabecalhoOrcamento.Cliente.RazaoSocial);
                    cellData.Colspan = 3;
                    cellData.Border  = 0;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("CNPJ:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.Cliente.CNPJ.ToString());
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Cidade:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.Cliente.Cidade.Descricao);
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Estado:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.Cliente.Cidade.Estado);
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Telefone:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.TelefoneContato);
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    //Dados do orcamento

                    cellMeta.Phrase      = new Phrase("Repres.:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = Rectangle.TOP_BORDER;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.FuncionarioVendedor.Nome);
                    cellData.Border      = Rectangle.TOP_BORDER;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Fixo:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = Rectangle.TOP_BORDER;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase("(34) 3253-0533");
                    cellData.Border      = Rectangle.TOP_BORDER;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Email:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.FuncionarioVendedor.Email);
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Celular:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.FuncionarioVendedor.Telefone);
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Val. da Proposta:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.ValidadeOrcamento.ToString() + " Dias");
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Condições de pag:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase(cabecalhoOrcamento.CondicaoPagamento.Descricao);
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    cellMeta.Phrase      = new Phrase("Prazo de entrega:", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMeta.Border      = 0;
                    cellMeta.BorderWidth = 2;
                    table.AddCell(cellMeta);

                    cellData             = new PdfPCell();
                    cellData.Phrase      = new Phrase("30 Dias úteis");
                    cellData.Colspan     = 3;
                    cellData.Border      = 0;
                    cellData.BorderWidth = 2;
                    table.AddCell(cellData);

                    doc.Add(table);

                    doc.Add(new Paragraph("\n"));
                    Paragraph p = new Paragraph("ORÇAMENTO", FontFactory.GetFont("Times New Roman", 15, Font.BOLD, BaseColor.Black));
                    p.Alignment = Element.ALIGN_CENTER;
                    doc.Add(p);
                    doc.Add(new Paragraph("\n"));

                    //Dados dos produtos vendidos
                    float[] columnWidths4 = { 3, 2, 2, 2, 2 };
                    float[] columnWidths5 = { 3, 2, 2, 2, 2, 2 };

                    PdfPTable tableProduct;

                    if (removerColunaDesconto)
                    {
                        tableProduct = new PdfPTable(columnWidths4);
                    }
                    else
                    {
                        tableProduct = new PdfPTable(columnWidths5);
                    }
                    tableProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct.TotalWidth          = 500f;
                    tableProduct.LockedWidth         = true;


                    PdfPCell cellMetaProduct = new PdfPCell();
                    PdfPCell cellDataProduct = new PdfPCell();

                    BaseColor myColor = WebColors.GetRgbColor("#00CD00");

                    cellMetaProduct.Phrase              = new Phrase("Produto", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMetaProduct.BackgroundColor     = myColor;
                    cellMetaProduct.BorderWidth         = 2;
                    cellMetaProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct.AddCell(cellMetaProduct);

                    cellMetaProduct.Phrase              = new Phrase("Unitário", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMetaProduct.BackgroundColor     = myColor;
                    cellMetaProduct.BorderWidth         = 2;
                    cellMetaProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct.AddCell(cellMetaProduct);

                    cellMetaProduct.Phrase              = new Phrase("Quantidade", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMetaProduct.BackgroundColor     = myColor;
                    cellMetaProduct.BorderWidth         = 2;
                    cellMetaProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct.AddCell(cellMetaProduct);

                    cellMetaProduct.Phrase              = new Phrase("Total", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMetaProduct.BackgroundColor     = myColor;
                    cellMetaProduct.BorderWidth         = 2;
                    cellMetaProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct.AddCell(cellMetaProduct);

                    if (!removerColunaDesconto)
                    {
                        cellMetaProduct.Phrase              = new Phrase("Desconto", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                        cellMetaProduct.BackgroundColor     = myColor;
                        cellMetaProduct.BorderWidth         = 2;
                        cellMetaProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableProduct.AddCell(cellMetaProduct);
                    }

                    cellMetaProduct.Phrase              = new Phrase("Valor Final", FontFactory.GetFont("Times New Roman", 11, Font.BOLD, BaseColor.Black));
                    cellMetaProduct.BackgroundColor     = myColor;
                    cellMetaProduct.BorderWidth         = 2;
                    cellMetaProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct.AddCell(cellMetaProduct);

                    //@foreach

                    foreach (ItemOrcamento item in produtos)
                    {
                        cellDataProduct.Phrase              = new Phrase(item.produto.Descricao);
                        cellDataProduct.BorderWidth         = 2;
                        cellDataProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableProduct.AddCell(cellDataProduct);

                        cellDataProduct.Phrase              = new Phrase(string.Format("{0:C}", item.produto.ValorPorPessoa + item.acrescimo));
                        cellDataProduct.BorderWidth         = 2;
                        cellDataProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableProduct.AddCell(cellDataProduct);

                        cellDataProduct.Phrase              = new Phrase(item.quantidade.ToString());
                        cellDataProduct.BorderWidth         = 2;
                        cellDataProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableProduct.AddCell(cellDataProduct);

                        cellDataProduct.Phrase              = new Phrase(string.Format("{0:C}", ((item.produto.ValorPorPessoa + item.acrescimo) * item.quantidade)));
                        cellDataProduct.BorderWidth         = 2;
                        cellDataProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableProduct.AddCell(cellDataProduct);

                        if (!removerColunaDesconto)
                        {
                            cellDataProduct.Phrase              = new Phrase(Convert.ToDecimal(item.percentualDesconto) + "%");
                            cellDataProduct.BorderWidth         = 2;
                            cellDataProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                            tableProduct.AddCell(cellDataProduct);
                        }

                        cellDataProduct.Phrase              = new Phrase(string.Format("{0:C}", item.subtotal));
                        cellDataProduct.BorderWidth         = 2;
                        cellDataProduct.HorizontalAlignment = Element.ALIGN_CENTER;
                        tableProduct.AddCell(cellDataProduct);
                    }
                    //#@End Foreach

                    doc.Add(tableProduct);

                    Paragraph p1 = new Paragraph("INVESTIMENTO", FontFactory.GetFont("Times New Roman", 15, Font.BOLD, BaseColor.Black));
                    p1.Alignment = Element.ALIGN_CENTER;
                    doc.Add(p1);

                    string valorPorExtenso = Uteis.toExtenso(cabecalhoOrcamento.ValorOrcamento);

                    Paragraph p2 = new Paragraph(string.Format("{0:C}", cabecalhoOrcamento.ValorOrcamento) + " - " + valorPorExtenso, FontFactory.GetFont("Times New Roman", 15, BaseColor.Black));
                    p2.Alignment = Element.ALIGN_CENTER;
                    doc.Add(p2);

                    int totalParcelas = cabecalhoOrcamento.CondicaoPagamento.Descricao.Split('/').Length;

                    string texto = totalParcelas + " X " + string.Format("{0:C}", cabecalhoOrcamento.ValorOrcamento / totalParcelas) + " No Boleto Bancário";

                    Paragraph p3 = new Paragraph(texto, FontFactory.GetFont("Times New Roman", 13, Font.BOLD, BaseColor.Black));
                    p3.Alignment = Element.ALIGN_CENTER;
                    doc.Add(p3);

                    texto = "\n*Vale ressaltar que o recolhimento da taxa da ART é de responsabilidade do contratante e o valor para pagamento de R$ 82,94 será entregue em boleto separado. " +
                            "\nOBS: Será cobrado 5 % sobre o valor total do investimento referente a despesas acessórias.";

                    Paragraph p4 = new Paragraph(texto, FontFactory.GetFont("Times New Roman", 15, BaseColor.Black));
                    p4.Alignment = Element.ALIGN_JUSTIFIED;
                    doc.Add(p4);

                    texto = "I. É de responsabilidade do Cliente:\n" +
                            "* Disponibilizar os colaboradores para participação das aulas teórico - práticas.\n" +
                            "* Arcar com os custos relativos às taxas geradas junto aos órgãos oficiais e CREA / ART.\n" +
                            "* Arcar com os custos das recargas e manutenções dos extintores que por ventura possam ser utilizados no curso.\n" +
                            "* Disponibilizar o cofee break e espaço físico para a realização dos treinamentos.\n" +
                            "* Disponibilizar toda a documentação necessária para elaboração dos laudos.\n\n" +
                            "II. É de responsabilidade Cia do Treinamento:\n" +
                            "* Executar os serviços relativos à elaboração, montagem e treinamentos propostos;\n" +
                            "* Aplicar Avaliação para os colaboradores.\n" +
                            "* Emitir Certificados referente aos cursos ministrados.\n";

                    Paragraph p5 = new Paragraph(texto, FontFactory.GetFont("Times New Roman", 15, BaseColor.Black));
                    p5.Alignment = Element.ALIGN_JUSTIFIED;
                    doc.Add(p5);

                    texto = "Serviços disponibilizados pela Cia do Treinamento";

                    Paragraph p6 = new Paragraph(texto, FontFactory.GetFont("Times New Roman", 15, BaseColor.Black));
                    p6.Alignment = Element.ALIGN_CENTER;
                    doc.Add(p6);

                    doc.Add(new Paragraph("\n"));

                    PdfPTable tableProduct2 = new PdfPTable(1);
                    tableProduct2.HorizontalAlignment = Element.ALIGN_CENTER;
                    tableProduct2.TotalWidth          = 300f;
                    tableProduct2.LockedWidth         = true;

                    PdfPCell cell = new PdfPCell();

                    cell.Phrase      = new Phrase("NR20");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR20 - Motoristas (24h)");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR20 - Motoristas (32h)");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Treinamento em Segurança do Trabalho, Basico em Meio Ambiente");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NBR-14.276 Brigada de Incêndio - 12 Horas");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NBR-14.276 Brigada de Incêndio - 8 Horas");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Treinamento Benzeno");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR06");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("PPP");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR35");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR33 - 40 Horas");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR33 - 8 Horas");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Certificado Cipa");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR17");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("NR10");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Prontuario NR20");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Plano de Atendimento a Emergencias ou Plano de Resposta a Emergencias");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("LTCAT");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("PPRA");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("PCMSO");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Mapa de Risco");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Pasta Cipa");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("PET - Plano de Emergencia e Transporte");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("PGR - Programa de Gerencimento de Riscos");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("BTXE (Medição)");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Estudo de classificação de áreas");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Laudo de aterramento e SPDA que discorra também sobre potencialização e eletricidade estática");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Laudo de inspeção detalhada das instalações elétricas-Laudo de inspeção não elétrica em atm.explosiv");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Inspeção no vaso de pressão - Acima 500 L");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Inspeção no vaso de pressão - Ate 500 L");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Teste de Estanqueidade");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Layout de planta baixa");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    cell             = new PdfPCell();
                    cell.Phrase      = new Phrase("Dosimetria de ruído");
                    cell.BorderWidth = 2;
                    tableProduct2.AddCell(cell);

                    doc.Add(tableProduct2);

                    doc.Close();

                    byte[] content = myMemoryStream.ToArray();

                    // Write out PDF from memory stream.
                    using (FileStream fs = File.Create(caminhoSaida))
                    {
                        fs.Write(content, 0, (int)content.Length);

                        fs.Close();
                    }

                    myMemoryStream.Close();
                }
            }
            catch (Exception e)
            {
                mensagemErro = e.ToString();
                return(false);
            }

            return(true);
        }
Esempio n. 3
0
        /// <author>Eddy Wilmer Canaza Tito</author>
        /// <summary>
        /// Método para generar el reporte de lista de alumnos a través del Id de sección.
        /// </summary>
        /// <param name="idSeccion">Id de la sección.</param>
        /// <returns>Archivo PDF.</returns>
        public FileStreamResult GenerarReporte(int idSeccion)
        {
            Document     document = new Document(PageSize.A4);
            MemoryStream stream   = new MemoryStream();

            // Datos necesarios
            var ex = _repository.Alumnos.GetAll();

            try
            {
                PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
                pdfWriter.CloseStream = false;

                document.Open();

                // Fonts
                Font title  = FontFactory.GetFont("Arial", 12, Font.BOLD);
                Font bold10 = FontFactory.GetFont("Arial", 10, Font.BOLD);
                Font body10 = FontFactory.GetFont("Arial", 10);

                // Membrete
                String baseUrl = _env.WebRootPath;
                Image  imagen  = Image.GetInstance(baseUrl + "/img/logo_trilce_reporte.png");
                imagen.ScaleAbsoluteWidth(150);
                document.Add(imagen);

                // Título del reporte
                Paragraph titulo = new Paragraph("\nLISTA DE ALUMNOS", title);
                titulo.Alignment = Element.ALIGN_CENTER;
                document.Add(titulo);

                var lista        = _repository.Secciones.GetLista(idSeccion);
                var seccionLista = _repository.Secciones.Get(idSeccion);
                var gradoLista   = _repository.Grados.Get(seccionLista.Grado.Id);
                // Fecha y hora
                Chunk  fechaCab = new Chunk("\nFECHA: ", bold10);
                Chunk  fecha    = new Chunk(DateTime.Now.ToString(), body10);
                Phrase pFecha   = new Phrase();
                pFecha.Add(fechaCab);
                pFecha.Add(fecha);

                Chunk  gradoCab = new Chunk("\nGRADO: ", bold10);
                Chunk  grado    = new Chunk(gradoLista.Nombre + " de " + gradoLista.Nivel.Nombre, body10);
                Phrase pGrado   = new Phrase();
                pGrado.Add(gradoCab);
                pGrado.Add(grado);

                Chunk  seccionCab = new Chunk("\nSECCIÓN: ", bold10);
                Chunk  seccion    = new Chunk(seccionLista.Nombre + "\n\n", body10);
                Phrase pSeccion   = new Phrase();
                pGrado.Add(seccionCab);
                pGrado.Add(seccion);

                Paragraph pDatos = new Paragraph();
                pDatos.Add(pFecha);
                pDatos.Add(pGrado);

                document.Add(pDatos);

                PdfPTable table           = new PdfPTable(4);
                float[]   anchoDeColumnas = new float[] { 5f, 40f, 20f, 20f };
                table.SetWidths(anchoDeColumnas);
                table.WidthPercentage = 100;

                PdfPCell header1 = new PdfPCell(new Paragraph("N°", bold10));
                header1.HorizontalAlignment = (Element.ALIGN_CENTER);
                header1.BackgroundColor     = WebColors.GetRgbColor("#aaaaaa");
                table.AddCell(header1);

                PdfPCell header2 = new PdfPCell(new Paragraph("APELLIDOS Y NOMBRES", bold10));
                header2.HorizontalAlignment = (Element.ALIGN_CENTER);
                header2.BackgroundColor     = WebColors.GetRgbColor("#aaaaaa");
                table.AddCell(header2);

                PdfPCell header3 = new PdfPCell(new Paragraph("DNI", bold10));
                header3.HorizontalAlignment = (Element.ALIGN_CENTER);
                header3.BackgroundColor     = WebColors.GetRgbColor("#aaaaaa");
                table.AddCell(header3);

                PdfPCell header4 = new PdfPCell(new Paragraph("FECHA DE NACIMIENTO", bold10));
                header4.HorizontalAlignment = (Element.ALIGN_CENTER);
                header4.BackgroundColor     = WebColors.GetRgbColor("#aaaaaa");
                table.AddCell(header4);

                int i = 1;
                foreach (Alumno alumno in lista)
                {
                    PdfPCell nroOrden = new PdfPCell(new Paragraph(i.ToString(), body10));
                    nroOrden.HorizontalAlignment = (Element.ALIGN_CENTER);
                    table.AddCell(nroOrden);

                    PdfPCell nombreAlumno = new PdfPCell(new Paragraph(alumno.ApellidoPaterno + " " + alumno.ApellidoMaterno + ", " + alumno.Nombres, body10));
                    nombreAlumno.HorizontalAlignment = (Element.ALIGN_LEFT);
                    table.AddCell(nombreAlumno);

                    PdfPCell dniAlumno = new PdfPCell(new Paragraph(alumno.Dni, body10));
                    dniAlumno.HorizontalAlignment = (Element.ALIGN_CENTER);
                    table.AddCell(dniAlumno);

                    PdfPCell fechaAlumno = new PdfPCell(new Paragraph(alumno.FechaNacimiento.Date.ToString("dd/MM/yyyy"), body10));
                    fechaAlumno.HorizontalAlignment = (Element.ALIGN_CENTER);
                    table.AddCell(fechaAlumno);

                    i++;
                }
                document.Add(table);
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }

            document.Close();

            stream.Flush();      //Always catches me out
            stream.Position = 0; //Not sure if this is required

            return(new FileStreamResult(stream, "application/pdf"));
        }
        // GET: ComPersona
        public async Task <IActionResult> Index(string reporte, string valuesOrder, string searchPerson)
        {
            try
            {
                var persona = from s in _context.ComPersona select s;
                persona = persona.Include(c => c.ComCatEscolaridad).Include(c => c.ComCatSexo);

                // Generar reporte PDF
                ViewData["GenerateReports"] = "reporte";

                if (!String.IsNullOrEmpty(reporte))
                {
                    // Creamos el documento PDF con el formato de hoja A4, y Rotate() para ponerla horizontal.
                    Document doc = new Document(PageSize.A4.Rotate());
                    // Indicamos la ruta donde se va a guardar el documento.
                    PdfWriter writer = PdfWriter.GetInstance(doc,
                                                             new FileStream(@"/Users/marcosmontiel/Desktop/personas.pdf", FileMode.Create));
                    // Colocamos el titulo y autor del documento (Esto no será visible en el documento).
                    doc.AddTitle("Reporte - Personas");
                    doc.AddCreator("Marcos Gabriel Cruz Montiel");
                    // Abrimos el documento.
                    doc.Open();
                    // Creamos el tipo de fuente, tamaño, estilo y color que vamos a utilizar.
                    Font fontPrincipal = new Font(Font.HELVETICA, 10, Font.BOLD, BaseColor.White);
                    Font fontBody      = new Font(Font.HELVETICA, 8, Font.NORMAL, BaseColor.Black);
                    // Añadimos el encabezado del documento.
                    doc.Add(new Paragraph("Reporte - Personas"));
                    doc.Add(Chunk.Newline);
                    // Creamos la tabla que contendrá los registro de la tabla ComPersona.
                    PdfPTable tblPersona = new PdfPTable(7)
                    {
                        WidthPercentage = 100
                    };
                    // Configuramos el titulo de las columnas.
                    PdfPCell colNombre = new PdfPCell(new Phrase("Nombre", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colAPaterno = new PdfPCell(new Phrase("A. Paterno", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colAMaterno = new PdfPCell(new Phrase("A. Materno", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colGenero = new PdfPCell(new Phrase("Género", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colFechaNac = new PdfPCell(new Phrase("Fecha de Nac.", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colCurp = new PdfPCell(new Phrase("C.U.R.P", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colEscolaridad = new PdfPCell(new Phrase("Escolaridad", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    // Añadimos las celdas a la tabla.
                    tblPersona.AddCell(colNombre);
                    tblPersona.AddCell(colAPaterno);
                    tblPersona.AddCell(colAMaterno);
                    tblPersona.AddCell(colGenero);
                    tblPersona.AddCell(colFechaNac);
                    tblPersona.AddCell(colCurp);
                    tblPersona.AddCell(colEscolaridad);

                    // Llenamos la tabla de información.
                    foreach (var item in persona)
                    {
                        colNombre = new PdfPCell(new Phrase(item.Nombre, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colAPaterno = new PdfPCell(new Phrase(item.APaterno, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colAMaterno = new PdfPCell(new Phrase(item.AMaterno, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colGenero = new PdfPCell(new Phrase(item.ComCatSexo.Nombre, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colFechaNac = new PdfPCell(new Phrase(item.FechaNac.ToShortDateString(), fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colCurp = new PdfPCell(new Phrase(item.Curp, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colEscolaridad = new PdfPCell(new Phrase(item.ComCatEscolaridad.Nombre, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        // Añadimos las celdas a la tabla.
                        tblPersona.AddCell(colNombre);
                        tblPersona.AddCell(colAPaterno);
                        tblPersona.AddCell(colAMaterno);
                        tblPersona.AddCell(colGenero);
                        tblPersona.AddCell(colFechaNac);
                        tblPersona.AddCell(colCurp);
                        tblPersona.AddCell(colEscolaridad);
                    }

                    // Añadimos la tabla al documento.
                    doc.Add(tblPersona);

                    doc.Close();
                    writer.Close();
                }

                // Ordenar valores desc y asc en la tabla
                ViewData["NameOrderAscDesc"] = String.IsNullOrEmpty(valuesOrder) ? "nombre_desc" : "";
                ViewData["APatOrderAscDesc"] = valuesOrder == "paterno_asc" ? "paterno_desc" : "paterno_asc";
                ViewData["AMatOrderAscDesc"] = valuesOrder == "materno_asc" ? "materno_desc" : "materno_asc";

                switch (valuesOrder)
                {
                case "nombre_desc":
                    persona = persona.OrderByDescending(s => s.Nombre);
                    break;

                case "paterno_desc":
                    persona = persona.OrderByDescending(s => s.APaterno);
                    break;

                case "paterno_asc":
                    persona = persona.OrderBy(s => s.APaterno);
                    break;

                case "materno_desc":
                    persona = persona.OrderByDescending(s => s.AMaterno);
                    break;

                case "materno_asc":
                    persona = persona.OrderBy(s => s.AMaterno);
                    break;

                default:
                    persona = persona.OrderBy(s => s.Nombre);
                    break;
                }

                // Caja de búsqueda
                ViewData["CurrentFilter"] = searchPerson;

                if (!String.IsNullOrEmpty(searchPerson))
                {
                    persona = persona.Where(s => s.Nombre.Contains(searchPerson) || s.APaterno.Contains(searchPerson));
                }

                return(View(await persona.AsNoTracking().ToListAsync()));
            }
            catch (Exception ex)
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Send", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Reception", "*****@*****.**"));
                message.Subject = "Exceptions";
                message.Body    = new TextPart("plain")
                {
                    Text = "Excepción encontrada: " + ex.StackTrace
                };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    client.Authenticate("*****@*****.**", "PruebaExcepciones123");
                    client.Send(message);
                    client.Disconnect(true);
                }

                return(null);
            }
        }