示例#1
0
        //Export weather data to PDF document.
        public MemoryStream CreatePdf(WeatherForecast[] forecasts)
        {
            if (forecasts == null)
            {
                throw new ArgumentNullException("Forecast cannot be null");
            }
            //Create a new PDF document
            using (PdfDocument pdfDocument = new PdfDocument())
            {
                int paragraphAfterSpacing = 8;
                int cellMargin            = 8;
                //    pdfDocument.PageSettings.Size = PdfPageSize.A4;
                //Add page to the PDF document
                PdfPage page = pdfDocument.Pages.Add();

                //Create a new font
                PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

                //Create a text element to draw a text in PDF page
                PdfTextElement  title  = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
                PdfLayoutResult result = title.Draw(page, new PointF(0, 0));


                PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement  content     = new PdfTextElement("This component demonstrates fetching data from a service and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
                PdfLayoutFormat format      = new PdfLayoutFormat();
                format.Layout = PdfLayoutType.Paginate;

                //Draw a text to the PDF document
                result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);

                //Create a PdfGrid
                PdfGrid pdfGrid = new PdfGrid();
                pdfGrid.Style.CellPadding.Left  = cellMargin;
                pdfGrid.Style.CellPadding.Right = cellMargin;

                //Applying built-in style to the PDF grid
                pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);

                //Assign data source
                pdfGrid.DataSource = forecasts;

                pdfGrid.Style.Font = contentFont;

                //Draw PDF grid into the PDF page
                pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));

                using (MemoryStream stream = new MemoryStream())
                {
                    //Saving the PDF document into the stream
                    pdfDocument.Save(stream);
                    //Closing the PDF document
                    pdfDocument.Close(true);
                    return(stream);
                }
            }
        }
示例#2
0
        public MemoryStream CreatePdf(WeatherForecast[] weatherForecasts)
        {
            if (weatherForecasts == null)
            {
                throw new ArgumentException("Data cannot be null");
            }
            //Create a new PDF document

            using (PdfDocument pdfDocument = new PdfDocument())
            {
                int paragraphAfterSpacing = 8;
                int cellMargin            = 8;

                //Add page to the pdf Document
                PdfPage page = pdfDocument.Pages.Add();

                //create New Font
                PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

                //Create a text elemet to draw a text in PDf Page
                PdfTextElement  title  = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
                PdfLayoutResult result = title.Draw(page, new PointF(0, 0));


                PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfLayoutFormat format      = new PdfLayoutFormat();
                format.Layout = PdfLayoutType.Paginate;


                //Create PDF
                PdfGrid pdfGrid = new PdfGrid();
                pdfGrid.Style.CellPadding.Left  = cellMargin;
                pdfGrid.Style.CellPadding.Right = cellMargin;

                //Apply built in Styke to the PDF grid
                pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);

                //Assing Data Source
                pdfGrid.DataSource = weatherForecasts.ToList();

                pdfGrid.Style.Font = contentFont;


                //Draw PDf Grid into the pdf Page
                pdfGrid.Draw(page, new PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));

                using (MemoryStream stream = new MemoryStream())
                {
                    pdfDocument.Save(stream);
                    pdfDocument.Close(true);
                    return(stream);
                }
            }
        }
示例#3
0
        public void ExportToPdf(List <T> entities, string reportTitle, ReportRequest reportRequest, List <string> columns)
        {
            int         paragraphAfterSpacing = 8;
            int         cellMargin            = 8;
            PdfDocument pdfDocument           = new PdfDocument();
            //Add Page to the PDF document.
            PdfPage page = pdfDocument.Pages.Add();

            //Create a new font.
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

            //Create a text element to draw a text in PDF page.
            PdfTextElement  title  = new PdfTextElement(reportTitle, font, PdfBrushes.Black);
            PdfLayoutResult result = title.Draw(page, new PointF(0, 0));

            var contentInfo = CreateContentInfo(reportRequest, entities);

            PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
            PdfTextElement  content     = new PdfTextElement(contentInfo, contentFont, PdfBrushes.Black);
            PdfLayoutFormat format      = new PdfLayoutFormat();

            format.Layout = PdfLayoutType.Paginate;

            //Draw a text to the PDF document.
            result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);

            //Create a PdfGrid.
            PdfGrid pdfGrid = new PdfGrid();

            pdfGrid.Style.CellPadding.Left  = cellMargin;
            pdfGrid.Style.CellPadding.Right = cellMargin;

            //Applying built-in style to the PDF grid
            pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);

            //Create data to populate table
            DataTable table = CreateDataSourceTable(entities, columns);

            //Assign data source.
            pdfGrid.DataSource = table;

            pdfGrid.Style.Font = contentFont;

            //Draw PDF grid into the PDF page.
            pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));

            MemoryStream memoryStream = new MemoryStream();

            // Save the PDF document.
            pdfDocument.Save(memoryStream);

            // Download the PDF document
            _jsRuntime.SaveAs(reportTitle + ".pdf", memoryStream.ToArray());
        }
示例#4
0
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            #region Field Definitions
            IEnumerable <Adventure> products = Provider.GetProducts();
            Stream          fontStream       = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Pdf.Assets.verdana.ttf");
            PdfStandardFont font             = new PdfStandardFont(PdfFontFamily.TimesRoman, 8f);
            #endregion

            styleName = this.gridBuiltinstyleComboBox.SelectedItem.ToString();

            PdfDocument document = new PdfDocument();

            PdfPage page = document.Pages.Add();

            #region PdfGrid
            grid            = new PdfGrid();
            grid.DataSource = products;

            PdfGridBuiltinStyle style = ConvertToPdfGridBuiltinStyle(styleName);

            PdfGridBuiltinStyleSettings setting = new PdfGridBuiltinStyleSettings();
            setting.ApplyStyleForHeaderRow  = true;
            setting.ApplyStyleForBandedRows = true;

            grid.Style.CellPadding.All = 2;

            grid.ApplyBuiltinStyle(style, setting);

            PdfGridLayoutFormat gridLayoutFormat = new PdfGridLayoutFormat();
            gridLayoutFormat.Layout = PdfLayoutType.Paginate;
            gridLayoutFormat.Break  = PdfLayoutBreakType.FitElement;

            grid.Draw(page, PointF.Empty, gridLayoutFormat);

            #endregion

            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream);

            document.Close(true);
            SaveFile(stream, "GridBuiltinStyle.pdf");
        }
示例#5
0
        public void ConvertToPdf(string source, string destination)
        {
            try
            {
                var excelEngine = new ExcelEngine();
                var application = excelEngine.Excel;
                var workbook    = application.Workbooks.Open(source);
                var worksheet   = workbook.Worksheets[0];
                var document    = new PdfDocument();
                var page        = document.Pages.Add();
                var pdfGrid     = new PdfGrid();
                pdfGrid.Columns.Add(worksheet.UsedRange.LastColumn);
                pdfGrid.Headers.Add(1);
                var pdfGridHeader = pdfGrid.Headers[0];

                for (var i = 0; i < worksheet.UsedRange.LastColumn; i++)
                {
                    pdfGridHeader.Cells[i].Value = worksheet.UsedRange.Columns[i].DisplayText;
                }

                //Add rows
                for (var row = 2; row <= worksheet.UsedRange.LastRow; row++)
                {
                    var pdfGridRow = pdfGrid.Rows.Add();
                    for (var col = 1; col <= worksheet.UsedRange.LastColumn; col++)
                    {
                        var text = worksheet[row, col].Text;
                        pdfGridRow.Cells[col - 1].Value = text;
                    }
                }

                pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable5DarkAccent6);
                pdfGrid.Draw(page, PointF.Empty);
                document.Save(destination);
                document.Close(true);
            }
            catch (Exception ex)
            {
                FileLogger.SetLog(string.Format(ExceptionConstants.ConvertToPdf, source, ex.Message));
            }
        }
