public void ListarLinks(DateTime comp)
        {
            contador = comp.Month;

            while (contador > 0)
            {
                IWebElement pesquisa = driver.FindElement(By.LinkText(contador.ToString("00") + "/" + comp.Year.ToString("0000")));
                pesquisa.SendKeys(OpenQA.Selenium.Keys.Enter);


                ICollection <IWebElement> links   = driver.FindElements(By.TagName("a"));
                ICollection <IWebElement> valores = driver.FindElements(By.TagName("td"));
                for (int i = 0; i < links.Count() - 1; i++)
                {
                    links = driver.FindElements(By.TagName("a"));
                    var numDoc = links.ElementAt(i).Text;
                    links.ElementAt(i).Click();
                    string path  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "aux.html";
                    string path2 = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\GPS";
                    Directory.CreateDirectory(path2);
                    File.WriteAllText(path, driver.PageSource, Encoding.UTF8);
                    string html      = File.ReadAllText(path, Encoding.UTF8);
                    var    htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                    htmlToPdf.GeneratePdfFromFile(path, null, Path.GetFullPath(path2) + "\\" + contador.ToString("00") + comp.Year + "_" + numDoc + ".pdf");
                    driver.Navigate().Back();
                }

                driver.FindElements(By.TagName("a"));
                driver.FindElements(By.TagName("a")).LastOrDefault().Click();
                contador--;
            }

            driver.Close();
            Console.WriteLine("Finalizado");
        }
Ejemplo n.º 2
0
        private void BtnClick_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(TxtURL.Text);
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.GeneratePdfFromFile("TxtURL.Text", null, "export.pdf");
        }
Ejemplo n.º 3
0
        protected void Imprimir(object sender, EventArgs e)
        {
            var htmlContent = String.Format("<body>Tiquete de Cine: {0}</body>",
                                            DateTime.Now);
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes  = htmlToPdf.GeneratePdf(htmlContent);

            htmlToPdf.GeneratePdfFromFile("Ticket.html/", null, "export.pdf");
        }
Ejemplo n.º 4
0
        public bool ConvertHtmlToPdf(string url, string storePath)
        {
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(storePath))
            {
                return(false);
            }
            var pdfGenerator = new NReco.PdfGenerator.HtmlToPdfConverter();

            pdfGenerator.GeneratePdfFromFile(url, null, storePath);
            return(true);
        }
Ejemplo n.º 5
0
 private void BtnClick_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         MessageBox.Show(TxtURL.Text);
         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         htmlToPdf.GeneratePdfFromFile(TxtURL.Text, null, "export.pdf");
     }
     catch (Exception TxtURL)
     {
         MessageBox.Show("The URL you have entered is invalid" + TxtURL.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
     }
 }
 public override void OnResultExecuted(ResultExecutedContext filterContext)
 {
     if (filterContext.RequestContext.HttpContext.Request.QueryString.GetValues("convert") != null)
     {
         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         filterContext.RequestContext.HttpContext.Response.Clear();
         filterContext.RequestContext.HttpContext.Response.ContentType = "application/pdf";
         htmlToPdf.GeneratePdfFromFile(
             filterContext.RequestContext.HttpContext.Request.Url.AbsoluteUri.Split('?')[0], null,
             filterContext.RequestContext.HttpContext.Response.OutputStream);
     }
     base.OnResultExecuted(filterContext);
 }
Ejemplo n.º 7
0
        public ActionResult PDF(string Facultet, string Gruppa, string Disciplina)
        {
            try
            {
                var    htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                string nazvanie  = "";
                htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
                int GruppaID     = int.Parse(Gruppa);
                int DisciplinaID = int.Parse(Disciplina);

                string GruppaName =
                    (from g in contextDB.tableGrupp
                     where g.ID == GruppaID
                     select g.Name).First().ToString();

                string DisciplinaName =
                    (from g in contextDB.tableDisciplin
                     where g.ID == DisciplinaID
                     select g.Name).First().ToString();

                string Host   = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("Teacher") - 1);
                string Zapros = Url.Action("ProsmotrAttVedomosti", "Teacher", new { Facultet = Facultet, Gruppa = Gruppa, Disciplina = Disciplina });
                string put    = Host + Zapros;
                int    rol    = 0;
                try
                {
                    rol =
                        (from r in contextDB.teachersAccounts
                         where r.Login == User.Identity.Name
                         select r.Role_ID).First();
                }
                catch
                {
                }
                if (rol == 2)
                {
                    byte[] pdfBytes = htmlToPdf.GeneratePdfFromFile(put, null);
                    Response.AddHeader("Content-Disposition", "inline; filename=" + nazvanie);
                    return(File(pdfBytes, "application/pdf"));
                }
                else
                {
                    return(View("NotFound"));
                }
            }
            catch
            {
                return(View("Error"));
            }
        }
Ejemplo n.º 8
0
 public static void ConvertHtmlToPdf()
 {
     try
     {
         //String html = File.ReadAllText("www.elmbergdevelopment.se/lunch/");
         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         //htmlToPdf.GeneratePdf(html, null, "C:/temp/lunchToPdf.pdf");
         htmlToPdf.GeneratePdfFromFile("http://www.nrecosite.com/", null, "C:/temp/htmlToPdf.pdf");
     }
     catch (Exception e)
     {
         throw;
     }
 }
Ejemplo n.º 9
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");


            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes  = htmlToPdf.GeneratePdfFromFile("<file_path_including_sas_token>", "");

            var response = req.CreateResponse(HttpStatusCode.OK);

            response.Content = new StreamContent(new MemoryStream(pdfBytes));
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            return(response);
        }
