Example #1
0
        private void CreateFileRequest()
        {
            PdfDocument document = new PdfDocument();

            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            PdfPage     page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;
            //text
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

            graphics.DrawString(AppSettings.TeamName, font, PdfBrushes.Black, point: new Syncfusion.Drawing.PointF(30, 0));
            //Image Maybe Try would work better
            //Stream streamImage = File.OpenRead(AppSettings.TeamLogo);
            //if (streamImage != null)
            //{
            //    PdfBitmap image = new PdfBitmap(streamImage);
            //    graphics.DrawImage(image, point: new Syncfusion.Drawing.PointF(20, 20), size: new Syncfusion.Drawing.SizeF(35, 35));
            //}
            //Event Name, location and date
            PdfFont         standardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 15);
            PdfTextElement  textElement  = new PdfTextElement(CurrentEvent.EventName, standardFont);
            PdfLayoutResult layoutResult = textElement.Draw(page, new Syncfusion.Drawing.RectangleF(0, 60, page.GetClientSize().Width, page.GetClientSize().Height));

            if (CurrentEvent.Location != null)
            {
                textElement.Text = CurrentEvent.Location;
                layoutResult     = textElement.Draw(page, new Syncfusion.Drawing.PointF(0, layoutResult.Bounds.Bottom + 5));
            }
            textElement.Text = CurrentEvent.RaceDate.ToString("d MMM yyyy");
            layoutResult     = textElement.Draw(page, new Syncfusion.Drawing.PointF(0, layoutResult.Bounds.Bottom + 5));
            //add a line
            PdfLine line = new PdfLine(new Syncfusion.Drawing.PointF(0, 0), new Syncfusion.Drawing.PointF(page.GetClientSize().Width, 0))
            {
                Pen = PdfPens.DarkGray
            };

            layoutResult = line.Draw(page, new Syncfusion.Drawing.PointF(0, layoutResult.Bounds.Bottom + 5));
            //Add Data

            DataSource dataSource = new DataSource
            {
                Source = EventWithRunners
            };

            dataSource.GroupDescriptors.Add(new GroupDescriptor("Category")
            {
                PropertyName = "Category",
                KeySelector  = (object obj1) =>
                {
                    var item = (obj1 as EventWithRunners);
                    return(item.Category.ToString());
                }
            });

            var items = dataSource.Items;

            {
                foreach (var item in dataSource.Groups)
                {
                    PdfGrid   pdfGrid   = new PdfGrid();
                    DataTable dataTable = new DataTable();
                    dataTable.TableName = item.Key.ToString();
                    textElement.Text    = dataTable.TableName;
                    textElement.Font    = new PdfStandardFont(PdfFontFamily.Helvetica, 15);
                    layoutResult        = textElement.Draw(page, new Syncfusion.Drawing.PointF(0, layoutResult.Bounds.Bottom + 20));

                    dataTable.Columns.Add("Name");
                    dataTable.Columns.Add("Distance");
                    dataTable.Columns.Add("Time");
                    var laps = item.Items as IEnumerable <EventWithRunners>;
                    foreach (var lap in laps.OrderBy(t => t.RanTime.Times))    //May consider order by time
                    {
                        dataTable.Rows.Add(new Object[] { lap.Runner.Name, lap.RanTime.Distance, lap.RanTime.Times.ToString(@"mm\:ss\.ff") });
                    }

                    pdfGrid.DataSource = dataTable;
                    pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent6);
                    layoutResult = pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, layoutResult.Bounds.Bottom));
                }
            }

            //Save Stream
            MemoryStream stream = new MemoryStream();

            document.Save(stream);
            document.Close(true);
            WriteToDevice(stream);
        }