示例#6
0
        public ActionResult AdventureCycle(string styleName, string Header, string Bandedrow, string Bandedcolumn, string Firstcolumn, string Lastcolumn, string Lastrow, string InsideBrowser)
        {
            if (styleName == "" || styleName == null)
            {
                styleName = "GridTable4";
            }
            //Create PDF document
            PdfDocument doc = new PdfDocument();

            //Set font
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);

            //Create Pdf ben for drawing broder
            PdfPen borderPen = new PdfPen(PdfBrushes.DarkBlue);

            borderPen.Width = 0;

            //Create DataTable for source
            PdfPage page = doc.Pages.Add();


            //Use DataTable as source
            PdfGrid grid = new PdfGrid();

            //Create dataset with the "Customers" table from Norwind database
            IEnumerable <Orders> orders = Provider.GetOrdersData(_hostingEnvironment.WebRootPath);

            grid.Style.AllowHorizontalOverflow = true;

            //Set Data source
            grid.DataSource = orders;

            #region PdfGridBuiltinStyleSettings
            PdfGridBuiltinStyleSettings setting = new PdfGridBuiltinStyleSettings();
            setting.ApplyStyleForHeaderRow     = Header != null ? true : false;
            setting.ApplyStyleForBandedRows    = Bandedrow != null ? true : false;
            setting.ApplyStyleForBandedColumns = Bandedcolumn != null ? true : false;
            setting.ApplyStyleForFirstColumn   = Firstcolumn != null ? true : false;
            setting.ApplyStyleForLastColumn    = Lastcolumn != null ? true : false;
            setting.ApplyStyleForLastRow       = Lastrow != null ? true : false;
            #endregion

            //Set layout properties
            PdfLayoutFormat format = new PdfLayoutFormat();
            format.Break  = PdfLayoutBreakType.FitElement;
            format.Layout = PdfLayoutType.Paginate;

            PdfGridBuiltinStyle style = ConvertToPdfGridBuiltStyle(styleName);

            grid.ApplyBuiltinStyle(style, setting);
            grid.Style.Font                    = font;
            grid.Style.CellPadding.All         = 2;
            grid.Style.AllowHorizontalOverflow = false;
            //Draw table
            grid.Draw(page, PointF.Empty, format);

            MemoryStream stream = new MemoryStream();

            //Save the PDF document
            doc.Save(stream);

            //Close the PDF document
            doc.Close(true);

            stream.Position = 0;

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
            fileStreamResult.FileDownloadName = "AdventureCycle.pdf";
            return(fileStreamResult);
        }
示例#7
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);
        }
示例#8
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);
        }
示例#9
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"));
        }