Ejemplo n.º 10
0
        public string Get(int id)
        {
            List <Product> pro   = new List <Product>();
            List <Items>   items = new List <Items>();

            items.Add(new Items {
                Id = 1, Name = "haha"
            });
            items.Add(new Items {
                Id = 2, Name = "gaga"
            });
            pro.Add(new Product {
                Id = 1, OrderNumber = "12345", Items = items
            });
            string body = string.Empty;

            using (StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/Reports/22.html")))

            {
                body = reader.ReadToEnd();
            }

            body = body.Replace("{data}", new JavaScriptSerializer().Serialize(pro)); //replacing the required things

            //var htmlToImageConv = new NReco.PdfGenerator.HtmlToPdfConverter();
            //var jpegBytes = htmlToImageConv.GeneratePdfFromFile(System.Web.HttpContext.Current.Server.MapPath("~/Reports/22.html"), body);
            Stream str             = null;
            var    htmlToImageConv = new NReco.PdfGenerator.HtmlToPdfConverter();

            // htmlToImageConv.Zoom = 1;
            htmlToImageConv.Size        = NReco.PdfGenerator.PageSize.A4;
            htmlToImageConv.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;

            var jpegBytes = htmlToImageConv.GeneratePdfFromFile(System.Web.HttpContext.Current.Server.MapPath("~/Reports/22.html"), "");
            // var jpegBytes = convertHTMLToImage(body);

            //var jpegBytes = System.Text.Encoding.UTF8.GetBytes(body);
            string base64String = Convert.ToBase64String(jpegBytes);

//            byte[] bytes = Convert.FromBase64String(base64String);
//            System.IO.FileStream stream =
//new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/Reports/33344.pdf"), FileMode.CreateNew);
//            System.IO.BinaryWriter writer =
//                new BinaryWriter(stream);
//            writer.Write(bytes, 0, bytes.Length);
//            writer.Close();
            return(base64String);
        }
Ejemplo n.º 11
0
 public ActionResult PDFStatistic(string Facultet_ID)
 {
     try
     {
         var    htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         string Host      = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("Admin") - 1);
         string Zapros    = Url.Action("Statistic", "Admin", new { Facultet_ID = Facultet_ID });
         int    Fac_ID    = int.Parse(Facultet_ID);
         string FacName   =
             (from fn in contextDB.tableFacultet
              where fn.ID == Fac_ID
              select fn.Name).First();
         string nazvanie = FacName + ": Статистика";
         string put      = Host + Zapros;
         int    rol      = 0;
         try
         {
             rol =
                 (from r in contextDB.tableAdmins
                  where r.Login == User.Identity.Name
                  select r.Role_ID).First();
         }
         catch
         {
         }
         if (rol == 1)
         {
             byte[] pdfBytes = htmlToPdf.GeneratePdfFromFile(put, null);
             Response.AddHeader("Content-Disposition", "inline; filename=" + nazvanie);
             return(File(pdfBytes, "application/pdf"));
         }
         else
         {
             return(View("NotFound"));
         }
     }
     catch
     {
         return(View("Error"));
     }
 }
Ejemplo n.º 12
0
 public ActionResult PDFSvodJournal(string Facultet, string Gruppa)
 {
     try
     {
         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
         string Host   = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("Admin") - 1);
         string Zapros = Url.Action("SvodniyJurnal", "Admin", new { Facultet = Facultet, Gruppa = Gruppa });
         string put    = Host + Zapros;
         int    rol    = 0;
         try
         {
             rol =
                 (from r in contextDB.tableAdmins
                  where r.Login == User.Identity.Name
                  select r.Role_ID).First();
         }
         catch
         {
         }
         if (rol == 1)
         {
             byte[] pdfBytes = htmlToPdf.GeneratePdfFromFile(put, null);
             Response.AddHeader("Content-Disposition", "inline; filename=" + "SvodniyJournal");
             return(File(pdfBytes, "application/pdf"));
         }
         else
         {
             return(View("NotFound"));
         }
     }
     catch
     {
         return(View("Error"));
     }
 }
Ejemplo n.º 13
0
        public byte[] ConvertHtmlToPdfFromUrl(string url)
        {
            var pdfGenerator = new NReco.PdfGenerator.HtmlToPdfConverter();

            return(pdfGenerator.GeneratePdfFromFile(url, null));
        }
        public string GenertePDF(string pdfData)
        {
            StringWriter sw = new StringWriter();
            string css = System.IO.File.ReadAllText(Server.MapPath("~/Content/bootstrap.min.css"));
            string responsive = System.IO.File.ReadAllText(Server.MapPath("~/Content/responsive.css"));
            string html = "<html><head><style>"
                + css
                + "#header{display:none;}#printbtn{display:none;}@media screen and (max-width:768px){body{font-size:11px!important;}#mainDiv{font-size:11px!important;}.s-p-sign>.p-sign{min-width: 22%;padding: 8px 4px; margin-right:2px; font-size: 10px;text-align: center;word-wrap: break-word;width: auto;}.legendmilestone2 {font-weight: normal; font-size: 11px;padding: 8px 4px; margin-right:2px; margin-top:10px;display:inline-block;}.fa-stop{transform: rotate(45deg);}}</style></head><body >"
                + pdfData
                + "</body></html>";

            string path = Server.MapPath("~/Temp/PDF" + Guid.NewGuid().ToString().Substring(0, 6) + ".html");

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(html);
                fs.Write(info, 0, info.Length);

            }
            string pdfFileName = "ProjectSummaryDetail" + Guid.NewGuid().ToString().Substring(0, 6) + ".pdf";
            string filePath = Server.MapPath("~/Temp/" + pdfFileName);
            StringBuilder sb = new StringBuilder();
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
            var coverHTML = "";
            htmlToPdf.GeneratePdfFromFile(path, coverHTML, filePath);
            System.IO.File.Delete(path);
            return filePath;
        }
