Esempio n. 1
0
        public byte[] FillPdf(PdfViewModel model)
        {
            try
            {
                var pdfReader = new PdfReader(model.Url);
                using (var memStream = new MemoryStream())
                {
                    using (var stamper = new PdfStamper(pdfReader, memStream))
                    {
                        var form = stamper.AcroFields;

                        foreach (var element in model.FieldsData)
                        {
                            if (form.Fields.ContainsKey(element.Key))
                            {
                                form.SetField(element.Key, element.Value);
                            }
                        }
                    }
                    pdfReader.Close();
                    return(memStream.ToArray());
                }
            }
            catch (WebException e)
            {
                return(null);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> Create(string id)
        {
            var         converter = new SynchronizedConverter(new PdfTools());
            PatientUser user;

            if (id == null)
            {
                user = (PatientUser)await _userManager.GetUserAsync(HttpContext.User);
            }
            else
            {
                user = (PatientUser)await _userManager.FindByIdAsync(id);
            }
            var query = from appointment in _context.Appointments.AsEnumerable() where
                        appointment.PatientID == user.Id && (DateTime.Parse(appointment.Date) < DateTime.Now) == true
                        select appointment;
            PdfViewModel records = new PdfViewModel();

            records.PatientName  = user.FirstName + " " + user.LastName;
            records.Appointments = query;
            var documentContent = await _templateService.RenderTemplateAsync("Pdf/Records", records);

            var output = converter.Convert(new HtmlToPdfDocument()
            {
                Objects =
                {
                    new ObjectSettings()
                    {
                        HtmlContent = documentContent
                    }
                }
            });

            return(File(output, "application/pdf"));
        }
        public ActionResult CreatePDF(int?curriculumId)
        {
            if (curriculumId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Curriculum curriculum = db.GetFromDatabase <Curriculum>(curriculumId);
            Student    student    = curriculum.Student;

            if (curriculum == null)
            {
                return(HttpNotFound());
            }

            PdfViewModel pdfViewModel = new PdfViewModel();

            pdfViewModel.StudentId    = student.Id;
            pdfViewModel.StudentNaam  = student.VolledigeNaam;
            pdfViewModel.CurriculumId = curriculum.Id;
            pdfViewModel.NiveauList   = GetNiveaus();
            pdfViewModel.Course       = curriculum.Naam;
            //pdfViewModel.Niveau = student.Curriculum.

            return(View(pdfViewModel));
        }
Esempio n. 4
0
        private string RenderEmailTemplateUsingRazor(string pdfTemplatePath, PdfViewModel model)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(pdfTemplatePath))
                {
                    if (System.IO.File.Exists(pdfTemplatePath))
                    {
                        //return this.RenderViewToString(emailTemplatePath, model);
                        string pdfTemplate = System.IO.File.ReadAllText(pdfTemplatePath);
                        if (!string.IsNullOrWhiteSpace(pdfTemplate))
                        {
                            return(RazorEngine.Razor.Parse(pdfTemplate, model));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.ExceptionLogger.Log(LogLevel.Error, ex);
                throw ex;
            }

            return(string.Empty);
        }
Esempio n. 5
0
        public IActionResult RenderTemplate()
        {
            var model = new PdfViewModel {
                Title = "PDF title", Description = "Description of PDF"
            };

            return(this.View(model));
        }
Esempio n. 6
0
        public async Task <string> RenderTemplateAsString()
        {
            var model = new PdfViewModel {
                Title = "This is the title", Description = "And this is the description"
            };

            return(await this.RenderViewAsStringAsync("RenderTemplate", model));
        }
Esempio n. 7
0
        public ActionResult EditPost(int?id, PdfViewModel model, MenugroupViewModel mgmodel)
        {
            ViewBag.PageEdit       = true;
            ViewBag.Class          = "admin";
            ViewBag.PdfPanelActive = "active";
            HttpPostedFileBase fileImg = Request.Files["fileImg"];
            HttpPostedFileBase filePdf = Request.Files["filePdf"];

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var PdfItem  = db.Pdfs.Find(id);
            var MenuItem = db.Menugroups.Where(mi => mi.PdfId == id);

            if (PdfItem == null)
            {
                return(HttpNotFound());
            }

            if (fileImg != null)
            {
                model.Img = ConvertToBytes(fileImg);
            }
            else
            {
                model.Img = null;
            }

            if (PdfItem.FileName != null)
            {
                var PdfFile     = filePdf;
                var PdfFileItem = Regex.Replace(PdfFile.FileName, " ", "-");
                var fileName    = System.IO.Path.GetFileName(PdfFileItem);
                var path        = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/PdfFiles/"), fileName);
                PdfFile.SaveAs(path);

                model.FileName = PdfFileItem;

                if (TryUpdateModel(PdfItem, "", new string[] { "Title", "Summary", "Created", "Publish", "Author", "Img", "Filename", "NavbarId", "ImageId", "IsExternal", "Exlink" }))
                {
                    ;
                }
            }
            else
            {
                if (TryUpdateModel(PdfItem, "", new string[] { "Title", "Summary", "Created", "Publish", "Author", "Img", "NavbarId", "ImageId", "IsExternal", "Exlink" }))
                {
                    ;
                }
            }

            db.Entry(PdfItem).State = EntityState.Modified;
            int i = db.SaveChanges();

            return(RedirectToAction("Index"));
        }
Esempio n. 8
0
        public PdfPage()
        {
            InitializeComponent();

            var pdf = new Pdf();

            pdfViewModel   = new PdfViewModel(pdf);
            BindingContext = pdfViewModel;
        }
        public async Task <IActionResult> Download(string accountRef)
        {
            var value = RouteData.Values["id"];

            if (value == null)
            {
                return(RedirectToAction("Index", "MyAccounts"));
            }

            Guid.TryParse(value.ToString(), out var id);

            string lowellReference = ApplicationSessionState.GetLowellReferenceFromSurrogate(id);

            if (string.IsNullOrEmpty(lowellReference))
            {
                throw new Exception("No lowell reference found in cache");
            }

            Account account = ApplicationSessionState.GetAccount(lowellReference);

            if (account == null)
            {
                account = await _accountsService.GetAccount(LoggedInUserId, lowellReference);

                ApplicationSessionState.SaveAccount(account, lowellReference);
            }

            List <Transaction> transactions = ApplicationSessionState.GetTransactions(lowellReference);

            if (transactions == null)
            {
                transactions = await _transactionsService.GetTransactions(account.AccountReference);

                ApplicationSessionState.SaveTransactions(transactions, lowellReference);
            }

            transactions.OrderByDescending(x => x.Date).ToList();

            var transactionsVm = _mapper.Map <List <Transaction>, List <TransactionVm> >(transactions);

            var vm = new PdfViewModel()
            {
                AccountBalance   = account.OutstandingBalance,
                AccountName      = account.OriginalCompany,
                AccountReference = account.AccountReference,
                PaymentDetails   = transactionsVm
            };

            var pdf = _pdfGenerator.Generate(vm);

            await _webActivityService.LogStatementDownloaded(account.AccountReference, LoggedInUserId);

            return(File(new MemoryStream(pdf), "application/pdf",
                        $"{account.AccountReference}_{DateTime.UtcNow:ddMMMyyyyHHmmss}.pdf"));
        }
 public Window2()
 {
     InitializeComponent();
     del                  = new DeliveryMen();
     clientvm             = new ClientViewModel();
     this.lol.ItemsSource = clientvm.GetAllDeliveryMen().Select(m => m.ID);
     //  listView.ItemsSource = dal.GetDistributionList(del);
     this.DataContext          = del;
     myvvm                     = new PdfViewModel(this);
     this.buttGrid.DataContext = myvvm;
 }
Esempio n. 11
0
        public void Setup()
        {
            _sut = new PdfService();

            _pdf = new PdfViewModel
            {
                Url        = "https://www.lantmateriet.se/globalassets/fastigheter/andra-agare/blanketter-och-information/blanketter/anmalan_fornyelse_av_inskrivning.pdf",
                FieldsData = new Dictionary <string, string>
                {
                    { "Adress", "storgatan 4" },
                    { "Önskas", "It works" },
                    { "Test", "This won't show" }
                }
            };
        }
Esempio n. 12
0
        public ActionResult CreatePdf(int id, string param)
        {
            PersonInfo pi = db.PersonInfos.Find(id);

            PdfViewModel model = new PdfViewModel()
            {
                PersonInfo      = pi,
                Param           = param,
                Educations      = db.Educations.Where(x => x.PersonInfo.Id == pi.Id).ToList(),
                WorkExperiences = db.WorkExpriences.Where(x => x.PersonInfo.Id == pi.Id).ToList(),
                Skills          = db.Abilities.Where(x => x.PersonInfo.Id == pi.Id && x.Category == "skill").ToList(),
                Languages       = db.Abilities.Where(x => x.PersonInfo.Id == pi.Id && x.Category == "lang").ToList(),
            };

            return(View(model));
        }
Esempio n. 13
0
        public ActionResult Create(IEnumerable <HttpPostedFileBase> file, PdfViewModel PdfViewModel)
        {
            ViewBag.PageEdit       = true;
            ViewBag.Class          = "admin";
            ViewBag.PdfPanelActive = "active";
            ViewBag.Footer         = false;

            var PdfFile     = file.ElementAt(1);
            var PdfFileItem = Regex.Replace(PdfFile.FileName, " ", "-");
            var fileName    = System.IO.Path.GetFileName(PdfFileItem);
            var path        = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/PdfFiles/"), fileName);

            PdfFile.SaveAs(path);

            if (file.ElementAt(0) != null)
            {
                PdfViewModel.Img = ConvertToBytes(file.ElementAt(0));
            }
            else
            {
                PdfViewModel.Img = null;
            }

            var pdf = new Pdf
            {
                Title      = PdfViewModel.Title,
                Summary    = PdfViewModel.Summary,
                Created    = PdfViewModel.Created,
                Publish    = PdfViewModel.Publish,
                Author     = PdfViewModel.Author,
                ImageId    = PdfViewModel.ImageId,
                NavbarId   = PdfViewModel.NavbarId,
                IsExternal = PdfViewModel.IsExternal,
                ExLink     = PdfViewModel.ExLink,
                Img        = PdfViewModel.Img,
                FileName   = PdfFileItem
            };

            db.Pdfs.Add(pdf);
            int i = db.SaveChanges();

            if (i == 1)
            {
                return(RedirectToAction("Index"));
            }
            return(View(PdfViewModel));
        }
Esempio n. 14
0
        public async Task <IActionResult> ExportPDF(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            var deliver = await _context.Delivers.Include(o => o.Order).Include(o => o.Car).Include(o => o.Customer).FirstOrDefaultAsync(o => o.Id == id);

            if (deliver == null)
            {
                return(NotFound());
            }

            string[] stringArray = new string[6] {
                deliver.Id.ToString(), deliver.Order.Customer.Company, deliver.Order.Customer.Adress, deliver.OrderId.ToString(), deliver.Car.RegistrationPlate, deliver.Order.Customer.PhoneNumber
            };
            ViewBag.Content     = stringArray;
            ViewData["content"] = stringArray;

            var mobiSysContext = _context.DeliverDetails.Where(o => o.DeliverId == id).Include(d => d.Deliver).Include(d => d.Product);

            ViewBag.deliver  = deliver.Id;
            ViewBag.Customer = deliver.Order.Customer.Company;
            ViewBag.Adress   = deliver.Order.Customer.Adress;
            ViewBag.order    = deliver.OrderId;
            ViewBag.car      = deliver.Car.RegistrationPlate;
            ViewBag.Phone    = deliver.Order.Customer.PhoneNumber;
            IList <PdfViewModel> pdf = new List <PdfViewModel>();

            foreach (var item in mobiSysContext)
            {
                PdfViewModel temp = new PdfViewModel();
                temp.Adress      = deliver.Order.Customer.Adress;
                temp.Customer    = deliver.Order.Customer.Company;
                temp.DeliverId   = deliver.Id;
                temp.OrderId     = deliver.OrderId;
                temp.Car         = deliver.Car.RegistrationPlate;
                temp.Phone       = deliver.Order.Customer.PhoneNumber;
                temp.ProductName = item.Product.Name;
                temp.Weight      = item.Product.Weight;
                temp.Quantity    = item.Quantity;
                temp.UnitsPerBox = item.Product.UnitsPerBox;
                pdf.Add(temp);
            }
            return(new ViewAsPdf("Pdf", pdf));
        }
 public ActionResult CreatePDF(PdfViewModel pdfViewModel)
 {
     pdfViewModel.NiveauList = GetNiveaus();
     if (ModelState.IsValid)
     {
         //Student student = db.Studenten.Where(o => o.Id == pdfViewModel.StudentId).First();
         Curriculum curriculum = db.Curricula.Where(o => o.Id == pdfViewModel.CurriculumId)
                                 .Include(a => a.Topics.Select(c => c.Topic.Duur))
                                 .Include(a => a.Topics.Select(c => c.Topic.Benodigdheden))
                                 .Include(a => a.Topics.Select(c => c.Topic.Werkvorm))
                                 .Include(a => a.Topics.Select(c => c.Topic.Niveau))
                                 .First();
         Student student = curriculum.Student;
         //Student student = db.Studenten.Include("")
         //Curriculum curriculum = db.Curricula.Include("Student").Include("Topics.Topic").Where(m => m.Id == pdfViewModel.CurriculumId).FirstOrDefault();
         PDF.Create(pdfViewModel, curriculum);
     }
     return(View(pdfViewModel));
 }
        public async Task <IActionResult> Getpdf(int?id)
        {
            string accessToken = await HttpContext.GetTokenAsync("access_token");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            // Reprise du paiement séléctionné par le user
            string content = await client.GetStringAsync(_url + "DetailsPaiementPdf/" + id);

            Payment payment = JsonConvert.DeserializeObject <Payment>(content);

            if (payment == null)
            {
                return(NotFound());
            }

            // Reprise des coordonnées de l'utilisateur pour les rajouter dans le PDF
            string customerContent = await client.GetStringAsync(_configuration["URLApi"] + "api/Customers/");

            Customer customer = JsonConvert.DeserializeObject <Customer>(customerContent);

            PdfViewModel pdfPayment = new PdfViewModel
            {
                Firstname  = customer.Firstname,
                Lastname   = customer.Lastname,
                Address    = customer.Address,
                Zip        = customer.Zip,
                City       = customer.City,
                PaidDate   = payment.PaidDate,
                PriceTotal = payment.PriceTotal,
                Details    = payment.Details
            };

            ViewAsPdf pdf = new ViewAsPdf(pdfPayment)
            {
                PageMargins = { Left = 20, Bottom = 20, Right = 20, Top = 20 },
            };

            return(pdf);
        }
Esempio n. 17
0
        public int UploadImageFileInDataBase(IEnumerable <HttpPostedFileBase> file, PdfViewModel PdfViewModel)
        {
            PdfViewModel.Img = ConvertToBytes(file.ElementAt(0));

            var PdfFile  = file.ElementAt(1);
            var fileName = Path.GetFileName(PdfFile.FileName);
            var path     = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/PdfFiles/"), fileName);

            PdfFile.SaveAs(path);
            var pdf = new Pdf
            {
                Title      = PdfViewModel.Title,
                Summary    = PdfViewModel.Summary,
                Created    = PdfViewModel.Created,
                Publish    = PdfViewModel.Publish,
                Author     = PdfViewModel.Author,
                ImageId    = PdfViewModel.ImageId,
                NavbarId   = PdfViewModel.NavbarId,
                Img        = PdfViewModel.Img,
                FileName   = PdfFile.FileName,
                IsExternal = PdfViewModel.IsExternal,
                ExLink     = PdfViewModel.ExLink
            };

            db.Pdfs.Add(pdf);
            int i = db.SaveChanges();

            if (i == 1)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Esempio n. 18
0
        public PdfPage(PdfViewModel pdfViewModel)
        {
            InitializeComponent();

            BindingContext = this.pdfViewModel = pdfViewModel;
        }
Esempio n. 19
0
        public static void Create(PdfViewModel pdfvm, Curriculum curriculum)
        {
            // CuriculumModel curriculum = db.Curiculums.Include("StudentId").Where(m => m.CuriculumId == pdfvm.curriculumId).FirstOrDefault();
            List <CurriculumTopic> curriculumTopics = curriculum.Topics.ToList();
            Student student = curriculum.Student;


            // TODO: Sort and group topics by first Certification
            SortedDictionary <string, List <Topic> > groupedTopics = new SortedDictionary <string, List <Topic> >();

            foreach (var topic in curriculumTopics)
            {
                string first = String.Empty;
                if (topic.Topic.Certificeringen.Count != 0)
                {
                    first = topic.Topic.Certificeringen.First().Naam;
                }

                if (!groupedTopics.ContainsKey(first))
                {
                    groupedTopics.Add(first, new List <Topic>());
                    groupedTopics[first].Add(topic.Topic);
                }
                else
                {
                    groupedTopics[first].Add(topic.Topic);
                }
            }

            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();
            XGraphics   gfx      = XGraphics.FromPdfPage(page);
            var         tf       = new XTextFormatter(gfx);

            XStringFormat stringFormat = new XStringFormat();

            stringFormat.LineAlignment = XLineAlignment.Near;
            stringFormat.Alignment     = XStringAlignment.Near;

            var basepath = AppDomain.CurrentDomain.BaseDirectory;
            var path     = String.Concat(basepath, "App_Data\\logo_itvitae_learning_liggend.png");

            //var path = Server.MapPath(@"~/App_Data/logo_itvitae_learning_liggend.png");
            XImage logo = XImage.FromFile(path);

            gfx.DrawImage(logo, new XPoint(430, 5));

            //Fonts
            XFont Calibri20Bold       = new XFont("calibri", 20, XFontStyle.Bold);
            XFont Calibri20BoldItalic = new XFont("calibri", 20, XFontStyle.BoldItalic);
            XFont LabelFont           = new XFont("calibri", 11, XFontStyle.Regular);

            //Title Header
            gfx.DrawString("Persoonlijk Curriculum", Calibri20Bold, XBrushes.Black,
                           new XRect(0, 20, page.Width, 0), XStringFormats.Center);
            gfx.DrawString("ITvitae learning", Calibri20BoldItalic, XBrushes.Black,
                           new XRect(0, 41, page.Width, 0), XStringFormats.Center);
            //XImage ITvitaeLogo = XImage.FromFile(string.Empty);
            //gfx.DrawImage(ITvitaeLogo, new XRect(0, 0, 0, 0));

            //30-100-30 -100 -75-100-30 -100 -30
            //0 |30 |130|160|260|335|435|465|565|595
            //Student Info
            int col1x = 30; int col2x = 135; int col3x = 335; int col4x = 435;
            int colwidth = 100; int rowheight = 12;
            int row1 = 60; int row2 = 80; int row3 = 100;

            DrawLabel("Naam:", col1x, row1, colwidth, rowheight, gfx);
            DrawLabel(student.VolledigeNaam, col2x, row1, colwidth, rowheight, gfx);

            DrawLabel("Geboortedatum:", col1x, row2, colwidth, rowheight, gfx);
            DrawLabel(pdfvm.DoB.ToShortDateString(), col2x, row2, colwidth, rowheight, gfx);

            DrawLabel("StartDatum:", col1x, row3, colwidth, rowheight, gfx);
            DrawLabel(pdfvm.StartDate.ToShortDateString(), col2x, row3, colwidth, rowheight, gfx);

            DrawLabel("Einddatum:", col3x, row3, colwidth, rowheight, gfx);
            DrawLabel(pdfvm.EndDate.ToShortDateString(), col4x, row3, colwidth, rowheight, gfx);

            DrawLabel("Niveau:", col3x, row1, colwidth, rowheight, gfx);
            DrawLabel(pdfvm.Niveau, col4x, row1, colwidth, rowheight, gfx);

            DrawLabel("Richting:", col3x, row2, colwidth, rowheight, gfx);
            DrawLabel(pdfvm.Course, col4x, row2, colwidth, rowheight, gfx);

            //Topics
            //595 into 3 columns starting on Y = 150
            int   YPointer = 150;
            int   topicColumnWidth = 159;
            int   topicColumn1 = 30; int topicColumn2 = 30 + topicColumnWidth; int topicColumn3 = 2 * topicColumnWidth + 60;
            XFont certFont = new XFont("calibri", 11, XFontStyle.Regular);
            XPen  pen      = new XPen(XColors.LightGray);

            //Add headers
            DrawLabel("Modules", topicColumn1, YPointer, topicColumnWidth, rowheight, gfx);
            if (pdfvm.Leerdoel)
            {
                DrawLabel("Leerdoelen", topicColumn2, YPointer, topicColumnWidth, rowheight, gfx);
            }
            if (pdfvm.Certificeringen)
            {
                DrawLabel("Certificeringen", topicColumn3, YPointer, topicColumnWidth, rowheight, gfx);
            }
            YPointer += rowheight;

            //List<Topic> topics = curriculum.Topics.ToList();
            List <CurriculumTopic> topics = curriculum.Topics.ToList();

            for (int i = 0; i < curriculum.Topics.Count; i++)
            {
                List <DrawStringListItem> drawList = new List <DrawStringListItem>();

                //Update YPointer;
                YPointer += 4;
                CurriculumTopic topic = topics[i];

                //measure topic
                XSize topicSize = gfx.MeasureString(topic.Topic.NaamCode, certFont);
                //make rect
                int    rectWidth    = topicColumnWidth;
                double rectRows     = 1;
                int    CertYPointer = 0;
                if (topicSize.Width > topicColumnWidth)
                {
                    rectRows = topicSize.Width / topicColumnWidth;
                    if (rectRows % 1 > 0)
                    {
                        rectRows++;
                    }
                    rectRows = Math.Floor(rectRows);
                }
                //check if new page is needed
                if (YPointer + (rowheight * rectRows) > 780)
                {
                    gfx = NewPage(document, out page, gfx, out tf, out YPointer, logo);
                }
                //Make topicrect
                XRect topicRect = new XRect(topicColumn1, 0, rectWidth, rowheight * rectRows);
                //Add string to drawlist
                drawList.Add(new DrawStringListItem(topic.Topic.NaamCode, certFont, XBrushes.Black, topicRect));

                if (pdfvm.Leerdoel)
                {
                    //measure leerdoel
                    XSize leerdoelSize = gfx.MeasureString(topic.Topic.Leerdoel, certFont);
                    //make rect
                    if (leerdoelSize.Width / topicColumnWidth > rectRows)
                    {
                        rectRows = leerdoelSize.Width / topicColumnWidth;
                        if (rectRows % 1 > 0)
                        {
                            rectRows++;
                        }
                        rectRows = Math.Floor(rectRows);
                    }
                    //check if new page is needed
                    if (YPointer + (rowheight * rectRows) > 780)
                    {
                        gfx = NewPage(document, out page, gfx, out tf, out YPointer, logo);
                    }
                    XRect leerdoelRect = new XRect(topicColumn2, 0, rectWidth, rowheight * rectRows);
                    //update height and y pointer
                    drawList.Add(new DrawStringListItem(topic.Topic.Leerdoel, certFont, XBrushes.Black, leerdoelRect));
                }

                if (pdfvm.Certificeringen)
                {
                    List <Certificering> certs = topic.Topic.Certificeringen.ToList();
                    for (int j = 0; j < certs.Count; j++)
                    {
                        //measure each cert
                        XSize certSize = gfx.MeasureString(certs[j].Naam, certFont);
                        //make rect for each cert
                        double certRows = 1;
                        if (certSize.Width / topicColumnWidth > certRows)
                        {
                            certRows = certSize.Width / topicColumnWidth;
                            if (certRows % 1 > 0)
                            {
                                certRows++;
                            }
                            certRows = Math.Floor(certRows);
                        }
                        XRect certRect = new XRect(topicColumn3, CertYPointer, rectWidth, rowheight * certRows);
                        //Add each cert to drawlist
                        drawList.Add(new DrawStringListItem(certs[j].Naam, certFont, XBrushes.Black, certRect));
                        //update CertYPointer for the next cert
                        CertYPointer += rowheight * (int)certRows;
                    }
                    //Check if certs go over the footer
                    if (YPointer + CertYPointer > 780)
                    {
                        gfx = NewPage(document, out page, gfx, out tf, out YPointer, logo);
                    }
                }

                //Draw all the things relative to YPointer
                gfx.DrawLine(pen, topicColumn1, YPointer - 2, topicColumn3 + topicColumnWidth, YPointer - 2);
                foreach (var item in drawList)
                {
                    XRect r = new XRect(item.Rect.X, item.Rect.Y + YPointer, item.Rect.Width, item.Rect.Height);
                    tf.DrawString(item.Text, item.Font, item.Brush, r);
                }
                YPointer += (rowheight * (int)rectRows) > CertYPointer ? (rowheight * (int)rectRows) : CertYPointer;
            }

            //add footers
            gfx.Dispose();
            int pageNumber = 1; int outOf = document.Pages.Count;

            foreach (PdfPage pdfPage in document.Pages)
            {
                gfx = XGraphics.FromPdfPage(pdfPage);
                int   footerY    = 802;
                XFont footerFont = new XFont("verdana", 10, XFontStyle.Italic);
                gfx.DrawLine(pen, 0, footerY, page.Width, footerY);
                gfx.DrawString($"Pagina {pageNumber}/{outOf}", footerFont, XBrushes.SlateGray, new XPoint(455, footerY + 20));
                gfx.DrawString("Versie 1.0", footerFont, XBrushes.SlateGray, new XPoint(65, footerY + 20));
                pageNumber++;
            }



            string filename = student + $"{ DateTime.Now.Millisecond.ToString()}.pdf";

            // $"Hello_{DateTime.Now.Millisecond.ToString()}.pdf";
            document.Save(filename);
            Process.Start(filename);
        }
Esempio n. 20
0
        public ActionResult GenerateIncoicePdf(int ClaimId, int InvoiceId, int TimelogId)
        {
            try
            {
                StringBuilder html = new StringBuilder();

                List <InvoiceViewModel>        invoices = this.InvoiceBusinessLayer.GetAllInvoicesforPdf(User.Identity.GetUserId(), ClaimId, InvoiceId).ToList();
                IEnumerable <TimeLogViewModel> timeLogs = this.TimeLogBusinessLayer.GetAllTimeLogsforPdf(User.Identity.GetUserId(), ClaimId, TimelogId).Where(x => x.IsBilled == false);
                var          SeriveBillingItems         = new List <PdfBillingItems>();
                decimal      sTotal        = 0;
                decimal      tax           = 0;
                decimal      fTotal        = 0;
                string       claimNumber   = string.Empty;
                string       invoiceNumber = string.Empty;
                PdfViewModel pdfViewModel  = null;
                if (invoices != null && timeLogs != null)
                {
                    foreach (var invoice in invoices)
                    {
                        foreach (var timeLog in invoice.TimeLogs)
                        {
                            var serviceItem = new PdfBillingItems();
                            serviceItem.Item        = timeLog.ServiceItemName;
                            serviceItem.Description = timeLog.Comment;
                            serviceItem.Quantity    = timeLog.Quantity;
                            //serviceItem.Rate = timeLog.ServiceRate;
                            serviceItem.Price = timeLog.TotalAmount;
                            serviceItem.Rate  = decimal.Round(timeLog.ServiceRate, 2, MidpointRounding.AwayFromZero);
                            sTotal           += timeLog.TotalAmount;
                            SeriveBillingItems.Add(serviceItem);
                        }
                        claimNumber   = invoice.ClaimNumber;
                        invoiceNumber = invoice.InvoiceNumber;
                    }
                    foreach (var timeLog in timeLogs)
                    {
                        var serviceItem = new PdfBillingItems();
                        serviceItem.Item        = timeLog.ServiceItemName;
                        serviceItem.Description = timeLog.Comment;
                        serviceItem.Quantity    = timeLog.Quantity;
                        serviceItem.Rate        = decimal.Round(0, 2, MidpointRounding.AwayFromZero);
                        serviceItem.Price       = decimal.Round(0, 2, MidpointRounding.AwayFromZero);
                        SeriveBillingItems.Add(serviceItem);
                    }
                    fTotal       = tax + sTotal;
                    pdfViewModel = new PdfViewModel
                    {
                        ImagePath      = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath + ConfigurationManager.AppSettings.Get("InvoiceImageLocation") + "InvoiceImage.png",
                        BgImagePath    = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath + ConfigurationManager.AppSettings.Get("InvoiceImageLocation") + "InvoiceBackground.png",
                        InvoiceNumber  = invoices[0].InvoiceNumber,
                        InvoiceDate    = invoices[0].InvoiceDate,
                        InvoiceDueDate = invoices[0].DueDate,
                        Insured        = invoices[0].ClaimantName,
                        InsuredPolicy  = invoices[0].PolicyNumber,
                        FileNumber     = invoices[0].FileNumber,
                        Adjuster       = invoices[0].AdjusterName,
                        LostUnit       = invoices[0].LossType,
                        LostDate       = invoices[0].LostDate,
                        CompanyName    = invoices[0].CompanyName,
                        Street         = invoices[0].Street,
                        City           = invoices[0].City,
                        ProvinceName   = invoices[0].ProvinceName,
                        CountryName    = invoices[0].CountryName,
                        PostalCode     = invoices[0].PostalCode,
                        ContactName    = invoices[0].ContactName,
                        BillingItems   = SeriveBillingItems,
                        SubTotal       = sTotal,
                        Tax            = tax,
                        Total          = fTotal
                    };
                }
                string invoiceTemlatePath = Server.MapPath("~/Templates/Invoice/InvoicePdf.cshtml");
                //var emailDataModel = new EmailViewModel
                //{
                //    UserName ="******",
                //    CallbackUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath + ConfigurationManager.AppSettings.Get("InvoiceImageLocation")
                //};
                html.Append(RenderEmailTemplateUsingRazor(invoiceTemlatePath, pdfViewModel).ToString());

                string       dirPath    = GetDataDir_Data(User.Identity.GetUserId(), claimNumber, invoiceNumber) + ".pdf";
                FileStream   fs         = new FileStream(dirPath, FileMode.Create, FileAccess.Write, FileShare.None);
                StreamReader sr         = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(html.ToString())));
                Document     doc        = new Document(PageSize.A4, 50f, 50f, 10f, 0f);
                HTMLWorker   htmlParser = new HTMLWorker(doc);
                PdfWriter    writer     = PdfWriter.GetInstance(doc, fs);
                doc.Open();
                htmlParser.Parse(sr);
                //var htmlContext = new HtmlPipelineContext(null);
                //htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                //ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                //cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/Site/StyleSheets/Bootstrap/bootstrap.css"), true);
                //cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/Site/StyleSheets/Site.css"), true);
                //cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);
                //IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));

                //var worker = new XMLWorker(pipeline, true);
                //var xmlParse = new XMLParser(true, worker);

                //xmlParse.Parse(sr);
                //xmlParse.Flush();
                doc.Close();
                //Response.ContentType = "application/pdf";
                //Response.AddHeader("content-disposition", "attachment;filename="+dirPath);
                //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //Response.Write(doc);
                //Response.End();

                InvoiceDocumentViewModel documentViewModel = new InvoiceDocumentViewModel
                {
                    UserId         = User.Identity.GetUserId(),
                    FileType       = "Pdf",
                    FileName       = dirPath,
                    FileLocation   = fileLocation,
                    CreatedBy      = User.Identity.GetUserId(),
                    CreatedOn      = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"),
                    LastModifiedBy = User.Identity.GetUserId(),
                    LastModifiedOn = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"),
                    IsActive       = true,
                    ClaimId        = ClaimId
                };
                documentViewModel = InvoiceDocumnetMappingBusinessLayer.Create(documentViewModel);

                if (documentViewModel.DocumentId > 0)
                {
                    return(Content("True"));
                }
            }
            catch (Exception ex)
            {
                this.ExceptionLogger.Log(LogLevel.Error, ex);
                throw ex;
            }
            return(Content("False"));
        }