示例#10
0
        public async Task <MemoryStream> CreatePDF(SfGrid <AttendanceReportViewModel> grid, AttReportSet attReportSet, ReportViewModel ReportVM)
        {
            string    json = JsonConvert.SerializeObject(grid.DataSource);
            DataTable dt   = JsonConvert.DeserializeObject <DataTable>(json);

            int i = 0;

            if (!attReportSet.Date)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Day)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }

            if (!attReportSet.Attend1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.EarlyAttend1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Late1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Depart1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.EarlyDepart1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Bonus1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Shift1)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }

            if (!attReportSet.Attend2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.EarlyAttend2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Late2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Depart2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.EarlyDepart2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Bonus2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Shift2)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }

            if (!attReportSet.Early)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Late)
            {
                dt.Columns.RemoveAt(i);
            }
            if (!attReportSet.EarlyDepart)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Bonus)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }

            if (!attReportSet.TotalTime)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.TotalSubtract)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.TotalSupplement)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }

            if (!attReportSet.TotalHours)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Holiday)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Absent)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.AttendDevice)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.DepartDevice)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.Worksys)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.BonusType)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }
            if (!attReportSet.UpdatedActions)
            {
                dt.Columns.RemoveAt(i);
            }
            else
            {
                i++;
            }

            //for (int x = 0; x < dt.Columns.Count; x++)
            //{
            //    dt.Columns[x].ColumnName = grid.Columns[x].HeaderText;
            //}

            if (grid.DataSource == null)
            {
                throw new ArgumentNullException("No data found");
            }

            using (PdfDocument doc = new PdfDocument())
            {
                int             paragraphAfterSpacing = 18;
                int             cellMargin            = 4;
                PdfStandardFont standardFont          = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfStandardFont HeaderFont            = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
                PdfStandardFont contentFont           = new PdfStandardFont(PdfFontFamily.TimesRoman, 8);
                PdfLayoutFormat format = new PdfLayoutFormat();
                format.Layout = PdfLayoutType.Paginate;

                PdfPage page = doc.Pages.Add();

                #region Header
                PdfTextElement title    = new PdfTextElement("Attendance Report", standardFont, PdfBrushes.Black);
                PdfTextElement empName  = new PdfTextElement("Employee Name : " + ReportVM.Employee.Name, HeaderFont, PdfBrushes.Black);
                PdfTextElement attSys   = new PdfTextElement("Attendance System : " + ReportVM.Worksys.Name, HeaderFont, PdfBrushes.Black);
                PdfTextElement depart   = new PdfTextElement("Department : ", HeaderFont, PdfBrushes.Black);
                PdfTextElement sec      = new PdfTextElement("Section : ", HeaderFont, PdfBrushes.Black);
                PdfTextElement fromDate = new PdfTextElement("From : " + ReportVM.FromDate, HeaderFont, PdfBrushes.Black);
                PdfTextElement toDate   = new PdfTextElement("To : " + ReportVM.ToDate, HeaderFont, PdfBrushes.Black);
                #endregion

                PdfLayoutResult result = title.Draw(page, new Syncfusion.Drawing.PointF(170, 0));
                result = empName.Draw(page, new Syncfusion.Drawing.PointF(0, 20));
                result = fromDate.Draw(page, new Syncfusion.Drawing.PointF(0, 40));
                result = toDate.Draw(page, new Syncfusion.Drawing.PointF(0, 60));

                result = attSys.Draw(page, new Syncfusion.Drawing.PointF(300, 20));
                result = depart.Draw(page, new Syncfusion.Drawing.PointF(300, 40));
                result = sec.Draw(page, new Syncfusion.Drawing.PointF(300, 60));



                //Create a PdfGrid
                PdfGrid pdfGrid = new PdfGrid();
                pdfGrid.Style.CellPadding.Left  = cellMargin;
                pdfGrid.Style.CellPadding.Right = cellMargin;

                pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable1Light);

                //Assign data source
                pdfGrid.DataSource = dt;
                pdfGrid.Style.Font = contentFont;

                //Draw grid to the page of PDF document
                pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));

                //Save the document.
                using (MemoryStream stream = new MemoryStream())
                {
                    doc.Save(stream);
                    doc.Close(true);
                    return(stream);
                };
            }
        }
        private float GenerateItemizedBodyWithGrid(GenerateInvoiceContext request, PdfGenerator pdf, float y)
        {
            y = pdf.IncrementY(y, 10, FOOTER_HEIGHT);
            //Create a new PdfGrid.

            PdfGrid pdfGrid = new PdfGrid();

            //Add four columns.

            pdfGrid.Columns.Add(4);
            var columnFormat = new PdfStringFormat
            {
                Alignment     = PdfTextAlignment.Center,
                LineAlignment = PdfVerticalAlignment.Middle
            };

            pdfGrid.Columns[1].Format = columnFormat;
            pdfGrid.Columns[2].Format = columnFormat;
            pdfGrid.Columns[3].Format = columnFormat;

            //Add header.

            pdfGrid.Headers.Add(1);

            PdfGridRow pdfGridHeader = pdfGrid.Headers[0];

            pdfGridHeader.Cells[0].Value = "Item";
            pdfGridHeader.Cells[1].Value = "Cost";
            pdfGridHeader.Cells[2].Value = "Qty";
            pdfGridHeader.Cells[3].Value = "Total";

            //Add rows.
            foreach (var item in request.Invoice.Items)
            {
                PdfGridRow pdfGridRow = pdfGrid.Rows.Add();

                //NOTE: It seems that values MUST be string values

                pdfGridRow.Cells[0].Value = item.Name;
                pdfGridRow.Cells[1].Value = item.ItemAmount.ToString("n2");
                pdfGridRow.Cells[2].Value = item.Quantity.ToString("n0");
                pdfGridRow.Cells[3].Value = item.Amount.ToString("n2");
            }

            var data = request.Invoice.Items.Select(x => x.ItemAmount.ToString("n2"));

            pdfGrid.Columns[1].SizeColumnToContent(data, pdf.PageWidth, pdf.NormalFont);
            data = request.Invoice.Items.Select(x => x.Quantity.ToString("n2"));
            pdfGrid.Columns[2].SizeColumnToContent(data, pdf.PageWidth, pdf.NormalFont);
            data = request.Invoice.Items.Select(x => x.Amount.ToString("n2"));
            pdfGrid.Columns[3].SizeColumnToContent(data, pdf.PageWidth, pdf.NormalFont);

            //Apply built-in table style
            //NOTE: that the accent2 color of #FFED7D31 is used in generating the total rectangle as well
            pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent2);

            //Apply Custom Style
            //pdfGrid.Style = new PdfGridStyle
            //{
            //    //BackgroundBrush = pdf.AccentBrush,
            //    TextBrush = pdf.AccentBrush,
            //    //TextPen = new PdfPen(pdf.AccentBrush)
            //};

            PdfGridLayoutFormat format = new PdfGridLayoutFormat();

            format.Layout         = PdfLayoutType.Paginate;
            format.PaginateBounds = new RectangleF(0, 0, pdf.CurrentPage.Graphics.ClientSize.Width, pdf.CurrentPage.Graphics.ClientSize.Height - FOOTER_HEIGHT);

            //Draw the PdfGrid.
            var result = pdfGrid.Draw(pdf.CurrentPage, new PointF(10, y), format);

            return(result.Bounds.Bottom);
        }
        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());
        }
        public ActionResult DownloadPDF(int orderId)
        {
            var         order         = orderRepository.GetOrderDetailsById(orderId);
            int         ShipingCharge = Convert.ToInt32(configuration["shippingCharge"]);
            PdfDocument document      = new PdfDocument();

            //Adds page settings
            document.PageSettings.Orientation = PdfPageOrientation.Landscape;
            document.PageSettings.Margins.All = 50;
            //Adds a page to the document
            PdfPage     page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;
            //Set the standard font
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 35, PdfFontStyle.Bold);


            //Draw the text
            graphics.DrawString("Prince Fashion!", font, PdfBrushes.Gray, new PointF(120, 5));

            FileStream imageStream = new FileStream("wwwroot/images/logo.png", FileMode.Open, FileAccess.Read);


            RectangleF bounds = new RectangleF(10, 0, 80, 40);
            PdfImage   image  = PdfImage.FromStream(imageStream);

            //Draws the image to the PDF page
            page.Graphics.DrawImage(image, bounds);

            PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(116, 152, 190));

            bounds = new RectangleF(0, bounds.Bottom + 50, graphics.ClientSize.Width, 40);
            //Draws a rectangle to place the heading in that region.
            graphics.DrawRectangle(solidBrush, bounds);
            //Creates a font for adding the heading in the page
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);
            //Creates a text element to add the invoice number

            PdfTextElement element1;

            if (order.OrderType.Equals("DoneOnlinepayment"))
            {
                element1 = new PdfTextElement("Type :: " + order.OrderType, subHeadingFont);
            }
            else
            {
                element1 = new PdfTextElement("Type :: COD ");
            }

            element1.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);

            element1.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            element1.Draw(page, new PointF(graphics.ClientSize.Width - 250, bounds.Top - 40));


            PdfTextElement element = new PdfTextElement("INVOICE " + orderId, subHeadingFont);

            element.Brush = PdfBrushes.White;

            //Draws the heading on the page
            PdfLayoutResult result      = element.Draw(page, new PointF(10, bounds.Top + 8));
            string          currentDate = "DATE " + DateTime.Now.ToString("dd/MM/yyyy");
            //Measures the width of the text to place it in the correct location
            SizeF  textSize     = subHeadingFont.MeasureString(currentDate);
            PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y);


            //Draws the date by using DrawString method
            graphics.DrawString(currentDate, subHeadingFont, element.Brush, textPosition);
            PdfFont timesRoman = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);

            //Creates text elements to add the address and draw it to the page.
            element       = new PdfTextElement("BILL TO ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(126, 155, 203));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));


            element       = new PdfTextElement("Name :: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 5));

            element       = new PdfTextElement(order.FirstName.ToUpper() + " " + order.LastName.ToUpper(), timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(result.Bounds.Left + 40, result.Bounds.Bottom - 10));


            element       = new PdfTextElement("Mob No :: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(result.Bounds.Left + 200, result.Bounds.Bottom - 10));

            element       = new PdfTextElement(order.PhoneNumber, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(result.Bounds.Left + 45, result.Bounds.Bottom - 10));


            element       = new PdfTextElement("Address :: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 5));

            element       = new PdfTextElement(order.AddressLine1 + " , " + order.AddressLine2, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(result.Bounds.Left + 45, result.Bounds.Bottom - 10));


            element       = new PdfTextElement("Email Id:: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(result.Bounds.Left + 195, result.Bounds.Bottom - 10));

            element       = new PdfTextElement(order.Email, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(result.Bounds.Left + 45, result.Bounds.Bottom - 10));


            element       = new PdfTextElement(order.City + " , " + order.State + " -" + order.ZipCode, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(55, result.Bounds.Bottom + 5));


            element       = new PdfTextElement(order.Country, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(55, result.Bounds.Bottom + 5));



            PdfPen linePen    = new PdfPen(new PdfColor(126, 151, 173), 0.70f);
            PointF startPoint = new PointF(0, result.Bounds.Bottom + 3);
            PointF endPoint   = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3);

            //Draws a line at the bottom of the address
            graphics.DrawLine(linePen, startPoint, endPoint);


            DataTable dt = new DataTable();

            dt.Columns.Add("Product Code");
            dt.Columns.Add("Product Disc");
            dt.Columns.Add("Price");
            dt.Columns.Add("Discount");
            dt.Columns.Add("Discount Price");

            foreach (var p in order.OrderLines)
            {
                float discountPrice = (float)Math.Round(p.Product.Price - p.Product.Price * p.Product.Discount / 100, 2);
                dt.Rows.Add(p.Product.ProductName, p.Product.ShortDescription, "Rs. " + p.Product.Price, p.Product.Discount + " %", "Rs. " + discountPrice);
            }
            if (order.OrderType.Equals("codpayment"))
            {
                dt.Rows.Add("Shipping Charge", "", "Rs. " + ShipingCharge, "", "Rs. " + ShipingCharge);
            }

            DataTable invoiceDetails = dt;
            //Creates a PDF grid
            PdfGrid grid = new PdfGrid();

            //Adds the data source
            grid.DataSource = invoiceDetails;
            //Creates the grid cell styles
            PdfGridCellStyle cellStyle = new PdfGridCellStyle();

            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];
            //Creates the header style
            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

            headerStyle.Borders.All     = new PdfPen(new PdfColor(126, 155, 203));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 155, 203));
            headerStyle.TextBrush       = PdfBrushes.White;
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular);

            //Adds cell customizations
            for (int i = 0; i < header.Cells.Count; i++)
            {
                header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            }

            //Applies the header style
            header.ApplyStyle(headerStyle);

            PdfGridStyle gridStyle = new PdfGridStyle();

            gridStyle.CellPadding = new PdfPaddings(2, 2, 2, 2);

            gridStyle.CellSpacing = 1;

            grid.Style = gridStyle;

            PdfStringFormat stringFormat = new PdfStringFormat();

            stringFormat.Alignment     = PdfTextAlignment.Left + 5;
            stringFormat.LineAlignment = PdfVerticalAlignment.Middle;


            //Apply string formatting for whole table
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                grid.Columns[i].Format = stringFormat;
            }


            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
            cellStyle.Font      = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
            cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136));
            //Creates the layout format for grid
            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            // Creates layout format settings to allow the table pagination
            layoutFormat.Layout = PdfLayoutType.Paginate;
            //Draws the grid to the PDF page.
            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 100)), layoutFormat);


            element       = new PdfTextElement("Total Price:: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(graphics.ClientSize.Width - 200, gridResult.Bounds.Bottom + 10));

            element       = new PdfTextElement("Rs. " + order.OrderTotal.ToString("0.00"), timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(graphics.ClientSize.Width - 140, result.Bounds.Bottom - 10));



            element       = new PdfTextElement("Total Product:: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(graphics.ClientSize.Width - 500, gridResult.Bounds.Bottom + 10));

            element       = new PdfTextElement(order.TotalItem.ToString("0"), timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(graphics.ClientSize.Width - 420, result.Bounds.Bottom - 10));


            element       = new PdfTextElement("OrderDate:: ", timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(10, gridResult.Bounds.Bottom + 10));

            element       = new PdfTextElement(order.OrderPlacedDate.ToString("dd/MM/yyyy"), timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new PointF(60, result.Bounds.Bottom - 10));

            element1.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 20, PdfFontStyle.Bold);

            element1       = new PdfTextElement("Thanks,", subHeadingFont);
            element1.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result         = element1.Draw(page, new PointF(graphics.ClientSize.Width - 130, result.Bounds.Bottom + 20));
            element1       = new PdfTextElement("Prince Digital,Surat", subHeadingFont);
            element1.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result         = element1.Draw(page, new PointF(graphics.ClientSize.Width - 130, result.Bounds.Bottom + 1));

            MemoryStream stream = new MemoryStream();

            document.Save(stream);

            //Set the position as '0'.
            stream.Position = 0;

            //Download the PDF document in the browser
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
            string           FileName         = "order_" + order.OrderId + ".pdf";

            fileStreamResult.FileDownloadName = FileName;

            return(fileStreamResult);
        }