Ejemplo n.º 15
0
        public ActionResult PDFJournal()
        {
            try
            {
                int ID_Prepoda =
                    //2 раза
                    (from t in contextDB.teachersAccounts
                     where t.Login == User.Identity.Name
                     from p in contextDB.tablePrepods
                     where t.ID_Prepoda == p.ID
                     select p.ID).First();

                string PrepodName =
                    (from p in contextDB.tablePrepods
                     where p.ID == ID_Prepoda
                     select p.Name).First();
                ViewBag.PrepodName = PrepodName;

                var prinadlegnostDisciplin =
                    from pd in contextDB.tablePrinadlegnistDisciplin
                    where pd.ID_Prepoda == ID_Prepoda
                    orderby pd.ID_Gruppi, pd.ID_Disciplini
                    select new TeachersData {
                    prinadlegnostDisciplin_ID = pd.ID, Gruppa_ID = pd.ID_Gruppi, Gruppa = pd.tableGrupp.Name, Prepod_ID = pd.ID_Prepoda, Prepod = PrepodName, Facultet_ID = pd.ID_Facultet, Facultet = pd.tableFacultet.Name, Disciplina_ID = pd.ID_Disciplini, Disciplina = pd.tableDisciplin.Name
                };
                ViewBag.PrinadlegnostDisciplin = prinadlegnostDisciplin;


                var students =
                    from s in contextDB.tableStudents
                    select s;
                ViewBag.Students = students;


                var    htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                string nazvanie  = "Журнал.pdf";
                htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Portrait;

                string Host   = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("Journal") - 1);
                string Zapros = Url.Action("CreateJournal", "Journal", new { prepod_ID = ID_Prepoda });
                string put    = Host + Zapros;
                int    rol    = 0;
                try
                {
                    rol =
                        (from r in contextDB.teachersAccounts
                         where r.Login == User.Identity.Name
                         select r.Role_ID).First();
                }
                catch
                {
                }
                if (rol == 2)
                {
                    byte[] pdfBytes = htmlToPdf.GeneratePdfFromFile(put, null);
                    Response.AddHeader("Content-Disposition", "inline; filename=" + nazvanie);
                    return(File(pdfBytes, "application/pdf"));
                }
                else
                {
                    return(View("NotFound"));
                }
            }
            catch
            {
                return(View("Error"));
            }
        }
Ejemplo n.º 16
0
        public ActionResult PDF(string Facultet, string Gruppa, string Disciplina, string Vedomost, string VidVedomost)
        {
            try
            {
                var    htmlToPdf    = new NReco.PdfGenerator.HtmlToPdfConverter();
                string nazvanie     = "";
                string MetodPechati = "";
                int    GruppaID     = int.Parse(Gruppa);
                int    DisciplinaID = int.Parse(Disciplina);

                string GruppaName =
                    (from g in contextDB.tableGrupp
                     where g.ID == GruppaID
                     select g.Name).First().ToString();

                string DisciplinaName =
                    (from g in contextDB.tableDisciplin
                     where g.ID == DisciplinaID
                     select g.Name).First().ToString();

                if (VidVedomost == "ATT")
                {
                    htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
                    MetodPechati          = "ProsmotrAttVedomosti";
                    nazvanie = "Атт. ведомость " + GruppaName + " по дисциплине " + " .pdf";
                }
                else
                {
                    htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Portrait;
                    MetodPechati          = "ProsmotrEkzVedomosti";
                    nazvanie = "Зач./Экз. ведомость " + GruppaName + " по дисциплине " + " .pdf";
                }
                string Host   = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("Admin") - 1);
                string Zapros = Url.Action(MetodPechati, "Admin", new { Facultet = Facultet, Gruppa = Gruppa, Disciplina = Disciplina, Vedomost = Vedomost });
                string put    = Host + Zapros;
                int    rol    = 0;
                try
                {
                    rol =
                        (from r in contextDB.tableAdmins
                         where r.Login == User.Identity.Name
                         select r.Role_ID).First();
                }
                catch
                {
                }
                if (rol == 1)
                {
                    byte[] pdfBytes = htmlToPdf.GeneratePdfFromFile(put, null);
                    Response.AddHeader("Content-Disposition", "inline; filename=" + nazvanie);
                    return(File(pdfBytes, "application/pdf"));
                }
                else
                {
                    return(View("NotFound"));
                }
            }
            catch
            {
                return(View("Error"));
            }
        }
Ejemplo n.º 17
0
        public static void relCliente()
        {
            Camadas.DAL.Clientes          bllCliente  = new Camadas.DAL.Clientes();
            List <Camadas.MODEL.Clientes> lstClientes = new List <Camadas.MODEL.Clientes>();

            lstClientes = bllCliente.Select();

            string pasta      = Funcoes.diretorioPasta();
            string arquivo    = pasta + @"\RelClientes_" + DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".html";
            string arquivoPDF = pasta + @"\RelClientes_" + DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".pdf";

            StreamWriter sw = new StreamWriter(arquivo);

            using (sw)
            {
                sw.WriteLine("<html>");

                sw.WriteLine("<head>");
                sw.WriteLine("<meta http-equiv='Content-Type' " +
                             "content='text/html; charset=utf-8'/>");
                sw.WriteLine("<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'>");
                sw.WriteLine("</head>");

                sw.WriteLine("<body>");
                sw.WriteLine("<h1>RELATÓRIO DE CLIENTES</h1>");
                sw.WriteLine("<h6> <i>");
                sw.WriteLine("Gerado em " + DateTime.Now.ToString());
                sw.WriteLine("</i></h6>");
                sw.WriteLine("</br>");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("<table class='table table-striped'>");
                sw.WriteLine("<tr align='center'>");
                sw.WriteLine("<th align='center' width='30px'>");
                sw.WriteLine("ID");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='left' width='150px'>");
                sw.WriteLine("NOME");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='left' width='150px'>");
                sw.WriteLine("ENDERECO");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='center' width='150px'>");
                sw.WriteLine("FONE");
                sw.WriteLine("</th>");
                sw.WriteLine("</tr>");

                int cont = 0;
                foreach (Camadas.MODEL.Clientes cliente in lstClientes.OrderBy(o => o.nome))
                {
                    sw.WriteLine("<tr>");
                    sw.WriteLine("<td align='center' width='30px'>");
                    sw.WriteLine(cliente.idCli);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='left' width='150px'>");
                    sw.WriteLine(cliente.nome);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='left' width='150px'>");
                    sw.WriteLine(cliente.endereco);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='center' width='150px'>");
                    sw.WriteLine(cliente.fone);
                    sw.WriteLine("</td>");
                    sw.WriteLine("</tr>");
                    cont++;
                }

                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("</table>");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("<h5>");
                sw.WriteLine("Total de Clientes: " + cont.ToString());
                sw.WriteLine("</br>");
                sw.WriteLine("</h5>");
                sw.WriteLine("</body>");

                sw.WriteLine("</html>");
            }
            System.Diagnostics.Process.Start(arquivo);

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.CustomWkHtmlArgs = "--dpi 300";
            htmlToPdf.GeneratePdfFromFile(arquivo, null, arquivoPDF);
        }