Example #2
0
        private async void listpreview_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var Orderproduct = listpreview.SelectedItem as OrderItem;

            //  await Navigation.PushAsync(new NavigationPage(new RecieptPage(products,saleproducts,  paymentname)) );
            #region Fields
            //Create border color
            PdfColor borderColor     = new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 51, 181, 75));
            PdfBrush lightGreenBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 218, 218, 221)));

            PdfBrush darkGreenBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 51, 181, 75)));

            PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255)));
            PdfPen   borderPen  = new PdfPen(borderColor, 1f);
            Stream   fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf");
            //Create TrueType font
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 11, PdfFontStyle.Bold);


            const float margin       = 30;
            const float lineSpace    = 7;
            const float headerHeight = 90;
            #endregion

            #region header and buyer infomation
            //Create PDF with PDF/A-3b conformance
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
            //Set ZUGFeRD profile
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;

            //Add page to the PDF
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Get the page width and height
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;
            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Fill the header with light Brush
            graphics.DrawRectangle(lightGreenBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString("INVOICE", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3));
            Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.ic_launcher.png");

            //Create a new PdfBitmap instance
            PdfBitmap image = new PdfBitmap(imageStream);

            //Draw the image
            graphics.DrawImage(image, new PointF(margin + 90, headerAmountBounds.Height / 2));
            graphics.DrawRectangle(darkGreenBrush, headerAmountBounds);

            graphics.DrawString("Amount", arialRegularFont, whiteBrush, headerAmountBounds,
                                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            graphics.DrawString("$" + Orderproduct.amount_paid.ToString(), arialBoldFont, whiteBrush,
                                new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
                                PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));



            PdfTextElement textElement = new PdfTextElement("Invoice Number: " + Orderproduct.id.ToString(), arialRegularFont);

            PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120));

            textElement.Text = "Date : " + DateTime.Now.ToString("dddd dd, MMMM yyyy");
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace));
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db");
            var db     = new SQLiteConnection(dbpath);
            if (Orderproduct.client_id != null)
            {
                var client = (db.Table <Client>().ToList().Where(clien => clien.id == int.Parse(Orderproduct.client_id)).FirstOrDefault());
                textElement.Text = "Bill To:";
                layoutResult     = textElement.Draw(page, new PointF(margin, 120));

                textElement.Text = client.enname;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.address;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.email;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.phone;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            }

            #endregion

            #region Invoice data
            PdfGrid        grid            = new PdfGrid();
            DataTable      dataTable       = new DataTable("EmpDetails");
            List <Product> customerDetails = new List <Product>();
            //Add columns to the DataTable
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Price");
            dataTable.Columns.Add("Qty");
            dataTable.Columns.Add("Disc");
            dataTable.Columns.Add("Total");

            //Add rows to the DataTable.
            foreach (var item in Orderproduct.products)
            {
                Product customer = new Product();
                customer.id          = Orderproduct.products.IndexOf(item) + 1;
                customer.Enname      = item.Enname;
                customer.sale_price  = item.sale_price;
                customer.quantity    = item.quantity;
                customer.discount    = item.discount;
                customer.total_price = item.total_price;
                customerDetails.Add(customer);
                dataTable.Rows.Add(new string[] { customer.id.ToString(), customer.Enname, customer.sale_price.ToString(),
                                                  customer.quantity.ToString(), customer.discount.ToString(), customer.total_price.ToString() });
            }

            //Assign data source.
            grid.DataSource = dataTable;


            grid.Columns[1].Width      = 150;
            grid.Style.Font            = arialRegularFont;
            grid.Style.CellPadding.All = 5;

            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable1Light);

            layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40));

            textElement.Text = "Grand Total: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom +
                                                                 lineSpace));

            float totalAmount = float.Parse(Orderproduct.total_price);
            textElement.Text = "$" + totalAmount.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            //graphics.DrawString("$" + totalAmount.ToString(), arialBoldFont, whiteBrush,
            //    new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
            //    PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            textElement.Text = "Total Discount: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom +
                                                                 lineSpace));

            float totalDisc = float.Parse(Orderproduct.discount);
            textElement.Text = "$" + totalDisc.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            //graphics.DrawString("$" + totalDisc.ToString(), arialBoldFont, whiteBrush,
            //    new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
            //    PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));


            #endregion

            #region Seller information
            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0));
            layoutResult = line.Draw(page, new PointF(0, pageHeight - 100));

            textElement.Text = "IttezanPos";
            textElement.Font = arialRegularFont;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3)));
            textElement.Text = "Buradah,  AlQassim, Saudi Arabia";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Any Questions? ittezan.com";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            #endregion

            //#region Create ZUGFeRD XML

            ////Create //ZUGFeRD Invoice
            //ZugferdInvoice invoice = new ZugferdInvoice("2058557939", DateTime.Now, CurrencyCodes.USD);

            ////Set ZUGFeRD profile to basic
            //invoice.Profile = ZugferdProfile.Basic;

            ////Add buyer details
            //invoice.Buyer = new UserDetails
            //{
            //    ID = "Abraham_12",
            //    Name = "Abraham Swearegin",
            //    ContactName = "Swearegin",
            //    City = "United States, California",
            //    Postcode = "9920",
            //    Country = CountryCodes.US,
            //    Street = "9920 BridgePointe Parkway"
            //};

            ////Add seller details
            //invoice.Seller = new UserDetails
            //{
            //    ID = "Adventure_123",
            //    Name = "AdventureWorks",
            //    ContactName = "Adventure support",
            //    City = "Austin,TX",
            //    Postcode = "78721",
            //    Country = CountryCodes.US,
            //    Street = "800 Interchange Blvd"
            //};


            //IEnumerable<Product> products = saleproducts;

            //foreach (Product product in products)
            //    invoice.AddProduct(product);


            //invoice.TotalAmount = totalAmount;

            //MemoryStream zugferdXML = new MemoryStream();
            //invoice.Save(zugferdXML);
            //#endregion

            #region Embed ZUGFeRD XML to PDF

            //Attach ZUGFeRD XML to PDF
            //PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXML);
            //attachment.Relationship = PdfAttachmentRelationship.Alternative;
            //attachment.ModificationDate = DateTime.Now;
            //attachment.Description = "ZUGFeRD-invoice";
            //attachment.MimeType = "application/xml";
            //document.Attachments.Add(attachment);
            #endregion
            //Creates an attachment
            MemoryStream stream = new MemoryStream();
            //    Stream invoiceStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.Data.ZUGFeRD-invoice.xml");

            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", stream);

            attachment.Relationship = PdfAttachmentRelationship.Alternative;

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "ZUGFeRD-invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);

            //Save the document into memory stream



            document.Save(stream);

            //Close the document

            document.Close(true);

            await Xamarin.Forms.DependencyService.Get <ISave>().SaveAndView("تقرير العملاء.pdf", "application/pdf", stream);
        }
        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            //Create PDF with PDF/A-3b conformance.
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            //Set ZUGFeRD profile.
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;
            //Create border color.
            PdfColor borderColor    = new PdfColor(Color.FromArgb(255, 142, 170, 219));
            PdfBrush lightBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 91, 126, 215)));

            PdfBrush darkBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 65, 104, 209)));

            PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 255, 255, 255)));
            PdfPen   borderPen  = new PdfPen(borderColor, 1f);

            //Create TrueType font.
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(new Font("Arial", 30, System.Drawing.FontStyle.Regular), true);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(new Font("Arial", 9, System.Drawing.FontStyle.Regular), true);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(new Font("Arial", 11, System.Drawing.FontStyle.Bold), true);


            const float margin       = 30;
            const float lineSpace    = 7;
            const float headerHeight = 90;


            //Add page to the PDF.
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Get the page width and height.
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;

            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Fill the header with light Brush.
            graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString("Faktura VAT Nr." + (Invoices_DataGrid.SelectedCells[0].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text, headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3));

            graphics.DrawRectangle(darkBlueBrush, headerAmountBounds);

            graphics.DrawString("Amount", arialRegularFont, whiteBrush, headerAmountBounds, new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

            PdfTextElement textElement = new PdfTextElement("Numer faktury:" + (Invoices_DataGrid.SelectedCells[0].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text, arialRegularFont);

            PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120));

            textElement.Text = "Data wystawienia : " + (Invoices_DataGrid.SelectedCells[2].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text;
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Data płatności : " + (Invoices_DataGrid.SelectedCells[3].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text;
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace + 20));

            textElement.Text = "Nabywca:";
            layoutResult     = textElement.Draw(page, new PointF(margin, 120));

            textElement.Text = DataBaseCon.ReadData("select name_company from Company where id_company=" + (Invoices_DataGrid.SelectedCells[1].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text + "; ");
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = DataBaseCon.ReadData("select nip from Company where id_company=" + (Invoices_DataGrid.SelectedCells[1].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text + "; ");
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = DataBaseCon.ReadData("select street from Company where id_company=" + (Invoices_DataGrid.SelectedCells[1].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text + "; ") + " " + DataBaseCon.ReadData("select building_nr from Company where id_company=" + (Invoices_DataGrid.SelectedCells[1].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text + "; ");
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = DataBaseCon.ReadData("select city from Company where id_company=" + (Invoices_DataGrid.SelectedCells[1].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text + "; ") + ", " + DataBaseCon.ReadData("select postcode from Company where id_company=" + (Invoices_DataGrid.SelectedCells[1].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text + "; ");
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));


            string           CmdString = "select id_invoicegoods, article, quantity, value_netto, total_netto from invoiceGoods where id_invoice=" + (Invoices_DataGrid.SelectedCells[0].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text;
            OleDbDataAdapter sda       = new OleDbDataAdapter(CmdString, ConfigurationManager.ConnectionStrings["Connection"].ToString());
            DataTable        dt        = new DataTable("invoiceGoods");

            sda.Fill(dt);

            PdfGrid grid = new PdfGrid();

            grid.DataSource = dt.DefaultView;

            grid.Columns[0].Width      = 150;
            grid.Style.Font            = arialRegularFont;
            grid.Style.CellPadding.All = 5;

            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);

            layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40));

            textElement.Text = "Razem: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom + lineSpace));
            decimal sum = 0;

            foreach (DataRow row in dt.Rows)
            {
                sum += Convert.ToDecimal(row["total_netto"]);
            }

            decimal totalAmount = sum;

            /*DataBaseCon.GridCalc("select total_netto from invoiceGoods where id_invoice = " + (Invoices_DataGrid.SelectedCells[0].Column.GetCellContent(Invoices_DataGrid.SelectedItem) as TextBlock).Text, "invoiceGoods", grid, 0);*/
            textElement.Text = totalAmount.ToString() + " zł";
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            graphics.DrawString(" zł" + totalAmount.ToString(), arialBoldFont, whiteBrush, new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));


            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0));

            layoutResult = line.Draw(page, new PointF(0, pageHeight - 100));

            textElement.Text = "Sprzedawca: ";
            textElement.Font = arialRegularFont;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Filip Filip";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "NIP: 7862019988";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "ul. Bławatkowa 85";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Środa Wielkopolska, 63-000";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));



            //PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXML);
            //attachment.Relationship = PdfAttachmentRelationship.Alternative;
            //attachment.ModificationDate = DateTime.Now;
            //attachment.Description = "ZUGFeRD-invoice";
            //attachment.MimeType = "application/xml";
            //document.Attachments.Add(attachment);
            document.Save("ZUGFeRDInvoice.pdf");
            document.Close(true);
        }