示例#14
0
        private void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document.
            PdfDocument document = new PdfDocument();
            //Add a page to the document.
            PdfPage page = document.Pages.Add();
            //Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;

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

            //Set the header height
            float headerHeight = 90;
            //Create brush with light blue color.
            PdfColor lightBlue      = Color.FromArgb(255, 91, 126, 215);
            PdfBrush lightBlueBrush = new PdfSolidBrush(lightBlue);
            //Create brush with dark blue color.
            PdfColor darkBlue      = Color.FromArgb(255, 65, 104, 209);
            PdfBrush darkBlueBrush = new PdfSolidBrush(darkBlue);
            //Create brush with white color.
            PdfBrush whiteBrush = new PdfSolidBrush(Color.FromArgb(255, 255, 255, 255));

            //Get the font file stream from assembly.
            Stream fontStream = typeof(Invoice).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.arial.ttf");

            //Create PdfTrueTypeFont from stream with different size.
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 18, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);

            //Create string format.
            PdfStringFormat format = new PdfStringFormat();

            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            float y = 0;
            float x = 0;

            //Set the margins of address.
            float margin = 30;

            //Set the line space.
            float lineSpace = 10;

            //Create border pen and draw the border to PDF page.
            PdfColor borderColor = Color.FromArgb(255, 142, 170, 219);
            PdfPen   borderPen   = new PdfPen(borderColor, 1f);

            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Create a new PdfGrid
            PdfGrid grid = new PdfGrid();

            //Add five columns to the grid.
            grid.Columns.Add(5);

            //Create the header row of the grid.
            PdfGridRow[] headerRow = grid.Headers.Add(1);

            //Set style to the header row and set value to the header cells.
            headerRow[0].Style.BackgroundBrush           = new PdfSolidBrush(new PdfColor(68, 114, 196));
            headerRow[0].Style.TextBrush                 = PdfBrushes.White;
            headerRow[0].Cells[0].Value                  = "Product ID";
            headerRow[0].Cells[0].StringFormat.Alignment = PdfTextAlignment.Center;
            headerRow[0].Cells[1].Value                  = "Product Name";
            headerRow[0].Cells[2].Value                  = "Price ($)";
            headerRow[0].Cells[3].Value                  = "Quantity";
            headerRow[0].Cells[4].Value                  = "Total ($)";

            //Add products to the grid table.
            AddProducts("CA-1098", "AWC Logo Cap", 8.99, 2, 17.98, grid);
            AddProducts("LJ-0192", "Long-Sleeve Logo Jersey,M", 49.99, 3, 149.97, grid);
            AddProducts("So-B909-M", "Mountain Bike Socks,M", 9.50, 2, 19, grid);
            AddProducts("LJ-0192", "Long-Sleeve Logo Jersey,M", 49.99, 4, 199.96, grid);
            AddProducts("FK-5136", "ML Fork", 175.49, 6, 1052.94, grid);
            AddProducts("HL-U509", "Sports-100 Helmet,Black", 34.99, 1, 34.99, grid);

            #region Header

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

            string title = "INVOICE";

            //Specificy the bounds for total value.
            RectangleF headerTotalBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            //Measure the string size using font.
            SizeF textSize = headerFont.MeasureString(title);
            graphics.DrawString(title, headerFont, whiteBrush, new RectangleF(0, 0, textSize.Width + 50, headerHeight), format);
            //Draw rectangle in PDF page.
            graphics.DrawRectangle(darkBlueBrush, headerTotalBounds);
            //Draw the toal value to PDF page.
            graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight + 10), format);
            //Create font from font stream.
            arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
            //Set bottom line alignment and draw the text to PDF page.
            format.LineAlignment = PdfVerticalAlignment.Bottom;
            graphics.DrawString("Amount", arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight / 2 - arialRegularFont.Height), format);
            #endregion
            //Measure the string size using font.
            SizeF size = arialRegularFont.MeasureString("Invoice Number: 2058557939");
            y = headerHeight + margin;
            x = (pageWidth - margin) - size.Width;
            //Draw text to PDF page with provided font and location.
            graphics.DrawString("Invoice Number: 2058557939", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            //Measure the string size using font.
            size = arialRegularFont.MeasureString("Date :" + DateTime.Now.ToString("dddd dd, MMMM yyyy"));
            x    = (pageWidth - margin) - size.Width;
            y   += arialRegularFont.Height + lineSpace;
            //Draw text to PDF page with provided font and location.
            graphics.DrawString("Date: " + DateTime.Now.ToString("dddd dd, MMMM yyyy"), arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y = headerHeight + margin;
            x = margin;
            //Draw text to PDF page with provided font and location.
            graphics.DrawString("Bill To:", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("Abraham Swearegin,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("United States, California, San Mateo,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9920 BridgePointe Parkway,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9365550136", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            #region Grid
            //Set width to grid columns.
            grid.Columns[0].Width = 110;
            grid.Columns[1].Width = 150;
            grid.Columns[2].Width = 110;
            grid.Columns[3].Width = 70;
            grid.Columns[4].Width = 100;

            for (int i = 0; i < grid.Headers.Count; i++)
            {
                //Set height to the grid header row.
                grid.Headers[i].Height = 20;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    //Create string format for header cell.
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;
                    pdfStringFormat.Alignment     = PdfTextAlignment.Left;

                    //Set cell padding for header cell.
                    if (j == 0 || j == 2)
                    {
                        grid.Headers[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }
                    //Set string format to grid header cell.
                    grid.Headers[i].Cells[j].StringFormat = pdfStringFormat;
                    //Set font to the grid header cell.
                    grid.Headers[i].Cells[j].Style.Font = arialBoldFont;
                }
                //Set value to the grid header cell.
                grid.Headers[0].Cells[0].Value = "Product ID";
            }
            for (int i = 0; i < grid.Rows.Count; i++)
            {
                //Set height to the grid row.
                grid.Rows[i].Height = 23;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    //Create string format for grid row.
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;
                    pdfStringFormat.Alignment     = PdfTextAlignment.Left;

                    //Set cell padding for grid row cell.
                    if (j == 0 || j == 2)
                    {
                        grid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }

                    //Set string format to grid row cell.
                    grid.Rows[i].Cells[j].StringFormat = pdfStringFormat;
                    //Set font to the grid row cell.
                    grid.Rows[i].Cells[j].Style.Font = arialRegularFont;
                }
            }
            //Apply built-in table style to the grid.
            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);
            //Subscribing to begin cell layout event.
            grid.BeginCellLayout += Grid_BeginCellLayout;
            //Draw the PDF grid to PDF page and get the layout result.
            PdfGridLayoutResult result = grid.Draw(page, new PointF(0, y + 40));

            //Using the layout result, continue to draw the text.
            y                = result.Bounds.Bottom + lineSpace;
            format           = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;
            RectangleF bounds = new RectangleF(QuantityCellBounds.X, y, QuantityCellBounds.Width, QuantityCellBounds.Height);
            //Draw text to PDF page based on the layout result.
            page.Graphics.DrawString("Grand Total:", arialBoldFont, PdfBrushes.Black, bounds, format);
            //Draw the total amount value to PDF page based on the layout result.
            bounds = new RectangleF(TotalPriceCellBounds.X, y, TotalPriceCellBounds.Width, TotalPriceCellBounds.Height);
            page.Graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialBoldFont, PdfBrushes.Black, bounds);
            #endregion
            //Create border pen with custom dash style and draw the border to page.
            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };
            graphics.DrawLine(borderPen, new PointF(0, pageHeight - 100), new PointF(pageWidth, pageHeight - 100));

            //Get the image file stream from assembly.
            Stream imageStream = typeof(Invoice).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.AdventureWork.png");
            //Create PDF bitmap image from stream.
            PdfBitmap bitmap = new PdfBitmap(imageStream);
            //Draw the image to PDF page.
            graphics.DrawImage(bitmap, new RectangleF(10, pageHeight - 90, 80, 80));

            //Calculate the text position and draw the text to PDF page.
            y    = pageHeight - 100 + margin;
            size = arialRegularFont.MeasureString("800 Interchange Blvd.");
            x    = pageWidth - size.Width - margin;
            graphics.DrawString("800 Interchange Blvd.", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            //Calculate the text position and draw the text to PDF page.
            y   += arialRegularFont.Height + lineSpace;
            size = arialRegularFont.MeasureString("Suite 2501,  Austin, TX 78721");
            x    = pageWidth - size.Width - margin;
            graphics.DrawString("Suite 2501,  Austin, TX 78721", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            //Calculate the text position and draw the text to PDF page.
            y   += arialRegularFont.Height + lineSpace;
            size = arialRegularFont.MeasureString("Any Questions? [email protected]");
            x    = pageWidth - size.Width - margin;
            graphics.DrawString("Any Questions? [email protected]", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            //Creating the stream object
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the document into stream
                document.Save(stream);
                document.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("Invoice.pdf", stream);
            }
        }
示例#15
0
        private void DrawDataTable(PdfPage page, PdfGraphics graphics)
        {
            //Create a new PdfGrid.
            PdfGrid pdfGrid = new PdfGrid();


            //Pagination
            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            layoutFormat.Break  = PdfLayoutBreakType.FitColumnsToPage;
            layoutFormat.Layout = PdfLayoutType.Paginate;


            //Cell Padding
            pdfGrid.Style.CellPadding.All = 4;
            //Cell align text
            PdfStringFormat centredText = new PdfStringFormat()
            {
                LineAlignment = PdfVerticalAlignment.Middle,
                Alignment     = PdfTextAlignment.Center
            };
            PdfStringFormat leftText = new PdfStringFormat()
            {
                LineAlignment = PdfVerticalAlignment.Middle,
                Alignment     = PdfTextAlignment.Left
            };
            PdfStringFormat rightText = new PdfStringFormat()
            {
                LineAlignment = PdfVerticalAlignment.Middle,
                Alignment     = PdfTextAlignment.Right
            };

            //Add 7 column
            pdfGrid.Columns.Add(5);

            pdfGrid.Columns[0].Width = 270;
            pdfGrid.Columns[1].Width = 50;
            pdfGrid.Columns[2].Width = 70;
            pdfGrid.Columns[3].Width = 80;
            pdfGrid.Columns[4].Width = 100;


            //Add header.
            pdfGrid.Headers.Add(1);
            PdfGridRow pdfGridHeader = pdfGrid.Headers[0];

            pdfGridHeader.Style.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 14);


            pdfGridHeader.Cells[0].Value = AppResources.Description;
            pdfGridHeader.Cells[1].Value = AppResources.Taxes;
            pdfGridHeader.Cells[2].Value = AppResources.Quantity;
            pdfGridHeader.Cells[3].Value = AppResources.UnitPrice;
            pdfGridHeader.Cells[4].Value = AppResources.Price;


            //centre text dans cellule
            for (var i = 0; i < 5; i++)
            {
                pdfGridHeader.Cells[i].StringFormat = centredText;
            }

            //Add Rows
            string logo = model.CurrencyLogo;



            Stream fontstream = typeof(ContactsPage).GetTypeInfo().Assembly.GetManifestResourceStream("voltaire.Resources.Raleway-Regular.ttf");

            for (int i = 0; i < OrderItems.Count; i++)
            {
                PdfGridRow pdfGridRow = pdfGrid.Rows.Add();

                pdfGridRow.Style.Font = new PdfTrueTypeFont(fontstream, 12);

                pdfGridRow.Cells[0].Value        = string.IsNullOrEmpty(OrderItems[i].Description) ? "" : OrderItems[i].Description;
                pdfGridRow.Cells[0].StringFormat = leftText;

                pdfGridRow.Cells[1].Value        = OrderItems[i].TaxPercent.ToString() + "%";
                pdfGridRow.Cells[1].StringFormat = centredText;

                pdfGridRow.Cells[2].Value        = OrderItems[i].Quantity.ToString();
                pdfGridRow.Cells[2].StringFormat = centredText;

                pdfGridRow.Cells[3].Value        = OrderItems[i].Product.PriceUnit + logo;
                pdfGridRow.Cells[3].StringFormat = centredText;

                pdfGridRow.Cells[4].Value        = (OrderItems[i].Product.PriceUnit * OrderItems[i].Product.ProductQty) + logo;
                pdfGridRow.Cells[4].StringFormat = rightText;
            }

            //ajout sub total
            PdfGridRow pdfGridRowTotal = pdfGrid.Rows.Add();

            pdfGridRowTotal.Style.Font            = new PdfTrueTypeFont(fontstream, 12);
            pdfGridRowTotal.Cells[0].ColumnSpan   = 4;
            pdfGridRowTotal.Cells[0].Value        = AppResources.TotalHT;
            pdfGridRowTotal.Cells[0].StringFormat = rightText;

            pdfGridRowTotal.Cells[4].Value        = SaleOrder.AmountUntaxed + logo;
            pdfGridRowTotal.Cells[4].StringFormat = rightText;

            //ajout taxes
            if (true)
            {
                PdfGridRow pdfGridRowDeposit = pdfGrid.Rows.Add();
                pdfGridRowDeposit.Style.Font = new PdfTrueTypeFont(fontstream, 12);

                pdfGridRowDeposit.Cells[0].ColumnSpan   = 4;
                pdfGridRowDeposit.Cells[0].Value        = AppResources.Taxes;
                pdfGridRowDeposit.Cells[0].StringFormat = rightText;

                pdfGridRowDeposit.Cells[4].Value        = SaleOrder.AmountTax + logo;
                pdfGridRowDeposit.Cells[4].StringFormat = rightText;
            }

            //Total
            PdfGridRow pdfGridRowtotal = pdfGrid.Rows.Add();

            pdfGridRowtotal.Style.Font = new PdfTrueTypeFont(fontstream, 12);

            pdfGridRowtotal.Cells[0].ColumnSpan   = 4;
            pdfGridRowtotal.Cells[0].Value        = AppResources.Total;
            pdfGridRowtotal.Cells[0].StringFormat = rightText;

            pdfGridRowtotal.Cells[4].Value        = $"{SaleOrder.AmountTotal}{logo}";
            pdfGridRowtotal.Cells[4].StringFormat = rightText;


            //signature
            if (Signature != null)
            {
                PdfGridRow pdfGridRowsign = pdfGrid.Rows.Add();

                pdfGridRowsign.Height = 70;

                PdfBitmap pBmp = new PdfBitmap(new MemoryStream(Signature));

                pdfGridRowsign.Cells[0].Style.BackgroundImage = pBmp;
                pdfGridRowsign.Cells[0].Value = "";
            }

            //Style du PdfGrid
            PdfGridBuiltinStyleSettings tableStyleOption = new PdfGridBuiltinStyleSettings();

            tableStyleOption.ApplyStyleForBandedRows = true;
            tableStyleOption.ApplyStyleForHeaderRow  = true;

            pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);

            //ecriture du pdfGrid
            resultDataTable = pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, 300), layoutFormat);
        }