Ejemplo n.º 18
0
        public string CrearPdf(PagareContrato pagareContrato)
        {
            Guid x = Guid.NewGuid();

            manager = new Manager.Manager();
            Utilitario  Util          = new Utilitario();
            Solicitudes solicitudes   = new Solicitudes();
            var         pagareCon     = new List <PagareContrato>();
            var         datosContrato = new List <PagareContrato>();

            string xClase      = string.Format("{0}|{1}", MethodBase.GetCurrentMethod().Module.Name, MethodBase.GetCurrentMethod().DeclaringType.Name);
            string xProceso    = MethodBase.GetCurrentMethod().Name;
            string strHostName = System.Net.Dns.GetHostName();
            //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); <-- Obsolete
            IPHostEntry ipHostInfo = Dns.GetHostEntry(strHostName);
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];

            Tab_ConfigSys dto_Config = new Tab_ConfigSys();

            dto_Config.llave_Config1 = "SERVICIO";
            dto_Config.llave_Config2 = "CONFIGURACION";
            dto_Config.llave_Config3 = "SERVIDOR";
            dto_Config.llave_Config4 = "DIRECTORIO";
            dto_Config.llave_Config5 = "CONTRATOPAGARE";

            solicitudes.IdTipoIdentificacion = pagareContrato.IdTipoIdentificacion;
            solicitudes.Identificacion       = pagareContrato.Identificacion;

            var dto_DatosCredito = manager.CargarDatosCredito(solicitudes);

            var    dto_interval = manager.ConsultaConfiUrlImagen(dto_Config);
            string URL          = dto_interval.Where(y => y.llave_Config5 == "CONTRATOPAGARE").Select(y => y.Dato_Char1).FirstOrDefault();

            var dto_excepcion = new UTL_TRA_EXCEPCION
            {
                STR_CLASE      = xClase,
                STR_EVENTO     = xProceso,
                STR_APLICATIVO = ConfigurationManager.AppSettings["APLICATIVO"].ToString(),
                STR_SERVIDOR   = ipAddress.ToString(),
                STR_PARAMETROS = JsonConvert.SerializeObject(pagareContrato),
                FEC_CREACION   = DateTime.Now
            };

            try
            {
                if (dto_DatosCredito.Any())
                {
                    pagareCon = manager.TraeDocumentoPagare();
                    pagareContrato.IdSolicitud       = dto_DatosCredito.FirstOrDefault().IdSolicitud;
                    pagareContrato.fechagenerapagare = DateTime.Today;
                    datosContrato           = manager.PagareContrato(pagareContrato);
                    pagareContrato.Pagare   = pagareCon.FirstOrDefault().Pagare;
                    pagareContrato.Contrato = pagareCon.FirstOrDefault().Contrato;

                    string Contrato = pagareContrato.Contrato;
                    string Pagare   = pagareContrato.Pagare;
                    string fileName = @"Pagare y contrato_" + datosContrato[0].Nombre + ".docx";

                    //Remplazo en la cadena los datos para generar el contrato
                    Contrato = Contrato.Replace("<Nombre>", datosContrato[0].Nombre);
                    Contrato = Contrato.Replace("<Identificacion>", datosContrato[0].Identificacion);
                    Contrato = Contrato.Replace("<MontoProductoLetras>", datosContrato[0].MontoProductoLetras);
                    Contrato = Contrato.Replace("<Moneda>", datosContrato[0].Moneda);
                    Contrato = Contrato.Replace("<MontoProducto>", Convert.ToString(datosContrato[0].MontoProducto));
                    Contrato = Contrato.Replace("<CantidadCuotas>", Convert.ToString(datosContrato[0].CantidadCuotas));
                    Contrato = Contrato.Replace("<Frecuencia>", datosContrato[0].Frecuencia);
                    Contrato = Contrato.Replace("<Cuota>", Convert.ToString(datosContrato[0].Cuota));
                    Contrato = Contrato.Replace("<FechaPrimerPagoLetras>", datosContrato[0].FechaPrimerPagoLetras);
                    Contrato = Contrato.Replace("<FechaUltimoPagoLetras>", datosContrato[0].FechaUltimoPagoLetras);
                    Contrato = Contrato.Replace("<Interes>", Convert.ToString(datosContrato[0].Interes));
                    Contrato = Contrato.Replace("<InteresLetras>", datosContrato[0].InteresLetras);
                    Contrato = Contrato.Replace("<CtaCliente>", datosContrato[0].CtaCliente);
                    Contrato = Contrato.Replace("<FechaHoy>", datosContrato[0].FechaHoy);
                    Contrato = Contrato.Replace("<CuotaenLetras>", datosContrato[0].CuotaenLetras);
                    Contrato = Contrato.Replace("<Frecuencia2>", datosContrato[0].Frecuencia2);
                    Contrato = Contrato.Replace("<Frecuencia3>", datosContrato[0].Frecuencia3);
                    Contrato = Contrato.Replace("<CantidadCuotasLetras>", datosContrato[0].CantidadCuotasLetras);

                    //Reemplazo los datos para generar el Pagaré
                    Pagare = Pagare.Replace("<Nombre>", datosContrato[0].Nombre);
                    Pagare = Pagare.Replace("<Identificacion>", datosContrato[0].Identificacion);
                    Pagare = Pagare.Replace("<MontoProductoLetras>", datosContrato[0].MontoProductoLetras);
                    Pagare = Pagare.Replace("<Moneda>", datosContrato[0].Moneda);
                    Pagare = Pagare.Replace("<MontoProductoPagare>", Convert.ToString(datosContrato[0].MontoProductoPagare));
                    Pagare = Pagare.Replace("<MontoProductoLetrasPagare>", Convert.ToString(datosContrato[0].MontoProductoLetrasPagare));
                    Pagare = Pagare.Replace("<CantidadCuotas>", Convert.ToString(datosContrato[0].CantidadCuotas));
                    Pagare = Pagare.Replace("<Frecuencia>", datosContrato[0].Frecuencia);
                    Pagare = Pagare.Replace("<Cuota>", Convert.ToString(datosContrato[0].Cuota));
                    Pagare = Pagare.Replace("<FechaPrimerPagoLetras>", datosContrato[0].FechaPrimerPagoLetras);
                    Pagare = Pagare.Replace("<FechaUltimoPagoLetras>", datosContrato[0].FechaUltimoPagoLetras);
                    Pagare = Pagare.Replace("<Interes>", Convert.ToString(datosContrato[0].Interes));
                    Pagare = Pagare.Replace("<InteresLetras>", datosContrato[0].InteresLetras);
                    Pagare = Pagare.Replace("<CtaCliente>", datosContrato[0].CtaCliente);
                    Pagare = Pagare.Replace("<FechaHoy>", datosContrato[0].FechaHoy);
                    Pagare = Pagare.Replace("<CuotaenLetras>", datosContrato[0].CuotaenLetras);
                    Pagare = Pagare.Replace("<CantidadCuotasLetras>", datosContrato[0].CantidadCuotasLetras);
                    Pagare = Pagare.Replace("<Frecuencia2>", datosContrato[0].Frecuencia2);
                    Pagare = Pagare.Replace("<pagoProximasCuotas>", datosContrato[0].PagoProximasCuotas);

                    //creamos la imagen editada de la firma para agregarla luego al documento
                    if (datosContrato[0].FotoFirma != "")
                    {
                        editarImagen(datosContrato[0].FotoFirma);
                    }

                    //Doy formato al archivo PDF
                    iTextSharp.text.Font fontHeader_1 = FontFactory.GetFont("Calibri", 9, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));
                    //Genero el documento PDF con la libreria iTextSharp
                    using (Document pdfDoc = new Document(PageSize.LETTER, 25f, 25f, 25f, 25f))
                    {
                        iTextSharp.text.Document oDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
                        //Escribo el documento en el archivo PDF generado
                        //PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);

                        var OutputPathDocumento = AppDomain.CurrentDomain.BaseDirectory + "/Machote/archivos/Documento-" + datosContrato.FirstOrDefault().Nombre.ToString() + x + ".pdf";
                        using (PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(OutputPathDocumento, FileMode.Create)))
                        {
                            pdfDoc.Open();

                            var espacio = new Paragraph(" ");
                            //Ingreso el texto que corresponde al Contrato
                            var tituloContrato = new Paragraph("Solicitud N°: " + datosContrato.FirstOrDefault().Id.ToString(), FontFactory.GetFont("Calibri", 14, BaseColor.BLACK));
                            tituloContrato.Alignment = Element.ALIGN_CENTER;
                            tituloContrato.Font.Size = 14;
                            pdfDoc.Add(tituloContrato);
                            pdfDoc.Add(espacio);
                            var Contratopdf = new Paragraph(Contrato, fontHeader_1);
                            Contratopdf.Alignment = Element.ALIGN_JUSTIFIED;
                            Contratopdf.Font.Size = 8;
                            pdfDoc.Add(Contratopdf);


                            //si existe foto de la firma lo agregamos al contrato
                            if (datosContrato[0].FotoFirma != "")
                            {
                                //creamos la imagen de la firma para el PDF
                                iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\FotoFirma-Copia-Editada.png");
                                imagen.BorderWidth = 0;
                                imagen.Alignment   = Element.ALIGN_LEFT;
                                float percentage = 0.0f;
                                percentage = 70 / imagen.Width;
                                imagen.ScalePercent(percentage * 100);

                                //creamos una tabla para agregar la imagen
                                PdfPTable tablaImagen = new PdfPTable(1);;
                                PdfPCell  c1          = new PdfPCell();
                                PdfPCell  c2          = new PdfPCell(imagen);
                                c1.Border              = 0;
                                c2.Border              = 0;
                                c2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                c2.HorizontalAlignment = Element.ALIGN_LEFT;
                                tablaImagen.AddCell(c1); //celda con espacio a la derecha
                                tablaImagen.AddCell(c2); //celda con la imagen de la firma

                                // Insertamos la tabla con la imagen de la firma en el contrato
                                pdfDoc.Add(tablaImagen);
                            }
                            else
                            {
                                pdfDoc.Add(espacio);
                                pdfDoc.Add(espacio);
                            }

                            //Agregamos la info final del contrato
                            string textoFinal   = "               ……………………………………………                                                                                          ……………………………………………\n                                   El DEUDOR                                                                                                                                   LA ACREEDORA\n\n\n                                    " + datosContrato.FirstOrDefault().Identificacion.ToString() + "\n               …………………………………………      \n                                     CÉDULA ";
                            var    parrafoFinal = new Paragraph(textoFinal, fontHeader_1);
                            pdfDoc.Add(parrafoFinal);

                            //Ingreso el titulo del Pagaré
                            pdfDoc.NewPage();
                            var SubtituloPdf = new Paragraph("Pagaré N°: " + datosContrato.FirstOrDefault().Id.ToString(), FontFactory.GetFont("Calibri", 14, BaseColor.BLACK));
                            SubtituloPdf.Alignment = Element.ALIGN_CENTER;
                            SubtituloPdf.Font.Size = 14;
                            pdfDoc.Add(SubtituloPdf);
                            pdfDoc.Add(espacio);
                            //Ingreso Texto de Pagare
                            var PagarePdf = new Paragraph(Pagare, FontFactory.GetFont("Calibri", 10, BaseColor.BLACK));
                            PagarePdf.Alignment = Element.ALIGN_JUSTIFIED;
                            PagarePdf.Font.Size = 10;
                            pdfDoc.Add(PagarePdf);

                            if (datosContrato[0].FotoFirma != "")
                            {
                                iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\FotoFirma-Copia-Editada.png");
                                imagen.BorderWidth = 0;
                                imagen.Alignment   = Element.ALIGN_LEFT;
                                float percentage = 0.0f;
                                percentage = 70 / imagen.Width;
                                imagen.ScalePercent(percentage * 100);
                                // Insertamos la imagen de la firma en el Pagare
                                PdfPTable tablaImagenPagare       = new PdfPTable(5);;
                                iTextSharp.text.Phrase fraseFirma = new iTextSharp.text.Phrase("Firma Deudor:");
                                fraseFirma.Font.Size = 10;
                                PdfPCell espacioCelda = new PdfPCell();
                                PdfPCell celdaTexto   = new PdfPCell(fraseFirma);
                                PdfPCell celdaFirma   = new PdfPCell(imagen);
                                espacioCelda.Border            = 0;
                                celdaTexto.Border              = 0;
                                celdaTexto.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                celdaTexto.HorizontalAlignment = Element.ALIGN_LEFT;
                                celdaFirma.Border              = 0;
                                celdaFirma.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                celdaFirma.HorizontalAlignment = Element.ALIGN_LEFT;
                                tablaImagenPagare.AddCell(celdaTexto);   //celda con el texto de la firma
                                tablaImagenPagare.AddCell(celdaFirma);   //celda con la imagen de la firma
                                tablaImagenPagare.AddCell(espacioCelda); //celda con espacio en blanco
                                tablaImagenPagare.AddCell(espacioCelda); //celda con espacio en blanco
                                tablaImagenPagare.AddCell(espacioCelda); //celda con espacio en blanco
                                pdfDoc.Add(tablaImagenPagare);
                            }
                            else
                            {
                                var parrafoFirma = new Paragraph("\n\n                     Firma Deudor: \n\n\n", fontHeader_1);
                                parrafoFirma.Font.Size = 10;
                                pdfDoc.Add(parrafoFirma);
                            }
                            //Agregamos la info final del contrato
                            string textoFinalPagare   = "                     Nombre Completo:   " + datosContrato[0].Nombre + "\n\n\n                     Número de Cédula:   " + datosContrato[0].Identificacion;
                            var    parrafoFinalPagare = new Paragraph(textoFinalPagare, fontHeader_1);
                            parrafoFinalPagare.Font.Size = 10;
                            pdfDoc.Add(parrafoFinalPagare);
                            //Cierro el archivo PDF
                            pdfDoc.Close();
                            wri.Close();
                        }
                        oDoc.Close();
                    }

                    //Proceso para crear y agregar el formulario BCCR a el pdf final
                    var    path          = @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\formulario-bac.html";
                    var    pathOriginal  = @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\formulario-bac-sin-remplazo.html";
                    string html          = File.ReadAllText(pathOriginal);
                    string EncodedString = "";
                    string ret           = "";
                    string DecodedStringFormulario;
                    string htmlOriginal = html; //este sera el html orinal sin hacer los remplazas para luego de todo el proceso volver a guaradr el archivo html con los valores originales
                    using (StringWriter writer = new StringWriter())
                    {
                        HttpUtility.HtmlEncode(html, writer);

                        //Server.HtmlEncode(html, writer);
                        EncodedString           = html.ToString();
                        ret                     = completarFormularioDomiciliacion(EncodedString, datosContrato[0]); // replazamos el html con la info dinamica
                        DecodedStringFormulario = HttpUtility.HtmlDecode(ret);                                       //Server.HtmlDecode(ret);
                        writer.Close();
                    }
                    using (StreamWriter sw = new StreamWriter(path)) //sobrescribimos el html con la nueva info
                    {
                        sw.WriteLine(DecodedStringFormulario);
                        sw.Close();
                    }
                    //Generamos el pdf del formulario caon base en el archivo html

                    NReco.PdfGenerator.HtmlToPdfConverter pdfFormulario = new NReco.PdfGenerator.HtmlToPdfConverter();
                    pdfFormulario.PageHeight = 279;
                    pdfFormulario.PageWidth  = 216;
                    pdfFormulario.GeneratePdfFromFile(path, null, @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\archivos\Formulario-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf");

                    //llamamos al metodo interno mergePdfs para unir los pdfs del contrato, el pagare y el formulario
                    string rutaDocumentoFinal = URL + "/" + pagareContrato.Identificacion + "/" + "Contrato_Pagare_" + pagareContrato.Identificacion + ".pdf";


                    if (Util.ValidarFichero(rutaDocumentoFinal) == true)
                    {
                        rutaDocumentoFinal = Util.Renamefile(rutaDocumentoFinal, pagareContrato.Identificacion, ".pdf");
                        string[] archivos = { AppDomain.CurrentDomain.BaseDirectory + "/Machote/archivos/Documento-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf", @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\archivos\Formulario-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf" };
                        mergePdfs(rutaDocumentoFinal, archivos);
                    }
                    //volvemos a guaradar el archivo html Original(sin los valores remplazados)
                    using (StreamWriter sw = new StreamWriter(path))
                    {
                        sw.WriteLine(htmlOriginal);
                        sw.Close();
                    }
                    File.Delete(AppDomain.CurrentDomain.BaseDirectory + "/Machote/archivos/Documento-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf");
                    File.Delete(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\archivos\Formulario-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf");
                    File.Delete(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\FotoFirma-Copia-Editada.png");

                    return(rutaDocumentoFinal);
                }
            }
            catch (Exception ex)
            {
                dto_excepcion.STR_MENSAJE = ex.Message;
                DynamicSqlDAO.guardaExcepcion(dto_excepcion, GlobalClass.connectionString.Where(a => a.Key == infDto.STR_COD_PAIS).FirstOrDefault().Value);
                pagareContrato.Mensaje = "ERR";
            }

            return(null);
        }
Ejemplo n.º 19
0
        public static void relOrdem()
        {
            Camadas.BLL.Ordens          bllOrdem  = new Camadas.BLL.Ordens();
            List <Camadas.MODEL.Ordens> lstOrdens = new List <Camadas.MODEL.Ordens>();

            lstOrdens = bllOrdem.Select();

            string pasta      = Funcoes.diretorioPasta();
            string arquivo    = pasta + @"\RelOrdens_" + DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".html";
            string arquivoPDF = pasta + @"\RelOrdens_" + DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".pdf";

            StreamWriter sw = new StreamWriter(arquivo);

            using (sw)
            {
                sw.WriteLine("<html>");

                sw.WriteLine("<head>");
                sw.WriteLine("<meta http-equiv='Content-Type' " +
                             "content='text/html; charset=utf-8'/>");
                sw.WriteLine("<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'>");
                sw.WriteLine("</head>");

                sw.WriteLine("<body>");
                sw.WriteLine("<h1>RELATÓRIO DE ORDEM DE SERVIÇO</h1>");
                sw.WriteLine("<h6> <i>");
                sw.WriteLine("Gerado em " + DateTime.Now.ToString());
                sw.WriteLine("</i></h6>");
                sw.WriteLine("</br>");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("<table class='table table-striped'>");
                sw.WriteLine("<tr align='right'>");
                sw.WriteLine("<th align='center' width='50px'>");
                sw.WriteLine("ORDEM Nº");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='center' width='100px'>");
                sw.WriteLine("CLIENTE");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='center' width='100px'>");
                sw.WriteLine("EQUIPAMENTO");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='center' width='100px'>");
                sw.WriteLine("DEFEITO");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='center' width='100px'>");
                sw.WriteLine("VALOR");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='center' width='50px'>");
                sw.WriteLine("SITUAÇÃO");
                sw.WriteLine("</th>");
                sw.WriteLine("</tr>");

                int   cont = 0;
                float soma = 0;
                foreach (Camadas.MODEL.Ordens ordem in lstOrdens.OrderBy(o => o.idOrd))
                {
                    sw.WriteLine("<tr>");
                    sw.WriteLine("<td align='center' width='50px'>");
                    sw.WriteLine(ordem.idOrd);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='center' width='100px'>");
                    sw.WriteLine(ordem.nomeCli);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='center' width='100px'>");
                    sw.WriteLine(ordem.equipamento);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='center' width='100px'>");
                    sw.WriteLine(ordem.defeito);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='right' width='100px'>");
                    sw.WriteLine(string.Format("{0:C2}", ordem.valor));
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='center' width='50px'>");
                    sw.WriteLine(ordem.situacao);
                    sw.WriteLine("</td>");
                    sw.WriteLine("</tr>");
                    soma = soma + ordem.valor;
                    cont++;
                }

                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("</table>");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("<h5>");
                sw.WriteLine("Total de Registros: " + cont.ToString());
                sw.WriteLine("</br>");
                sw.WriteLine("Valor Total dos Registros: " + string.Format("{0:C2}", soma));
                sw.WriteLine("</h5>");
                sw.WriteLine("</body>");

                sw.WriteLine("</html>");
            }
            System.Diagnostics.Process.Start(arquivo);

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.CustomWkHtmlArgs = "--dpi 300";
            htmlToPdf.GeneratePdfFromFile(arquivo, null, arquivoPDF);
        }
Ejemplo n.º 20
0
        public static void relLivro()
        {
            CAMADAS.BLL.Livros          bllLivro  = new CAMADAS.BLL.Livros();
            List <CAMADAS.MODEL.Livros> lstLivros = new List <CAMADAS.MODEL.Livros>();

            lstLivros = bllLivro.Select();

            string pasta      = Funcoes.deretorioPasta();
            string arquivo    = pasta + @"\RelLivros_" + DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".html";
            string arquivoPDF = pasta + @"\RelLivros_" + DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".pdf";


            StreamWriter sw = new StreamWriter(arquivo);

            using (sw)
            {
                sw.WriteLine("<html>");
                sw.WriteLine("<head>");
                sw.WriteLine("<meta http-equiv='Content-Type' " +
                             "content='text/html; charset=utf-8'/>");
                sw.WriteLine("<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'>");

                sw.WriteLine("</head>");

                sw.WriteLine("<body>");
                sw.WriteLine("<h1>Relatório de Livros</h1>");
                sw.WriteLine("<hr align='left' border:'5px' />");

                sw.WriteLine("<table class='table table-striped'>");
                //Cabeçalho da tabela

                sw.WriteLine("<tr align='right'>");
                sw.WriteLine("<th align='right' width='30px'>");
                sw.WriteLine("ID");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='right' width='250px'>");
                sw.WriteLine("TITULO");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='right' width='150px'>");
                sw.WriteLine("EDITORA");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='right' width='150px'>");
                sw.WriteLine("AUTOR");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='right' width='150px'>");
                sw.WriteLine("VALOR");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='right' width='60px'>");
                sw.WriteLine("SITUAÇÃO");
                sw.WriteLine("</th>");
                sw.WriteLine("</tr>");

                int   cont = 0;
                float soma = 0;
                foreach (CAMADAS.MODEL.Livros livro in lstLivros.OrderBy(o => o.situacao).ThenBy(t => t.autor).ThenBy(w => w.titulo))
                {
                    sw.WriteLine("<tr>");
                    sw.WriteLine("<td align='right' width='30px'>");
                    sw.WriteLine(livro.id);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='right' width='250px'>");
                    sw.WriteLine(livro.titulo);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='right' width='150px'>");
                    sw.WriteLine(livro.editora);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='right' width='150px'>");
                    sw.WriteLine(livro.autor);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='right' width='150px'>");
                    sw.WriteLine(string.Format("{0:C2}", livro.valor));
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='right' width='60px'>");
                    sw.WriteLine(livro.situacao);
                    sw.WriteLine("</td>");
                    sw.WriteLine("</tr>");
                    soma = soma + livro.valor;
                    cont++;
                }



                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("</table>");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("<h2>");
                sw.WriteLine("Total de Registros Impressos: " + cont.ToString());
                sw.WriteLine("</br>");
                sw.WriteLine("Valor total dos Livros R$: " + string.Format("{0:#.#,00}", soma));
                sw.WriteLine("</body>");
                sw.WriteLine("</h2>");
                sw.WriteLine("</html>");
            }
            System.Diagnostics.Process.Start(arquivo);

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.CustomWkHtmlArgs = "--dpi 300";
            htmlToPdf.GeneratePdfFromFile(arquivo, null, arquivoPDF);
        }
Ejemplo n.º 21
0
        public static void relLivros()
        {
            CAMADAS.BLL.Livros          bllLivro  = new CAMADAS.BLL.Livros();
            List <CAMADAS.MODEL.Livros> lstLivros = new List <CAMADAS.MODEL.Livros>();

            lstLivros = bllLivro.Select().OrderByDescending(o => o.situacao).ThenBy(e => e.editora.ToLower()).ThenByDescending(t => t.titulo).ToList();

            string       pasta   = Funcoes.deretorioPasta();
            string       arquivo = pasta + @"\RelLivros.html";
            string       arqpdf  = pasta + @"\RelLivros.pdf";
            StreamWriter sw      = new StreamWriter(arquivo);

            using (sw) {
                sw.WriteLine("<html>");
                sw.WriteLine("<head>");
                sw.WriteLine("<meta http-equiv = 'Content-Type' " +
                             "content='text/html; charset=utf-8'/>");
                sw.WriteLine("<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'>");

                sw.WriteLine("</head>");
                sw.WriteLine("<body>");
                sw.WriteLine("<h1> Relatório de Livros</h1>");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("</br>");
                sw.WriteLine("<table class='table table-striped'>");
                sw.WriteLine("<thead>");

                sw.WriteLine("<tr align='right'>");
                sw.WriteLine("<th  align='right' width='40px'>");
                sw.WriteLine("ID");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='right' width='250px'>");
                sw.WriteLine("TÍTULO");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='right' width='200px'>");
                sw.WriteLine("EDITORA");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='right' width='250px'>");
                sw.WriteLine("AUTOR");
                sw.WriteLine("</th>");
                sw.WriteLine("<th  align='right' width='150px'>");
                sw.WriteLine("VALOR");
                sw.WriteLine("</th>");
                sw.WriteLine("<th align='right' width='60px'>");
                sw.WriteLine("SITUAÇÃO");
                sw.WriteLine("</th>");
                sw.WriteLine("</tr>");
                sw.WriteLine("</thead>");

                int   cont  = 0;
                float total = 0;
                sw.WriteLine("<tbody>");
                foreach (CAMADAS.MODEL.Livros livro in lstLivros)
                {
                    sw.WriteLine("<tr>");
                    sw.WriteLine("<td  align='right' width='40px'>");
                    sw.WriteLine(livro.id);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='right' width='250px'>");
                    sw.WriteLine(livro.titulo);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='right' width='200px'>");
                    sw.WriteLine(livro.editora);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='right' width='250px'>");
                    sw.WriteLine(livro.autor);
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td  align='right' width='150px'>");
                    sw.WriteLine(string.Format("{0:C2}", livro.valor));
                    sw.WriteLine("</td>");
                    sw.WriteLine("<td align='right' width='60px'>");
                    sw.WriteLine(livro.situacao);
                    sw.WriteLine("</td>");
                    sw.WriteLine("</tr>");
                    total = total + livro.valor;
                    cont++;
                }
                sw.WriteLine("<tbody>");
                sw.WriteLine("</table> ");
                sw.WriteLine("<hr align='left' border:'5px' />");
                sw.WriteLine("<h2>Foram impressos {0} livros", cont);
                sw.WriteLine("<h2>Valor dos livros impresssos: " + string.Format("{0:R$ #,#.00}", total));
                sw.WriteLine("");

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");
            }

            System.Diagnostics.Process.Start(arquivo);

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.CustomWkHtmlArgs = "--dpi 300";
            htmlToPdf.GeneratePdfFromFile(arquivo, null, arqpdf);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// creates a pdf for a given html string
        /// </summary>
        /// <param name="courseName"></param>
        /// <param name="labNumber"></param>
        /// <param name="htmlString"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string CreatePDF(string courseName, string labNumber, string htmlString, string type)
        {
            // get the users home directory
            var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            #region createDirectories
            // Specify the directory you want to manipulate.
            string docPath    = $"{userDirectory}\\Documents";
            string labPath    = $"{docPath}\\Labormanager";
            string coursePath = $"{labPath}\\{courseName}".Replace(" ", "");

            try {
                // Determine whether the directory exists.
                if (!Directory.Exists(docPath))
                {
                    // Try to create the directory.
                    Directory.CreateDirectory(docPath);
                }
            } catch (Exception e) {
                return($"ERROR, {e.Message}");
            }
            try {
                // Determine whether the directory exists.
                if (!Directory.Exists(labPath))
                {
                    // Try to create the directory.
                    Directory.CreateDirectory(labPath);
                }
            } catch (Exception e) {
                return($"ERROR, {e.Message}");
            }

            try {
                // Determine whether the directory exists.
                if (!Directory.Exists(coursePath))
                {
                    // Try to create the directory.
                    Directory.CreateDirectory(coursePath);
                }
            } catch (Exception e) {
                return($"ERROR, {e.Message}");
            }
            #endregion

            // define paths for the files
            var htmlPath = ($"{coursePath}\\{courseName}_Labor_{labNumber}_{type}.html").Replace(" ", "");
            var pdfPath  = ($"{coursePath}\\{courseName}_Labor_{labNumber}_{type}.pdf").Replace(" ", "");

            // create html file from the html string
            CreateFile(htmlPath, htmlString);

            // create pdf from html file
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            try {
                htmlToPdf.GeneratePdfFromFile(htmlPath, null, pdfPath);
            } catch (Exception e) {
                return($"ERROR, {e.Message}");
            }

            // remove html file which was used for pdf creation
            RemoveFile(htmlPath);

            // return the path to the created pdf
            return(pdfPath);
        }