Example #4
0
        public ActionResult Index(List <ShoppingCart> cart)
        {
            ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext()
                                   .GetUserManager <ApplicationUserManager>()
                                   .FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

            Invoice invoice = new Invoice(DateTime.Today, false, false, DateTime.Now.ToString(), user.Email, user.Surname, user.Firstname);

            APIConsumer <Models.Webshop.Invoice> .AddObject("invoice", invoice);

            Webshop.BL.EmailService service = new Webshop.BL.EmailService();
            PdfDocument             doc     = new PdfDocument();
            //Add a page
            PdfPage page = doc.Pages.Add();

            //Create border color.
            PdfColor borderColor    = new PdfColor(Color.FromArgb(255, 142, 170, 219));
            PdfBrush lightBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 91, 126, 215)));

            PdfBrush darkBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 65, 104, 209)));

            PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 255, 255, 255)));
            PdfPen   borderPen  = new PdfPen(borderColor, 1f);

            //Create TrueType font.
            PdfTrueTypeFont headerFont =
                new PdfTrueTypeFont(new Font("Arial", 30, System.Drawing.FontStyle.Regular), true);
            PdfTrueTypeFont arialRegularFont =
                new PdfTrueTypeFont(new Font("Arial", 9, System.Drawing.FontStyle.Regular), true);
            PdfTrueTypeFont arialBoldFont =
                new PdfTrueTypeFont(new Font("Arial", 11, System.Drawing.FontStyle.Bold), true);

            const float margin       = 30;
            const float lineSpace    = 7;
            const float headerHeight = 90;

            //Add Ghrapics
            PdfGraphics graphics = page.Graphics;

            //Get the page width and height.
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;

            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Fill the header with light Brush.
            graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString("Bestelbon", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3));

            graphics.DrawRectangle(darkBlueBrush, headerAmountBounds);

            graphics.DrawString("Totaal te betalen", arialRegularFont, whiteBrush, headerAmountBounds,
                                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

            List <Invoice> invoices = APIConsumer <Invoice> .GetAPI("invoice").ToList();

            PdfTextElement textElement = new PdfTextElement("Factuurnr.: " + invoices.Count, arialRegularFont);

            PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120));

            textElement.Text = "Datum : " + DateTime.Now.ToString("dd MMMM yyyy");
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace));

            textElement.Text = "Aan:";
            layoutResult     = textElement.Draw(page, new PointF(margin, 120));

            textElement.Text = user.Firstname + " " + user.Surname;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = user.Address + " , Postcode: " + user.ZIPCode;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = user.PhoneNumber;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = user.Email;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            PdfGrid grid = new PdfGrid();

            DataTable dataTable = new DataTable();

            ////Add columns to the DataTable
            dataTable.Columns.Add("Product");
            dataTable.Columns.Add("Aantal");
            dataTable.Columns.Add("Prijs");

            ////Add rows to the DataTable
            cart = (List <ShoppingCart>)Session["cart"];
            foreach (ShoppingCart item in (List <ShoppingCart>)Session["cart"])
            {
                if (item.Course == null)
                {
                    dataTable.Rows.Add(new object[]
                                       { item.Product.Name, item.Quantity, (item.Product.Price * item.Quantity) });
                }
                else
                {
                    dataTable.Rows.Add(new object[]
                                       { item.Course.Name, item.Quantity, (item.Course.Price * item.Quantity) });
                }
            }

            grid.DataSource = dataTable;

            grid.Columns[1].Width      = 150;
            grid.Style.Font            = arialRegularFont;
            grid.Style.CellPadding.All = 5;

            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);

            layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40));

            textElement.Text = "Totaal: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page,
                                                new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom + lineSpace));

            float totalAmountCourses  = (float)cart.Where(item => item.Course != null).Sum(item => item.Course.Price * item.Quantity);
            float totalAmountProducts = (float)cart.Where(item => item.Product != null).Sum(item => item.Product.Price * item.Quantity);
            float totalAmount         = totalAmountProducts + totalAmountCourses;

            textElement.Text = "€" + totalAmount.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            graphics.DrawString("€" + totalAmount.ToString(), arialBoldFont, whiteBrush,
                                new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15),
                                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0));

            layoutResult = line.Draw(page, new PointF(0, pageHeight - 100));

            textElement.Text = "dotNET academy Antwerpen";
            textElement.Font = arialRegularFont;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3)));
            textElement.Text = "Komiteitstraat 46-52 (de Koekenfabriek), 2170 Antwerpen";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Vragen? \n tel: +32 16 35 93 78 \n email: [email protected]";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            //Save the document
            doc.Save(@"\Invoices\Bestelling.pdf");
            //Close the document
            doc.Close(true);


            foreach (ShoppingCart item in cart)
            {
                if (item.Course == null)
                {
                    InvoiceDetail detail = new InvoiceDetail(item.Quantity, 0, item.Product.Id);
                    APIConsumer <Models.Webshop.InvoiceDetail> .AddObject("InvoiceDetail", detail);
                }
                else
                {
                    InvoiceDetail detail = new InvoiceDetail(item.Quantity, item.Course.Id);
                    APIConsumer <Models.Webshop.InvoiceDetail> .AddObject("InvoiceDetail", detail);
                }
            }

            string mail = user.Email;

            service.SendInvoice(mail, "Factuur", "Als bijlage uw bestelbon.");

            return(RedirectToAction("Success", "Purchase"));
        }
        public async Task <IActionResult> CreateInvoice(int repairId, CancellationToken cancellationToken)
        {
            //Create PDF with PDF/A-3b conformance.
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            //Set ZUGFeRD profile.
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;

            //Create border color.
            PdfColor borderColor    = new PdfColor(Color.FromArgb(255, 142, 170, 219));
            PdfBrush lightBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 91, 126, 215)));

            PdfBrush darkBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 65, 104, 209)));

            PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 255, 255, 255)));
            PdfPen   borderPen  = new PdfPen(borderColor, 1f);

            string path       = _webHostEnvironment.ContentRootPath + "/arial.ttf";
            Stream fontStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

            //Create TrueType font.
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 11, PdfFontStyle.Regular);

            const float margin       = 30;
            const float lineSpace    = 7;
            const float headerHeight = 90;

            //Add page to the PDF.
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Get the page width and height.
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;

            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Fill the header with light Brush.
            graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString("INVOICE", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3));

            graphics.DrawRectangle(darkBlueBrush, headerAmountBounds);

            graphics.DrawString("Amount", arialRegularFont, whiteBrush, headerAmountBounds, new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

            var repair = await _repairService.GetRepairAsync(repairId, cancellationToken);

            PdfTextElement textElement = new PdfTextElement("Invoice Number: " + repair.Id, arialRegularFont);

            PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - (margin + 10), 120));

            textElement.Text = "Date : " + DateTime.Now.ToString("dddd dd, MMMM yyyy");
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace));

            textElement.Text = "Bill To:";
            layoutResult     = textElement.Draw(page, new PointF(margin, 120));

            textElement.Text = repair.CustomerFirstName + " " + repair.CustomerLastName;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = repair.CustomerEmail;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = repair.CustomerPhoneNumber;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            PdfGrid grid = new PdfGrid();

            List <CreateInvoicePDFModel> model = new List <CreateInvoicePDFModel>();
            int           i = 1;
            const decimal TaxNetValueValue  = 0.77M;
            const decimal VATValue          = 0.23M;
            decimal       summaryPartsPrice = 0;

            foreach (var u in repair.UsedParts)
            {
                decimal TaxValueForList1 = u.PartBoughtPrice * u.Quantity * VATValue;
                decimal NetPriceForList1 = u.PartBoughtPrice * TaxNetValueValue;
                decimal NetValueForList1 = u.PartBoughtPrice * u.Quantity * TaxNetValueValue;
                TaxValueForList1 = Math.Round(TaxValueForList1, 2);
                NetPriceForList1 = Math.Round(NetPriceForList1, 2);
                NetValueForList1 = Math.Round(NetValueForList1, 2);
                model.Add(new CreateInvoicePDFModel
                {
                    Id           = i,
                    Name         = u.Name,
                    Quantity     = (int)u.Quantity,
                    NetPrice     = NetPriceForList1,
                    NetValue     = NetValueForList1,
                    Tax          = (VATValue * 100).ToString() + "%",
                    TaxValue     = TaxValueForList1,
                    SummaryPrice = u.PartBoughtPrice * u.Quantity
                });

                summaryPartsPrice += u.PartBoughtPrice * u.Quantity;
                i++;
            }
            string allRepairNames = "";

            foreach (var repairType in repair.RepairTypes)
            {
                allRepairNames += repairType.Name + "\n";
            }

            decimal TaxValueForList2 = repair.RepairCost * VATValue;
            decimal NetPriceForList2 = repair.RepairCost * TaxNetValueValue;
            decimal NetValueForList2 = repair.RepairCost * TaxNetValueValue;

            TaxValueForList2 = Math.Round(TaxValueForList2, 2);
            NetPriceForList2 = Math.Round(NetPriceForList2, 2);
            NetValueForList2 = Math.Round(NetValueForList2, 2);
            model.Add(new CreateInvoicePDFModel
            {
                Id           = i,
                Name         = allRepairNames,
                Quantity     = 1,
                NetPrice     = NetPriceForList2,
                NetValue     = NetValueForList2,
                Tax          = (VATValue * 100).ToString() + "%",
                TaxValue     = TaxValueForList2,
                SummaryPrice = repair.RepairCost
            });

            grid.DataSource = model;

            grid.Columns[1].Width      = 150;
            grid.Style.Font            = arialRegularFont;
            grid.Style.CellPadding.All = 5;

            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);

            layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40));

            textElement.Text = "Grand Total: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom + lineSpace));

            decimal totalAmount = repair.RepairCost + summaryPartsPrice;

            textElement.Text = totalAmount.ToString() + "PLN";
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            graphics.DrawString(totalAmount.ToString() + "PLN", arialBoldFont, whiteBrush, new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));


            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0));

            layoutResult = line.Draw(page, new PointF(0, pageHeight - 100));

            textElement.Text = "Computer Services Adam Paluch";
            textElement.Font = arialRegularFont;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3)));
            textElement.Text = "ul. Krakowska 19/2\n" +
                               "02-20 Warsaw\n" +
                               "NIP: 8127749027";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Any Questions? [email protected]";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            var        fileName   = "Invoice" + repair.Id + ".pdf";
            FileStream fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite);

            document.Save(fileStream);
            var filePath = fileStream.Name;

            document.Close(true);
            fileStream.Close();

            var invoiceId = await _invoiceService.AddInvoiceAsync(filePath, cancellationToken);

            var repairToUpdate = await _repairRepository.GetByIdAsync(repairId, cancellationToken);

            repairToUpdate.Status         = EnumStatus.Finished;
            repairToUpdate.FinishDateTime = DateTime.Now;
            repairToUpdate.InvoiceId      = invoiceId;
            await _repairRepository.UpdateAsync(cancellationToken, repairToUpdate);

            return(Ok());
        }