示例#16
0
        /// <summary>
        /// Gets PDF file for invoice using Syncfusion.Pdf
        /// </summary>
        /// <param name="invoiceId">invoice Id for which file should be generated</param>
        /// <returns>PDF file for invoice</returns>
        public FileStreamResult GetInvoicePdf(string invoiceId)
        {
            //Declaring colors
            var black     = Color.FromArgb(255, 0, 0, 0);
            var white     = Color.FromArgb(255, 255, 255, 255);
            var lightGray = Color.FromArgb(255, 220, 220, 220);

            var model = InvoiceManager.GetInvoiceViewModelById(invoiceId);

            model.InvoiceLines = InvoiceManager.GetInvoiceLineViewModels(invoiceId);

            var invoiceNo      = model.InvoiceNumber;
            var invoiceHdrText = $"Faktura VAT: {invoiceNo}";

            var customer = model.Customer;

            var invoiceLines = model.InvoiceLines;

            var lightGrayBrush = new PdfSolidBrush(lightGray);

            //Creating new PDF document instance
            PdfDocument document = new PdfDocument();

            //Setting margin
            document.PageSettings.Margins.All = 20;

            //Adding a new page
            PdfPage     page = document.Pages.Add();
            PdfGraphics g    = page.Graphics;

            //Load the custom font as stream
            Stream fontStream = System.IO.File.OpenRead("wwwroot/fonts/Roboto-Regular.ttf");

            //Create a new PDF true type font.
            PdfTrueTypeFont customFont8      = new PdfTrueTypeFont(fontStream, 8, PdfFontStyle.Regular);
            PdfTrueTypeFont customFont8Bold  = new PdfTrueTypeFont(fontStream, 8, PdfFontStyle.Bold);
            PdfTrueTypeFont customFont10     = new PdfTrueTypeFont(fontStream, 10, PdfFontStyle.Regular);
            PdfTrueTypeFont customFont12     = new PdfTrueTypeFont(fontStream, 12, PdfFontStyle.Regular);
            PdfTrueTypeFont customFont12Bold = new PdfTrueTypeFont(fontStream, 12, PdfFontStyle.Bold);
            PdfTrueTypeFont customFont30     = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);

            //Creating font instances
            PdfFont headerFont = customFont30;
            //PdfFont standardText12 = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
            PdfFont standardText12     = customFont12;
            PdfFont standardText12Bold = customFont12Bold;
            PdfFont standardText10     = customFont10;
            PdfFont standardText8      = customFont8;
            PdfFont standardText8Bold  = customFont8Bold;

            //Set page size
            document.PageSettings.Size = PdfPageSize.A4;

            //Set page orientation
            document.PageSettings.Orientation = PdfPageOrientation.Landscape;

            //pen
            var pen = new PdfPen(Color.Black)
            {
                Width = 0.5F
            };

            //Invoice number printing
            var invoiceNoRectangle = new Syncfusion.Drawing.RectangleF(180, 30, 200, 100);

            g.DrawRectangle(lightGrayBrush, invoiceNoRectangle);
            var result = BodyContent(invoiceHdrText, headerFont, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, invoiceNoRectangle);

            //Customer data printing
            var customerDataHeaderRectangle  = new Syncfusion.Drawing.RectangleF(10, 200, 200, 15);
            var customerDataContentRectangle = new Syncfusion.Drawing.RectangleF(10, 215, 200, 100);

            g.DrawRectangle(lightGrayBrush, customerDataHeaderRectangle);
            result = BodyContent("Klient", standardText12Bold, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, customerDataHeaderRectangle);

            g.DrawRectangle(pen, new PdfSolidBrush(white), customerDataContentRectangle);
            var rect = new RectangleF(12, 215, 200, 25);

            result = BodyContent(customer.Name, standardText10, black, PdfTextAlignment.Left, PdfVerticalAlignment.Top, page, rect);
            rect   = new RectangleF(12, result.Bounds.Bottom + 5, 200, 25);
            result = BodyContent($"{customer.Street}/{customer.BuildingNumber}", standardText10, black, PdfTextAlignment.Left, PdfVerticalAlignment.Top, page, rect);
            rect   = new RectangleF(12, result.Bounds.Bottom, 200, 25);
            result = BodyContent($"{customer.PostalCode} {customer.City}", standardText10, black, PdfTextAlignment.Left, PdfVerticalAlignment.Top, page, rect);

            //Dates data printing
            var datesX      = page.Graphics.ClientSize.Width - customerDataHeaderRectangle.Width - customerDataHeaderRectangle.X;
            var datesY      = customerDataHeaderRectangle.Y;
            var datesWidth  = customerDataHeaderRectangle.Width;
            var datesHeight = customerDataHeaderRectangle.Height;

            //issue date
            var issueDateHeaderRectangle      = new Syncfusion.Drawing.RectangleF(datesX, datesY, datesWidth, datesHeight);
            var issueDateDataContentRectangle = new Syncfusion.Drawing.RectangleF(datesX, datesY + datesHeight, datesWidth, 20);

            g.DrawRectangle(lightGrayBrush, issueDateHeaderRectangle);
            BodyContent("Data wydania", standardText12Bold, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, issueDateHeaderRectangle);

            g.DrawRectangle(pen, new PdfSolidBrush(white), issueDateDataContentRectangle);
            result = BodyContent("2018-10-04", standardText10, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, issueDateDataContentRectangle);

            //receipt date
            var receiptDateHeaderRectangle      = new Syncfusion.Drawing.RectangleF(datesX, result.Bounds.Bottom + 9, datesWidth, datesHeight);
            var receiptDateDataContentRectangle = new Syncfusion.Drawing.RectangleF(datesX, result.Bounds.Bottom + 9 + datesHeight, datesWidth, 20);

            g.DrawRectangle(lightGrayBrush, receiptDateHeaderRectangle);
            BodyContent("Data przyjęcia", standardText12Bold, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, receiptDateHeaderRectangle);

            g.DrawRectangle(pen, new PdfSolidBrush(white), receiptDateDataContentRectangle);
            result = BodyContent("2018-10-04", standardText10, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, receiptDateDataContentRectangle);

            //receipt date
            var paymentDateHeaderRectangle      = new Syncfusion.Drawing.RectangleF(datesX, result.Bounds.Bottom + 9, datesWidth, datesHeight);
            var paymentDateDataContentRectangle = new Syncfusion.Drawing.RectangleF(datesX, result.Bounds.Bottom + 9 + datesHeight, datesWidth, 20);

            g.DrawRectangle(lightGrayBrush, paymentDateHeaderRectangle);
            BodyContent("Data płatności", standardText12Bold, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, paymentDateHeaderRectangle);

            g.DrawRectangle(pen, new PdfSolidBrush(white), paymentDateDataContentRectangle);
            result = BodyContent("2018-10-04", standardText10, black, PdfTextAlignment.Center, PdfVerticalAlignment.Middle, page, paymentDateDataContentRectangle);

            //adding grid for invoice lines
            PdfGrid grid = new PdfGrid();

            grid.Style.AllowHorizontalOverflow = false;

            //Set Data source for invoice lines
            if (invoiceLines.Count() == 0)
            {
                invoiceLines = new List <InvoiceLineViewModel>()
                {
                    new InvoiceLineViewModel()
                };
            }

            grid.DataSource = invoiceLines.Select(x => new
            {
                ItemName    = x.ItemName,
                Description = x.Description,
                Quantity    = x.Quantity,
                Price       = x.Price.ToString("N"),
                TaxRate     = x.TaxRate.ToString("##"),
                NetValue    = x.BaseNetto.ToString("N"),
                TaxValue    = x.BaseTax.ToString("N"),
                GrossValue  = x.BaseGross.ToString("N")
            });

            //grid styling
            var styleName = "GridTable4";
            PdfGridBuiltinStyleSettings setting = new PdfGridBuiltinStyleSettings();

            setting.ApplyStyleForHeaderRow     = false;
            setting.ApplyStyleForBandedRows    = false;
            setting.ApplyStyleForBandedColumns = false;
            setting.ApplyStyleForFirstColumn   = false;
            setting.ApplyStyleForLastColumn    = false;
            setting.ApplyStyleForLastRow       = false;

            var gridHeaderStyle = new PdfGridRowStyle()
            {
                BackgroundBrush = new PdfSolidBrush(lightGray),
                Font            = standardText8Bold
            };

            //Set layout properties
            PdfLayoutFormat format = new PdfLayoutFormat();

            format.Break  = PdfLayoutBreakType.FitElement;
            format.Layout = PdfLayoutType.Paginate;

            PdfGridBuiltinStyle style = (PdfGridBuiltinStyle)Enum.Parse(typeof(PdfGridBuiltinStyle), styleName);

            grid.ApplyBuiltinStyle(style, setting);
            grid.Style.Font                    = standardText8;
            grid.Style.CellPadding.All         = 2;
            grid.Style.AllowHorizontalOverflow = false;

            //set header texts
            PdfGridRow pdfGridHeader = grid.Headers[0];

            pdfGridHeader.Style          = gridHeaderStyle;
            pdfGridHeader.Cells[0].Value = "Kod pozycji";
            pdfGridHeader.Cells[1].Value = "Opis";
            pdfGridHeader.Cells[2].Value = "Ilość";
            pdfGridHeader.Cells[3].Value = "Cena";
            pdfGridHeader.Cells[4].Value = "VAT(%)";
            pdfGridHeader.Cells[5].Value = "Netto";
            pdfGridHeader.Cells[6].Value = "VAT";
            pdfGridHeader.Cells[7].Value = "Brutto";

            //grid location
            var gridStartLocation = new PointF(0, result.Bounds.Bottom + 50);

            //Draw table
            result = grid.Draw(page, gridStartLocation, format);

            var summaryByTaxRate = invoiceLines
                                   .GroupBy(x => x.TaxRate)
                                   .Select(x => new
            {
                TaxRate    = x.Key.ToString("##"),
                NetValue   = x.Sum(y => y.BaseNetto).ToString("N"),
                TaxValue   = x.Sum(y => y.BaseTax).ToString("N"),
                GrossValue = x.Sum(y => y.BaseGross).ToString("N")
            });

            //adding summary grid
            PdfGrid summaryGrid = new PdfGrid();

            summaryGrid.Style.AllowHorizontalOverflow = false;

            //Set Data source
            summaryGrid.DataSource = summaryByTaxRate;

            summaryGrid.ApplyBuiltinStyle(style, setting);
            summaryGrid.Style.Font                    = standardText8;
            summaryGrid.Style.CellPadding.All         = 2;
            summaryGrid.Style.AllowHorizontalOverflow = false;


            //set header texts
            PdfGridRow pdfSummaryGridHeader = summaryGrid.Headers[0];

            pdfSummaryGridHeader.Style          = gridHeaderStyle;
            pdfSummaryGridHeader.Cells[0].Value = "według stawki VAT";
            pdfSummaryGridHeader.Cells[1].Value = "wartość netto";
            pdfSummaryGridHeader.Cells[2].Value = "wartość VAT";
            pdfSummaryGridHeader.Cells[3].Value = "wartość brutto";

            summaryGrid.Columns[0].Width = 80;
            summaryGrid.Columns[1].Width = 60;
            summaryGrid.Columns[2].Width = 60;
            summaryGrid.Columns[3].Width = 60;

            //create summary total GridRow
            var summaryTotalNetto = invoiceLines.Sum(x => x.BaseNetto);
            var summaryTotalTax   = invoiceLines.Sum(x => x.BaseTax);
            var summaryTotalGross = invoiceLines.Sum(x => x.BaseGross);

            var summaryTotalRow = new PdfGridRow(summaryGrid);

            summaryGrid.Rows.Add(summaryTotalRow);
            summaryTotalRow.Cells[0].Value      = "Razem:";
            summaryTotalRow.Cells[0].Style.Font = customFont8Bold;
            summaryTotalRow.Cells[1].Value      = summaryTotalNetto.ToString("N");
            summaryTotalRow.Cells[2].Value      = summaryTotalTax.ToString("N");
            summaryTotalRow.Cells[3].Value      = summaryTotalGross.ToString("N");

            float columnsWidth = 0;

            foreach (PdfGridColumn column in summaryGrid.Columns)
            {
                columnsWidth += column.Width;
            }

            //Summary grid location
            var summaryGridStartLocation = new PointF(page.GetClientSize().Width - columnsWidth, result.Bounds.Bottom + 20);

            //Draw table
            result = summaryGrid.Draw(page, summaryGridStartLocation, format);

            //Saving the PDF to the MemoryStreamcolumnsWidth
            MemoryStream ms = new MemoryStream();

            document.Save(ms);

            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;

            var contentType = "application/pdf";
            var fileName    = $"{invoiceNo.Replace("/", "_")}_{DateHelper.GetCurrentDatetime():yyyyMMdd}.pdf";

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, contentType);

            fileStreamResult.FileDownloadName = fileName;
            return(fileStreamResult);
        }
示例#17
0
        public ActionResult AddPrescription(PrescriptionViewModel model)
        {
            if (ModelState.IsValid && model.days != null)
            {
                var prescription = _db.Prescriptions.Where(p => p.PrescriptionId == model.Id).FirstOrDefault();

                PdfDocument doc = new PdfDocument();


                //Add a page.
                PdfPage page = doc.Pages.Add();
                //Create PDF graphics for the page
                PdfGraphics graphics = page.Graphics;
                //Set the standard font
                PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 10);

                graphics.DrawString("Patient Name : " + prescription.appointment.patient.User.Name, font, PdfBrushes.Black, new PointF(0, 0));

                graphics.DrawString("Appoiment Time " + prescription.appointment.AppointmentTime.ToString("dd-MMMM-yyyy hh:mm tt"), font, PdfBrushes.Black, new PointF(0, 12));

                graphics.DrawString("Doctor Name : " + prescription.appointment.doctor.User.Name, font, PdfBrushes.Black, new PointF(0, 24));

                graphics.DrawString("Doctor Contact No : " + prescription.appointment.doctor.User.PhoneNumber, font, PdfBrushes.Black, new PointF(0, 36));

                //Create a PdfGrid.
                PdfGrid pdfGrid = new PdfGrid();
                //Create a DataTable.
                DataTable dataTable = new DataTable();
                //Add columns to the DataTable
                dataTable.Columns.Add("Medicine Name");
                dataTable.Columns.Add("Quantity");
                dataTable.Columns.Add("Days");
                dataTable.Columns.Add("Times");

                for (int i = 0; i < model.times.Count; i++)
                {
                    dataTable.Rows.Add(new object[] { model.medicines[i], model.quantity[i], model.days[i], model.times[i] });
                }
                //Assign data source.
                pdfGrid.DataSource = dataTable;

                PdfGridBuiltinStyleSettings tableStyleOption = new PdfGridBuiltinStyleSettings();
                tableStyleOption.ApplyStyleForBandedRows = true;
                tableStyleOption.ApplyStyleForHeaderRow  = true;
                pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent4, tableStyleOption);
                //Draw grid to the page of PDF document.
                pdfGrid.Draw(page, new PointF(0, 50));

                string filePathString = "~/Images/" + model.Id + ".pdf";

                // Open the document in browser after saving it
                doc.Save(Server.MapPath(filePathString));
                //close the document
                doc.Close(true);


                _db.Entry(prescription).State = EntityState.Modified;
                prescription.FileURL          = filePathString;
                _db.SaveChanges();

                TempData["Success"] = "Prescription added for appointment no. " + model.Id;

                return(RedirectToAction("Index", "DoctorAccount"));
            }


            return(View(model));
        }
        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);
        }
        /// <summary>
        /// Create ZugFerd Invoice Pdf
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public PdfDocument CreateZugFerdInvoicePDF(PdfDocument document)
        {
            //Add page to the PDF
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Create border color
            PdfColor borderColor = Syncfusion.Drawing.Color.FromArgb(255, 142, 170, 219);

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

            //Set the header height
            float headerHeight = 90;


            PdfColor lightBlue      = Syncfusion.Drawing.Color.FromArgb(255, 91, 126, 215);
            PdfBrush lightBlueBrush = new PdfSolidBrush(lightBlue);

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

            PdfBrush whiteBrush = new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255));

#if COMMONSB
            Stream fontStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.arial.ttf");
#else
            Stream fontStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.arial.ttf");
#endif

            PdfTrueTypeFont headerFont = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);

            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 18, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);

            //Create string format.
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            float y = 0;
            float x = 0;

            //Set the margins of address.
            float margin = 30;

            //Set the line space
            float lineSpace = 7;

            PdfPen borderPen = new PdfPen(borderColor, 1f);

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


            PdfGrid grid = new PdfGrid();

            grid.DataSource = GetProductReport();

            #region Header

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

            string title = "INVOICE";

            SizeF textSize = headerFont.MeasureString(title);

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

            graphics.DrawString(title, headerFont, whiteBrush, new RectangleF(0, 0, textSize.Width + 50, headerHeight), format);

            graphics.DrawRectangle(darkBlueBrush, headerTotalBounds);

            graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight + 10), format);

            arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);

            format.LineAlignment = PdfVerticalAlignment.Bottom;
            graphics.DrawString("Amount", arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight / 2 - arialRegularFont.Height), format);

            #endregion


            SizeF size = arialRegularFont.MeasureString("Invoice Number: 2058557939");
            y = headerHeight + margin;
            x = (pageWidth - margin) - size.Width;

            graphics.DrawString("Invoice Number: 2058557939", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            size = arialRegularFont.MeasureString("Date :" + DateTime.Now.ToString("dddd dd, MMMM yyyy"));
            x    = (pageWidth - margin) - size.Width;
            y   += arialRegularFont.Height + lineSpace;

            graphics.DrawString("Date: " + DateTime.Now.ToString("dddd dd, MMMM yyyy"), arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y = headerHeight + margin;
            x = margin;
            graphics.DrawString("Bill To:", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("Abraham Swearegin,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("United States, California, San Mateo,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9920 BridgePointe Parkway,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9365550136", arialRegularFont, PdfBrushes.Black, new PointF(x, y));


            #region Grid

            grid.Columns[0].Width = 110;
            grid.Columns[1].Width = 150;
            grid.Columns[2].Width = 110;
            grid.Columns[3].Width = 70;
            grid.Columns[4].Width = 100;

            for (int i = 0; i < grid.Headers.Count; i++)
            {
                grid.Headers[i].Height = 20;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;

                    pdfStringFormat.Alignment = PdfTextAlignment.Left;
                    if (j == 0 || j == 2)
                    {
                        grid.Headers[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }

                    grid.Headers[i].Cells[j].StringFormat = pdfStringFormat;

                    grid.Headers[i].Cells[j].Style.Font = arialBoldFont;
                }
                grid.Headers[0].Cells[0].Value = "Product Id";
            }
            for (int i = 0; i < grid.Rows.Count; i++)
            {
                grid.Rows[i].Height = 23;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;

                    pdfStringFormat.Alignment = PdfTextAlignment.Left;
                    if (j == 0 || j == 2)
                    {
                        grid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }

                    grid.Rows[i].Cells[j].StringFormat = pdfStringFormat;
                    grid.Rows[i].Cells[j].Style.Font   = arialRegularFont;
                }
            }
            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);
            grid.BeginCellLayout += Grid_BeginCellLayout;


            PdfGridLayoutResult result = grid.Draw(page, new PointF(0, y + 40));

            y                = result.Bounds.Bottom + lineSpace;
            format           = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;
            RectangleF bounds = new RectangleF(QuantityCellBounds.X, y, QuantityCellBounds.Width, QuantityCellBounds.Height);

            page.Graphics.DrawString("Grand Total:", arialBoldFont, PdfBrushes.Black, bounds, format);

            bounds = new RectangleF(TotalPriceCellBounds.X, y, TotalPriceCellBounds.Width, TotalPriceCellBounds.Height);
            page.Graphics.DrawString(GetTotalAmount(grid).ToString(), arialBoldFont, PdfBrushes.Black, bounds);


            #endregion



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

            graphics.DrawLine(borderPen, new PointF(0, pageHeight - 100), new PointF(pageWidth, pageHeight - 100));

            y = pageHeight - 100 + margin;

            size = arialRegularFont.MeasureString("800 Interchange Blvd.");

            x = pageWidth - size.Width - margin;

            graphics.DrawString("800 Interchange Blvd.", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y += arialRegularFont.Height + lineSpace;

            size = arialRegularFont.MeasureString("Suite 2501,  Austin, TX 78721");

            x = pageWidth - size.Width - margin;

            graphics.DrawString("Suite 2501,  Austin, TX 78721", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y += arialRegularFont.Height + lineSpace;

            size = arialRegularFont.MeasureString("Any Questions? [email protected]");

            x = pageWidth - size.Width - margin;
            graphics.DrawString("Any Questions? [email protected]", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            return(document);
        }
示例#20
0
        public MemoryStream CrearPdf(List <EstudianteEvaluacion> estudiantes, Asignaciones asignacion, Profesores profesor, String curso, String grupo, int anio, int periodo)
        {
            using (PdfDocument pdfDocument = new PdfDocument())
            {
                int paragraphAfterSpacing = 8;
                int cellMargin            = 8;

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

                //Create a new font
                PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

                //Create a text element to draw a text in PDF page
                PdfTextElement  title  = new PdfTextElement("Informe de notas " + grupo, font, PdfBrushes.Black);
                PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
                string          fecha  = DateTime.Now.ToShortDateString();

                PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement  content     = new PdfTextElement("Profesor: " + profesor.Nombre + " " + profesor.PrimerApellido + " " + profesor.SegundoApellido + "             Fecha: " + fecha + "\n" +
                                                                 "Curso: " + curso + "     Grupo: " + grupo + "      Anio: " + anio + "     Rubro: " + asignacion.Tipo + "    Asignación: " + asignacion.Nombre + "\n" +
                                                                 "Puntos: " + asignacion.Puntos + "      Porcentaje: " + asignacion.Porcentaje + "\n" +
                                                                 "Periodo: " + periodo, contentFont, PdfBrushes.Black);
                PdfLayoutFormat format = new PdfLayoutFormat();
                format.Layout = PdfLayoutType.Paginate;

                //Draw a text to the PDF document
                result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);

                PdfGrid pdfGrid = new PdfGrid();

                pdfGrid.Style.CellPadding.Left  = cellMargin;
                pdfGrid.Style.CellPadding.Right = cellMargin;

                //Applying built-in style to the PDF grid
                pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
                // Initialize DataTable to assign as DateSource to the light table.

                DataTable table = new DataTable();

                //Include columns to the DataTable.

                table.Columns.Add("Cédula");

                table.Columns.Add("Nombre");

                table.Columns.Add("Puntos");

                table.Columns.Add("Porcentaje");

                table.Columns.Add("Nota");
                //Include rows to the DataTable.
                foreach (EstudianteEvaluacion estu in estudiantes)
                {
                    table.Rows.Add(new object[] { estu.Cedula, estu.Nombre, estu.Puntos.ToString(), estu.Porcentaje.ToString(), estu.Nota.ToString() });
                }


                //Assign data source.

                pdfGrid.DataSource = table;

                pdfGrid.Style.Font = contentFont;

                //Draw PDF grid into the PDF page
                pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));

                using (MemoryStream stream = new MemoryStream())
                {
                    //Saving the PDF document into the stream
                    pdfDocument.Save(stream);
                    //Closing the PDF document
                    pdfDocument.Close(true);
                    return(stream);
                }
            }
        }