Exemplo n.º 1
0
        private void DrawRectangles(PointF startPoint, PdfGraphics g, PdfFont font, PdfBrush brush, PdfPen pen, PdfDocument doc)
        {
            PdfBrush   textBrush = new PdfSolidBrush(Color.Black);
            RectangleF rect      = new RectangleF(startPoint.X, startPoint.Y, 100, 100);

            g.Save();

            g.DrawString("Default: " + doc.ColorSpace.ToString(), font, textBrush, rect.Location);
            rect.Y += 20;
            g.DrawRectangle(pen, brush, rect);
            rect.Y += 106;

            doc.ColorSpace = PdfColorSpace.RGB;

            g.DrawString("RGB color space.", font, textBrush, rect.Location);
            rect.Y += 20;
            g.DrawRectangle(pen, brush, rect);
            rect.Y += 106;

            doc.ColorSpace = PdfColorSpace.CMYK;

            g.DrawString("CMYK color space.", font, textBrush, rect.Location);
            rect.Y += 20;
            g.DrawRectangle(pen, brush, rect);
            rect.Y += 106;

            doc.ColorSpace = PdfColorSpace.GrayScale;

            g.DrawString("Gray scale color space.", font, textBrush, rect.Location);
            rect.Y += 20;
            g.DrawRectangle(pen, brush, rect);
            rect.Y += 106;

            g.Restore();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Genera el Header en el documento especificado
        /// </summary>
        /// <param name="document">Documento PDF</param>
        /// <param name="title">Titulo del reporte</param>
        /// <returns>Documento PDF modificado</returns>
        internal static PdfDocument GenerateHeader(PdfDocument document, string title)
        {
            foreach (PdfPage page in document.Pages)
            {
                PdfGraphics graphics = page.Graphics;

                // Logo

                PdfImage image = new PdfBitmap("Logo.png");

                float PageWidth  = (float)Helper.MM2PX(60);
                float PageHeight = (float)Helper.MM2PX(30);
                float myWidth    = image.Width;
                float myHeight   = image.Height;

                float shrinkFactor;

                if (myWidth > PageWidth)
                {
                    shrinkFactor = myWidth / PageWidth;
                    myWidth      = PageWidth;
                    myHeight     = myHeight / shrinkFactor;
                }

                if (myHeight > PageHeight)
                {
                    shrinkFactor = myHeight / PageHeight;
                    myHeight     = PageHeight;
                    myWidth      = myWidth / shrinkFactor;
                }

                float XPosition = ((float)Helper.MM2PX(80) - myWidth) / 2;
                float YPosition = ((float)Helper.MM2PX(40) - myHeight) / 2;

                graphics.DrawImage(image, XPosition, YPosition, myWidth, myHeight);

                // Titulo.
                graphics.DrawRectangle(
                    new PdfPen(new PdfColor(0, 0, 0), 0.5F),
                    new RectangleF((float)Helper.MM2PX(10), (float)Helper.MM2PX(40), (float)Helper.MM2PX(60), (float)Helper.MM2PX(12)));
                graphics.DrawRectangle(
                    new PdfPen(new PdfColor(0, 0, 0), 0.5F),
                    new RectangleF((float)Helper.MM2PX(11), (float)Helper.MM2PX(41), (float)Helper.MM2PX(58), (float)Helper.MM2PX(10)));
                graphics.DrawString(
                    title,
                    new PdfTrueTypeFont("Ubuntu-Regular.ttf", 21),
                    PdfBrushes.Black,
                    new RectangleF((float)Helper.MM2PX(11), (float)Helper.MM2PX(41), (float)Helper.MM2PX(58), (float)Helper.MM2PX(10)),
                    new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            }

            return(document);
        }
Exemplo n.º 3
0
        void IPainter.FillRectangle(int x, int y, int width, int height, int argb)
        {
            if ((argb & 0x00ffffff) == 0x00ffffff)
            {
                return;                 // Do not fill white paint onto white canvas
            }

            PdfGraphics.DrawRectangle(GetBrush(argb), x + Shift.Width - 0.75f, y + Shift.Height - 0.75f, width + 1, height + 1);
        }
Exemplo n.º 4
0
        private void Draw(PdfGraphics g, Box box)
        {
            var boxX = (float)box.Layout.X;
            var boxY = (float)box.Layout.Y;
            var boxH = (float)box.Layout.Height;
            var boxW = (float)box.Layout.Width;

            var color      = new PdfColor(GetColor(box.Appearance.Background));
            var background = new PdfSolidBrush(color);

            g.DrawRectangle(background, boxX, boxY, boxW, boxH);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Generate pdf file with data from ticket model
        /// </summary>
        /// <param name="model">instance of Ticket class</param>
        public static void GenerateTicket(Ticket model)
        {
            using (PdfDocument document = new PdfDocument())
            {
                // Set the page size.
                document.PageSettings.Size        = new SizeF(500, 250);
                document.PageSettings.Orientation = PdfPageOrientation.Landscape;

                //Add a page to the document
                PdfPage page = document.Pages.Add();
                document.PageSettings.Margins.All = 0;

                //Create PDF graphics for a page
                PdfGraphics graphics = page.Graphics;

                //Create new PDF brush.
                PdfBrush brushSilver   = new PdfSolidBrush(Color.FromArgb(212, 212, 220));
                PdfBrush brushDarkGrey = new PdfSolidBrush(Color.FromArgb(57, 63, 77));
                PdfBrush brushYellow   = new PdfSolidBrush(Color.FromArgb(254, 218, 106));

                //Draw rectangle.
                graphics.DrawRectangle(brushDarkGrey, new RectangleF(0, 0, 500, 250));

                //Set the standard font
                PdfFont fontTitle      = new PdfTrueTypeFont(new Font("Broadway", 40));
                PdfFont fontMovieTitle = new PdfTrueTypeFont(new Font("Letter Gothic Std", 25));
                PdfFont font           = new PdfTrueTypeFont(new Font("Letter Gothic Std", 15));

                string title          = "Kino Neptun";
                string movieTitle     = model.MovieTitle;
                string rowNumber      = "Rząd " + model.RowNumber.ToString();
                string seatNumber     = "Miejsce " + model.SeatNumber.ToString();
                string showingDate    = model.ShowingDateTime.ToString("dd MMM yyyy");
                string showingTime    = model.ShowingDateTime.ToString("HH:mm");
                SizeF  sizeTitle      = fontTitle.MeasureString(title);
                SizeF  sizeMovieTitle = fontMovieTitle.MeasureString(movieTitle);

                //Draw the text
                graphics.DrawString(title, fontTitle, brushSilver, new RectangleF(new PointF(20, 20), sizeTitle));
                graphics.DrawString(movieTitle, fontMovieTitle, brushYellow, new RectangleF(new PointF(20, 80), sizeMovieTitle));
                graphics.DrawString(rowNumber, font, brushSilver, new PointF(300, 120));
                graphics.DrawString(seatNumber, font, brushSilver, new PointF(300, 140));
                graphics.DrawString(showingDate, font, brushSilver, new PointF(20, 120));
                graphics.DrawString(showingTime, font, brushSilver, new PointF(20, 140));

                //Save the document
                string path     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string filepath = path + @"/Tickets/ticket_" + model.Id + ".pdf";
                document.Save(filepath);
            }
        }
Exemplo n.º 6
0
        public override void DrawShapeForPdf(PdfGraphics g, float pdfDocumentWidth, float pdfDocumentHeight)
        {
            PdfPen   pdfPen = new PdfPen(MyPen.Color);
            PdfBrush brush  = null;

            var topLeftX     = pdfDocumentWidth / 2 + float.Parse(topLeftCoordinates[0]);
            var topLeftY     = pdfDocumentHeight / 2 - float.Parse(topLeftCoordinates[1]);
            var pdfRectangle = new RectangleF(topLeftX, topLeftY, Width, Height);

            if (Filled)
            {
                brush = new PdfSolidBrush(pdfPen.Color);
            }
            g.DrawRectangle(pdfPen, brush, pdfRectangle);
        }
Exemplo n.º 7
0
        public MemoryStream CreatePdfDocument(CbTransH trans)
        {
            string Title   = "BUKTI KAS/BANK";
            string Tanggal = "Tanggal";
            string NoDoc   = "No.";


            // var cetak = JsonConvert.DeserializeObject(trans);
            // Console.WriteLine(trans);

            //Create a new PDF document
            PdfDocument document = new PdfDocument();

            // document.PageSettings = new PdfPageSettings(new SizeF(300, 400));
            //Add a page
            document.PageSettings.Margins.All = 0;
            PdfPage page = document.Pages.Add();
            //Create Pdf graphics for the page
            PdfGraphics g = page.Graphics;
            //Create a solid brush
            PdfBrush brush      = new PdfSolidBrush(new PdfColor(0, 0, 0));
            PdfBrush tintamerah = new PdfSolidBrush(Color.Red);
            //Set the font
            PdfFont fontJudul = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
            PdfFont fontField = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
            //Draw Kotak
            RectangleF rectangle = new RectangleF(20, 120, 50, 50);

            g.DrawRectangle(brush, rectangle);
            g.TranslateTransform(60, 0);
            // Judul

            //Draw the text
            g.DrawString(Title, fontJudul, tintamerah, new PointF(150, 20));
            g.DrawString(Tanggal, fontField, brush, new PointF(0, 50));
            g.DrawString(trans.Tanggal.ToShortDateString(), fontField, brush, new PointF(50, 50));
            g.DrawString(NoDoc, fontField, brush, new PointF(0, 80));
            g.DrawString(trans.DocNo, fontField, brush, new PointF(50, 80));

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

            document.Save(ms);
            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;
            return(ms);
        }
Exemplo n.º 8
0
        private void Draw(PdfGraphics g, CheckBox box)
        {
            var lineWidth = Math.Min(box.Layout.Width, box.Layout.Height) / 10.0;

            var x      = box.Layout.X;
            var y      = box.Layout.Y;
            var width  = box.Layout.Width - lineWidth;
            var height = box.Layout.Height - lineWidth;

            var shiftX = 0.0;
            var shiftY = 0.0;

            if (width > height)
            {
                shiftX = (width - height) / 2;
                width  = height;
            }

            if (width < height)
            {
                shiftY = (height - width) / 2.0;
                height = width;
            }

            shiftX += x + (lineWidth / 2);
            shiftY += y + (lineWidth / 2);

            var pen = new PdfPen(PdfBrushes.Black, (float)lineWidth);

            g.DrawRectangle(pen, (float)x, (float)y, (float)width, (float)height);

            if (box.IsChecked)
            {
                pen = new PdfPen(PdfBrushes.Black, (float)lineWidth * 1.5f);
                g.DrawLine(pen, (float)(x + width * 0.2), (float)(y + height * 0.57),
                           (float)(x + width * 0.4), (float)(y + height * 0.77));
                g.DrawLine(pen, (float)(x + width * 0.4), (float)(y + height * 0.77),
                           (float)(x + width * 0.8), (float)(y + height * 0.27));
            }
        }
Exemplo n.º 9
0
        private void GenerateReportOfSegment(double BegMeasure, double endMeasure, string outFile)
        {
            if (checkBoxRotateMap.Checked)
            {
                IFeatureLayer pCenterlineLayer    = null;
                string        pCenterlineFileName = comboBoxExCenterline.SelectedItem.ToString();
                for (int i = 0; i < pMapcontrol.LayerCount; i++)
                {
                    if (pCenterlineFileName == pMapcontrol.get_Layer(i).Name)
                    {
                        pCenterlineLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                }
                IFeatureClass pCenterlineFC = pCenterlineLayer.FeatureClass;
                try
                {
                    IFeatureCursor pCurcor  = pCenterlineFC.Search(null, false);
                    IFeature       pFeature = pCurcor.NextFeature();
                    IGeometry      pGeo     = pFeature.Shape;
                    IMSegmentation pMS      = pGeo as IMSegmentation;
                    double         minM     = pMS.MMin;
                    double         maxM     = pMS.MMax;
                    BegMeasure = BegMeasure < minM ? minM : BegMeasure;
                    endMeasure = endMeasure > maxM ? maxM : endMeasure;
                    IPoint begPt = pMS.GetPointsAtM(BegMeasure, 0).Geometry[0] as IPoint;
                    IPoint endPt = pMS.GetPointsAtM(endMeasure, 0).Geometry[0] as IPoint;

                    ISpatialReference sourcePrj;
                    sourcePrj = pCenterlineFC.Fields.get_Field(pCenterlineFC.FindField(pCenterlineFC.ShapeFieldName)).GeometryDef.SpatialReference;
                    ISpatialReference targetPrj = pMapcontrol.Map.SpatialReference;
                    IPoint            begPtPrj;
                    IPoint            endPtPrj;
                    begPt.Project(targetPrj);
                    endPt.Project(targetPrj);
                    begPtPrj = begPt;
                    endPtPrj = endPt;
                    IActiveView pView = this.pMapcontrol.Map as IActiveView;
                    pView.ScreenDisplay.DisplayTransformation.Rotation = 0;
                    double widthHeightR = (((double)pView.ExportFrame.right - pView.ExportFrame.left) / ((double)pView.ExportFrame.bottom - pView.ExportFrame.top));
                    // Dim fw As New FileWindow(begPt, endPt, widthHeightR)
                    MCenterlineUtil fw = new MCenterlineUtil(begPtPrj, endPtPrj, widthHeightR);

                    fw.FitActiveViewTo(pView, true);

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pCurcor);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }


            #region //导出arcmap 地图 export mapfram

            IPageLayout _PageLayout = this.pPageLayoutControl.PageLayout;
            SizeF       m_PageSize  = new SizeF();
            double      width;
            double      hight;



            _PageLayout.Page.QuerySize(out width, out hight);
            m_PageSize.Width  = Convert.ToSingle(width);
            m_PageSize.Height = Convert.ToSingle(hight);
            IUnitConverter pUConvert = new UnitConverterClass();
            esriUnits      ut        = _PageLayout.Page.Units;
            float          pageUnitToInchUnitScale = (float)pUConvert.ConvertUnits(1, ut, esriUnits.esriInches);



            var layerOutPageSize = m_PageSize;
            var outputDPI        = 300;
            int BandHeadWidth    = 40;

            var originalActiveView = _PageLayout as IActiveView;
            var activeView         = _PageLayout as IActiveView;
            originalActiveView.Refresh();
            var avEvents = _PageLayout as IActiveViewEvents;

            float centerX = layerOutPageSize.Width / 2;
            float centerY = layerOutPageSize.Height / 2;

            var backGroundEnv = new Envelope() as IEnvelope;
            backGroundEnv.PutCoords(0, 0, layerOutPageSize.Width, layerOutPageSize.Height);

            activeView.Extent = backGroundEnv;
            //System.Threading.Thread.Sleep(2000);

            IExport pExporter = new ExportPDF() as IExport;
            pExporter.ExportFileName = outFile;
            pExporter.Resolution     = outputDPI;

            var pExPdf = pExporter as IExportPDF;
            pExPdf.Compressed       = true;
            pExPdf.ImageCompression = esriExportImageCompression.esriExportImageCompressionDeflate;

            var screenResolution = GetCurrentScreenResolution();
            var outputResolution = outputDPI;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = (int)(activeView.ExportFrame.right * outputResolution / screenResolution) + 1;
            exportRECT.bottom = (int)(activeView.ExportFrame.bottom * outputResolution / screenResolution) + 1;

            var envelope = new Envelope() as IEnvelope;
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            pExporter.PixelBounds = envelope;

            var hDC = pExporter.StartExporting();
            activeView.Output(hDC, outputDPI, exportRECT, backGroundEnv, null);

            pExporter.FinishExporting();
            pExporter.Cleanup();
            // MessageBox.Show("Export finished.");
            #endregion

            #region  //根据中线图层生成剖面图
            System.Drawing.Point LastBottomLeftPoint = new System.Drawing.Point();
            int         bandwidth = 0;
            PdfGraphics pGraphics = null;

            IFeatureLayer pCenterlinePointLayer = null;
            string        centerlinePointnName  = cboBoxPointLayer.SelectedItem.ToString();

            for (int i = 0; i < pMapcontrol.LayerCount; i++)
            {
                if (centerlinePointnName == pMapcontrol.get_Layer(i).Name)
                {
                    pCenterlinePointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
            }
            IQueryFilter pQF = null;
            DataTable    centerlinePointTable = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pCenterlinePointLayer.FeatureClass as ITable, pQF);
            chartControl1.Series.Clear();
            Series         series  = new Series("高程", ViewType.Line);
            Series         series2 = new Series("埋深", ViewType.Line);
            SecondaryAxisY myAxisY = new SecondaryAxisY("埋深");

            foreach (DataRow r in centerlinePointTable.Rows)
            {
                double m; double z; double underz;
                m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                if (m < BegMeasure || m > endMeasure)
                {
                    continue;
                }
                if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r[EvConfig.CenterlineZField] != DBNull.Value)
                {
                    m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                    z = Convert.ToDouble(r[EvConfig.CenterlineZField]);
                    series.Points.Add(new SeriesPoint(m, z));
                }
                // if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r["管道埋深("] != DBNull.Value)
                if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r[EvConfig.CenterlineBuryDepthField] != DBNull.Value)
                {
                    m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                    z = Convert.ToDouble(r[EvConfig.CenterlineBuryDepthField]);
                    series2.Points.Add(new SeriesPoint(m, z));
                }
            }

            chartControl1.Series.Add(series);
            chartControl1.Series.Add(series2);
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesX.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Add(myAxisY);
            ((LineSeriesView)series2.View).AxisY = myAxisY;
            ((LineSeriesView)series.View).AxisY  = ((XYDiagram)chartControl1.Diagram).AxisY;
            series.ChangeView(ViewType.Line);
            ((XYDiagram)chartControl1.Diagram).AxisY.WholeRange.Auto = true;
            myAxisY.WholeRange.Auto = true;
            series2.ChangeView(ViewType.Line);
            myAxisY.Tickmarks.Visible      = true;
            myAxisY.Tickmarks.MinorVisible = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.AutoSideMargins  = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SideMarginsValue = 0;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SetMinMaxValues(BegMeasure, endMeasure);
            series.ArgumentScaleType = ScaleType.Numerical;

            int ProfileMapHight = 8;

            #endregion


            #region export chartcontrol
            IGraphicsContainer pGC = _PageLayout as IGraphicsContainer;
            pGC.Reset();
            IElement pE = pGC.Next();
            while (pE != null)
            {
                if (pE is IMapFrame)
                {
                    // framgeo related to _PageLayout.Page pagesize, 8.5 x 11, inch
                    IEnvelope framgeo    = pE.Geometry.Envelope as IEnvelope;
                    float     defaultDPI = PdfGraphics.DefaultDpi;
                    double    x          = defaultDPI * framgeo.LowerLeft.X * pageUnitToInchUnitScale;
                    double    y          = defaultDPI * (layerOutPageSize.Height - framgeo.LowerLeft.Y) * pageUnitToInchUnitScale + 1;

                    bandwidth = (int)(defaultDPI * (framgeo.Width * pageUnitToInchUnitScale));

                    LastBottomLeftPoint.X = (int)x;
                    LastBottomLeftPoint.Y = (int)y;

                    chartControl1.Size = new System.Drawing.Size((int)(framgeo.Width * pageUnitToInchUnitScale * defaultDPI), (int)(ProfileMapHight * pageUnitToInchUnitScale * defaultDPI));

                    Image  img = null;
                    Bitmap bmp = null;
                    // Create an image of the chart.
                    ImageFormat format = ImageFormat.Png;
                    using (MemoryStream s = new MemoryStream())
                    {
                        chartControl1.ExportToImage(s, format);
                        img = Image.FromStream(s);
                        bmp = new Bitmap(img);
                        bmp.SetResolution(300, 300);
                    }

                    using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
                    {
                        processor.LoadDocument(outFile);
                        PdfDocument  pd     = processor.Document;
                        PdfPage      page   = pd.Pages[0];
                        PdfRectangle pdfrec = page.MediaBox;
                        // RectangleF rf = new RectangleF(0, 0, Convert.ToSingle(pdfrec.Width) * 96 / 72, Convert.ToSingle(pdfrec.Height) * 96 / 72);
                        // Create and draw PDF graphics.
                        using (pGraphics = processor.CreateGraphics())
                        {
                            PdfGraphics graph = pGraphics;

                            Pen defaultPen = new Pen(Color.Black);
                            defaultPen.Width = 1;
                            graph.DrawImage(bmp, new RectangleF((float)x, (float)y, (float)framgeo.Width * pageUnitToInchUnitScale * defaultDPI, (float)ProfileMapHight * pageUnitToInchUnitScale * defaultDPI));

                            // draw map head.
                            RectangleF MapheadRect = new RectangleF((float)(int)(defaultDPI * framgeo.XMin * pageUnitToInchUnitScale - BandHeadWidth),
                                                                    (float)(int)(defaultDPI * (layerOutPageSize.Height - framgeo.UpperLeft.Y) * pageUnitToInchUnitScale),
                                                                    (float)(int)(BandHeadWidth),
                                                                    (float)(int)(defaultDPI * framgeo.Height * pageUnitToInchUnitScale));
                            graph.DrawRectangle(defaultPen, MapheadRect);
                            //draw head text
                            RectangleF      rF  = new RectangleF(0, 0, (float)MapheadRect.Height, (float)BandHeadWidth);
                            PdfStringFormat psf = new PdfStringFormat(PdfStringFormat.GenericDefault);
                            psf.Alignment     = PdfStringAlignment.Center;
                            psf.LineAlignment = PdfStringAlignment.Center;
                            graph.SaveGraphicsState();
                            // head box 的左下角
                            System.Drawing.Font textfont = new System.Drawing.Font("仿宋", 6F);
                            graph.TranslateTransform((float)(MapheadRect.Left), (float)(MapheadRect.Bottom));
                            graph.RotateTransform(270);
                            graph.DrawString("地图", textfont, new SolidBrush(Color.Black), rF, psf);
                            graph.RestoreGraphicsState();


                            // draw chart head
                            RectangleF ChartheadRect = new RectangleF((float)(int)(defaultDPI * framgeo.XMin * pageUnitToInchUnitScale - BandHeadWidth),
                                                                      (float)(int)(defaultDPI * (layerOutPageSize.Height - framgeo.LowerLeft.Y) * pageUnitToInchUnitScale + 1),
                                                                      (float)(int)(BandHeadWidth),
                                                                      (float)(int)(defaultDPI * ProfileMapHight * pageUnitToInchUnitScale));
                            graph.DrawRectangle(defaultPen, ChartheadRect);
                            //draw head text
                            rF = new RectangleF(0, 0, (float)ChartheadRect.Height, (float)BandHeadWidth);
                            graph.SaveGraphicsState();
                            // head box 的左下角
                            graph.TranslateTransform((float)(ChartheadRect.Left), (float)(ChartheadRect.Bottom));
                            graph.RotateTransform(270);
                            graph.DrawString("剖面图", textfont, new SolidBrush(Color.Black), rF, psf);
                            graph.RestoreGraphicsState();


                            LastBottomLeftPoint.Y = (int)ChartheadRect.Bottom;
                            //double beginM = -999; double endM = -999;
                            //GetIMUBeginEndMeasure(ref beginM, ref endM);
                            double beginM = BegMeasure;
                            double endM   = endMeasure;
                            for (int i = 0; i < listBoxDrawBandFields.Items.Count; i++)
                            {
                                string fieldname = listBoxDrawBandFields.Items[i].ToString();
                                band   b         = new band();
                                b.BandName    = fieldname;
                                b.pdfGC       = pGraphics;
                                b.BandWidth   = (int)bandwidth;
                                b.headFont    = labelbiaotou.Font;
                                b.ContentFont = labelNeirong.Font;
                                System.Drawing.Point pt = new System.Drawing.Point();
                                pt.X = LastBottomLeftPoint.X;
                                pt.Y = LastBottomLeftPoint.Y;
                                b.BandTopLeftLocation = pt;

                                b.BeginM = beginM;
                                b.EndM   = endM;
                                //b.bandData = new List<Tuple<double, string>>();
                                //for (int j = 0; j < 6; j++)
                                //{
                                //    double m = j * 500;
                                //    string txt = "异常2";
                                //    Tuple<double, string> t = new Tuple<double, string>(m,txt);
                                //    b.bandData.Add(t);
                                //}
                                b.bandData = GetPDFBandData(fieldname);
                                b.Draw();
                                LastBottomLeftPoint.Y += (int)b.BandHight;
                            }
                            // graph.DrawImage(img, rf);
                            graph.AddToPageForeground(page);
                            // Render a page with graphics.
                            //processor.RenderNewPage(PdfPaperSize.Letter, graph);
                            processor.SaveDocument(outFile);
                        }
                    }
                    break;
                }
                pE = pGC.Next();
            }
            #endregion
        }
Exemplo n.º 10
0
        private void DrawBorder(PdfGraphics g, PdfObject obj)
        {
            if (obj.Border == null)
            {
                return;
            }

            // Store the needed properties in local variables for easy access
            var topThickness    = obj.Border.Top;
            var rightThickness  = obj.Border.Right;
            var bottomThickness = obj.Border.Bottom;
            var leftThickness   = obj.Border.Left;
            var x      = obj.Layout.X;
            var y      = obj.Layout.Y;
            var height = obj.Layout.Height;
            var width  = obj.Layout.Width;

            // Create a brush with the right color
            PdfBrush fill = new PdfSolidBrush(new PdfColor(GetColor(obj.Border.Color)));

            /**
            ** The following four if statements work with the following logic:
            ** If the border has a size, figure out the size it should be
            ** The size includes the size of neighboring border. Such that,
            ** if there is a top and right border, the top's width will be
            ** extended so that it goes all the way to the right of the right
            ** border, and the right's height and y position will be adjusted
            ** so that the right border will go to the top of the top border.
            ** This is a little redundant, But it keeps all the logic the same.
            ** Might change it someday.
            ** Then a rectangle is drawn to represent the border
            */

            if (topThickness > 0)
            {
                var bY = (float)(y - topThickness);
                var bX = (float)(x - leftThickness);
                var bW = (float)(width + leftThickness + rightThickness);

                g.DrawRectangle(fill, bX, bY, bW, (float)topThickness);
            }

            if (rightThickness > 0)
            {
                var bX = (float)(x + width);
                var bY = (float)(y - topThickness);
                var bH = (float)(height + topThickness + bottomThickness);

                g.DrawRectangle(fill, bX, bY, (float)rightThickness, bH);
            }

            if (bottomThickness > 0)
            {
                var bY = (float)(y + height);
                var bX = (float)(x - leftThickness);
                var bW = (float)(width + leftThickness + rightThickness);

                g.DrawRectangle(fill, bX, bY, bW, (float)bottomThickness);
            }

            if (leftThickness > 0)
            {
                var bX = (float)(x - leftThickness);
                var bY = (float)(y - topThickness);
                var bH = (float)(height + topThickness + bottomThickness);

                g.DrawRectangle(fill, bX, bY, (float)leftThickness, bH);
            }
        }
Exemplo n.º 11
0
        public async Task <FileStreamResult> GenerateBillPDFAsync(Order order)
        {
            //Creating new PDF document instance
            PdfDocument document = new PdfDocument();

            //Setting margins
            document.PageSettings.Margins.All = 0;

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

            //Creating font instances
            PdfFont headerFont     = new PdfStandardFont(PdfFontFamily.TimesRoman, 35);
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

            //Drawing content onto the PDF
            graphics.DrawRectangle(new PdfSolidBrush(aliceBlue), new Rectangle(0, 0, (int)page.Graphics.ClientSize.Width, (int)page.Graphics.ClientSize.Height));
            graphics.DrawRectangle(new PdfSolidBrush(blue), new Rectangle(0, 0, (int)page.Graphics.ClientSize.Width, 100));
            graphics.DrawString("RicardoLourencoWebStore", headerFont, new PdfSolidBrush(aliceBlue), new PointF(10, 20));

            PdfLayoutResult result = HeaderPoints("To:", 130, page);

            result = HeaderPoints($"Name: {order.User.FullName}", result.Bounds.Bottom + 10, page);
            result = HeaderPoints($"Address: {order.User.Address}", result.Bounds.Bottom + 10, page);

            result = BodyContent("Order info:", result.Bounds.Bottom + 25, page);
            result = BodyContent($"Serial number: {order.Id}", result.Bounds.Bottom + 10, page);
            result = BodyContent("Invoice info:", result.Bounds.Bottom + 45, page);

            Product product;

            foreach (var orderDetail in order.Items)
            {
                product = await _context.Products.FindAsync(orderDetail.ProductId);

                result = BodyContent($"Product name: {orderDetail.Product.Name}", result.Bounds.Bottom + 30, page);
                result = BodyContent($"Quantity: {orderDetail.Quantity}", result.Bounds.Bottom + 10, page);
                result = BodyContent($"Price: {orderDetail.Value}", result.Bounds.Bottom + 10, page);
            }

            graphics.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new PointF(10, graphics.ClientSize.Height - 30));
            PdfTextWebLink linkAnnot = new PdfTextWebLink();

            linkAnnot.Url   = "//www.syncfusion.com";
            linkAnnot.Text  = "www.syncfusion.com";
            linkAnnot.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic);
            linkAnnot.Brush = PdfBrushes.White;
            linkAnnot.DrawTextWebLink(page, new PointF(graphics.ClientSize.Width - 100, graphics.ClientSize.Height - 30));

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

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

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf")
            {
                FileDownloadName = $"Invoice_{order.Id}_{DateTime.UtcNow}.pdf"
            };

            return(fileStreamResult);
        }
Exemplo n.º 12
0
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            total = 0;
            string id = this.OrderIdList.SelectedValue.ToString();
            IEnumerable <CustOrders> products = Orders.GetProducts(id);

            List <CustOrders> list = new List <CustOrders>();

            foreach (CustOrders cust in products)
            {
                list.Add(cust);
            }
            var reducedList = list.Select(f => new { f.ProductID, f.ProductName, f.Quantity, f.UnitPrice, f.Discount, f.Price }).ToList();

            IEnumerable <ShipDetails> shipDetails = Orders.GetShipDetails();
            PdfDocument document = new PdfDocument();

            document.PageSettings.Orientation = PdfPageOrientation.Landscape;
            document.PageSettings.Margins.All = 50;
            PdfPage        page    = document.Pages.Add();
            PdfGraphics    g       = page.Graphics;
            PdfTextElement element = new PdfTextElement("Northwind Traders\n67, rue des Cinquante Otages,\nElgin,\nUnites States.");

            element.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
            element.Brush = new PdfSolidBrush(new PdfColor(89, 89, 93));
            PdfLayoutResult result    = element.Draw(page, new RectangleF(0, 0, page.Graphics.ClientSize.Width / 2, 200));
            Stream          imgStream = typeof(Invoice).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.logo.jpg");

            PdfImage img = new PdfBitmap(imgStream);

            page.Graphics.DrawImage(img, new RectangleF(g.ClientSize.Width - 200, result.Bounds.Y, 190, 45));
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);

            g.DrawRectangle(new PdfSolidBrush(new PdfColor(126, 151, 173)), new RectangleF(0, result.Bounds.Bottom + 40, g.ClientSize.Width, 30));


            element       = new PdfTextElement("INVOICE " + id.ToString(), subHeadingFont);
            element.Brush = PdfBrushes.White;
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 48));
            string currentDate = "DATE " + DateTime.Now.ToString("MM/dd/yyyy");
            SizeF  textSize    = subHeadingFont.MeasureString(currentDate);

            g.DrawString(currentDate, subHeadingFont, element.Brush, new PointF(g.ClientSize.Width - textSize.Width - 10, result.Bounds.Y));

            element       = new PdfTextElement("BILL TO ", new PdfStandardFont(PdfFontFamily.TimesRoman, 10));
            element.Brush = new PdfSolidBrush(new PdfColor(126, 155, 203));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));

            g.DrawLine(new PdfPen(new PdfColor(126, 151, 173), 0.70f), new PointF(0, result.Bounds.Bottom + 3), new PointF(g.ClientSize.Width, result.Bounds.Bottom + 3));

            GetShipDetails(shipDetails);

            element       = new PdfTextElement(shipName, new PdfStandardFont(PdfFontFamily.TimesRoman, 10));
            element.Brush = new PdfSolidBrush(new PdfColor(89, 89, 93));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 5, g.ClientSize.Width / 2, 100));

            element       = new PdfTextElement(string.Format("{0}, {1}, {2}", address, shipCity, shipCountry), new PdfStandardFont(PdfFontFamily.TimesRoman, 10));
            element.Brush = new PdfSolidBrush(new PdfColor(89, 89, 93));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 3, g.ClientSize.Width / 2, 100));

            PdfGrid grid = new PdfGrid();

            grid.DataSource = reducedList;


            PdfGridCellStyle cellStyle = new PdfGridCellStyle();

            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];

            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

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

            for (int i = 0; i < header.Cells.Count; i++)
            {
                if (i == 0 || i == 1)
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }
            header.ApplyStyle(headerStyle);
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
            cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
            cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(131, 130, 136));
            foreach (PdfGridRow row in grid.Rows)
            {
                row.ApplyStyle(cellStyle);
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    PdfGridCell cell = row.Cells[i];
                    if (i == 1)
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else if (i == 0)
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }

                    if (i > 2)
                    {
                        float val = float.MinValue;
                        float.TryParse(cell.Value.ToString(), out val);
                        cell.Value = '$' + val.ToString("0.00");
                    }
                }
            }

            grid.Columns[0].Width = 100;
            grid.Columns[1].Width = 200;

            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            layoutFormat.Layout = PdfLayoutType.Paginate;

            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(g.ClientSize.Width, g.ClientSize.Height - 100)), layoutFormat);
            float pos = 0.0f;

            for (int i = 0; i < grid.Columns.Count - 1; i++)
            {
                pos += grid.Columns[i].Width;
            }

            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f);

            GetTotalPrice(products);

            gridResult.Page.Graphics.DrawString("Total Due", font, new PdfSolidBrush(new PdfColor(126, 151, 173)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 20), new SizeF(grid.Columns[3].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right));
            gridResult.Page.Graphics.DrawString("Thank you for your business!", new PdfStandardFont(PdfFontFamily.TimesRoman, 12), new PdfSolidBrush(new PdfColor(89, 89, 93)), new PointF(pos - 55, gridResult.Bounds.Bottom + 60));
            pos += grid.Columns[4].Width;
            gridResult.Page.Graphics.DrawString('$' + string.Format("{0:N2}", total), font, new PdfSolidBrush(new PdfColor(131, 130, 136)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 20), new SizeF(grid.Columns[4].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right));


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

            document.Close(true);
            Save(stream, "Invoice.pdf");
        }
Exemplo n.º 13
0
        public IActionResult GeneratePDF()
        {
            //Creating new PDF document instance
            PdfDocument document = new PdfDocument();

            //Setting margin
            document.PageSettings.Margins.All = 0;
            //Adding a new page
            PdfPage     page = document.Pages.Add();
            PdfGraphics g    = page.Graphics;
            //Creating font instances
            PdfFont headerFont     = new PdfStandardFont(PdfFontFamily.TimesRoman, 35);
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

            //Drawing content onto the PDF
            g.DrawRectangle(new PdfSolidBrush(gray), new Syncfusion.Drawing.RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));
            g.DrawRectangle(new PdfSolidBrush(black), new Syncfusion.Drawing.RectangleF(0, 0, page.Graphics.ClientSize.Width, 130));
            g.DrawRectangle(new PdfSolidBrush(white), new Syncfusion.Drawing.RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450));
            g.DrawString("Enterprise", headerFont, new PdfSolidBrush(violet), new Syncfusion.Drawing.PointF(10, 20));
            g.DrawRectangle(new PdfSolidBrush(violet), new Syncfusion.Drawing.RectangleF(10, 63, 140, 35));
            g.DrawString("Reporting Solutions", subHeadingFont, new PdfSolidBrush(black), new Syncfusion.Drawing.PointF(15, 70));
            PdfLayoutResult result = HeaderPoints("Develop cloud-ready reporting applications in as little as 20% of the time.", 15, page);

            result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15, page);
            result = HeaderPoints("Microsoft Excel, Word, Adobe PDF, RDL display and editing.", result.Bounds.Bottom + 15, page);
            result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks", result.Bounds.Bottom + 15, page);
            result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45, page);
            result = BodyContent("Our architects and developers have years of reporting experience.", result.Bounds.Bottom + 25, page);
            result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25, page);
            result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25, page);
            result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25, page);
            PdfPen redPen = new PdfPen(PdfBrushes.Red, 2);

            g.DrawLine(redPen, new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 92), new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 145));
            float          headerBulletsXposition = 40;
            PdfTextElement txtElement             = new PdfTextElement("The Experts");

            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200));
            PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2);

            g.DrawLine(violetPen, new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145));
            txtElement      = new PdfTextElement("Accurate Estimates");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            result          = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200));
            txtElement      = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200));
            txtElement      = new PdfTextElement("Given our expertise, you can expect estimates to be accurate.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200));
            PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2);

            g.DrawLine(greenPen, new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 32), new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 85));
            txtElement      = new PdfTextElement("Product Licensing");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200));
            PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2);

            g.DrawLine(bluePen, new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85));
            txtElement      = new PdfTextElement("About Syncfusion");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            result          = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200));
            txtElement      = new PdfTextElement("Solution packages can be combined with product licensing for great cost savings.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200));
            txtElement      = new PdfTextElement("Syncfusion has more than 7,000 customers including large financial institutions and Fortune 100 companies.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200));
            g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new Syncfusion.Drawing.PointF(10, g.ClientSize.Height - 30));
            PdfTextWebLink linkAnnot = new PdfTextWebLink();

            linkAnnot.Url   = "//www.syncfusion.com";
            linkAnnot.Text  = "www.syncfusion.com";
            linkAnnot.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic);
            linkAnnot.Brush = PdfBrushes.White;
            linkAnnot.DrawTextWebLink(page, new Syncfusion.Drawing.PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30));
            //Saving the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            document.Save(ms);
            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;
            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

            fileStreamResult.FileDownloadName = "Sample.pdf";
            return(fileStreamResult);
        }
Exemplo n.º 14
0
        public ActionResult CreateDocument()
        {
            //Creates a new PDF document
            PdfDocument document = new PdfDocument();

            //Adds page settings
            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            //Adds a page to the document
            PdfPage     page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;
            RectangleF  bounds   = new RectangleF();

            if (person.photo != null)
            {
                //Loads the image as stream
                System.Drawing.Image img = System.Drawing.Image.FromFile(@person.photo.ImagePath);
                double perc;
                perc = 200.0 / img.Width;
                float      newHeight   = (float)(img.Height * perc);
                FileStream imageStream = new FileStream(person.photo.ImagePath, FileMode.Open, FileAccess.Read);
                bounds = new RectangleF(250, 0, 200, newHeight);
                PdfImage image = PdfImage.FromStream(imageStream);
                //Draws the image to the PDF page
                page.Graphics.DrawImage(image, bounds);
            }
            PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));

            bounds = new RectangleF(0, bounds.Bottom + 90, graphics.ClientSize.Width, 30);
            //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 element = new PdfTextElement("Personal Information", subHeadingFont);

            element.Brush = PdfBrushes.White;

            //Draws the heading on the page
            PdfLayoutResult result       = element.Draw(page, new PointF(10, bounds.Top + 8));
            string          name         = person.personalInfo.FirstName + " " + person.personalInfo.LastName;
            SizeF           textSize     = subHeadingFont.MeasureString(name);
            PointF          textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y);

            graphics.DrawString(name, subHeadingFont, element.Brush, textPosition);
            PdfFont timesRoman = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);

            //Creates text elements to add the address and draw it to the page.
            element = new PdfTextElement(System.Environment.NewLine
                                         + "Phonenumber: " + person.personalInfo.Phonenumber + System.Environment.NewLine, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
            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);

            element = new PdfTextElement(System.Environment.NewLine
                                         + "Email: " + person.personalInfo.Email + System.Environment.NewLine, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
            linePen       = new PdfPen(new PdfColor(126, 151, 173), 0.70f);
            startPoint    = new PointF(0, result.Bounds.Bottom + 3);
            endPoint      = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3);
            //Draws a line at the bottom of the address
            graphics.DrawLine(linePen, startPoint, endPoint);

            DateTime strDate = new DateTime(person.personalInfo.BirthDay.Year, person.personalInfo.BirthDay.Month, person.personalInfo.BirthDay.Day);

            element = new PdfTextElement(System.Environment.NewLine
                                         + "BirthDay: " + person.personalInfo.BirthDay.ToString("d") + System.Environment.NewLine, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
            linePen       = new PdfPen(new PdfColor(126, 151, 173), 0.70f);
            startPoint    = new PointF(0, result.Bounds.Bottom + 3);
            endPoint      = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3);
            //Draws a line at the bottom of the address
            graphics.DrawLine(linePen, startPoint, endPoint);

            element = new PdfTextElement(System.Environment.NewLine
                                         + "Location: " + person.personalInfo.City + System.Environment.NewLine, timesRoman);
            element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
            linePen       = new PdfPen(new PdfColor(126, 151, 173), 0.70f);
            startPoint    = new PointF(0, result.Bounds.Bottom + 3);
            endPoint      = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3);
            //Draws a line at the bottom of the address
            graphics.DrawLine(linePen, startPoint, endPoint);

            if (!person.personalInfo.Skills.Contains("Enter text here..."))
            {
                element = new PdfTextElement(System.Environment.NewLine
                                             + "Skills: " + person.personalInfo.Skills + System.Environment.NewLine, timesRoman);
                element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0));
                result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
                linePen       = new PdfPen(new PdfColor(126, 151, 173), 0.70f);
                startPoint    = new PointF(0, result.Bounds.Bottom + 3);
                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           Details;
            PdfGrid             grid;
            PdfGridCellStyle    cellStyle;
            PdfGridRow          header;
            PdfGridCellStyle    headerStyle  = new PdfGridCellStyle();
            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();
            PdfGridLayoutResult gridResult;

            if (person.gainedEducation != null && person.gainedEducation.Count > 0)
            {
                //Creates the datasource for the table
                Details = new DataTable();
                Details = CreateDataTable(person.gainedEducation);
                //Creates a PDF grid
                grid = new PdfGrid();
                //Adds the data source
                grid.DataSource = Details;
                //Creates the grid cell styles
                cellStyle             = new PdfGridCellStyle();
                cellStyle.Borders.All = PdfPens.White;
                header = grid.Headers[0];
                //Creates the header style
                headerStyle                 = new PdfGridCellStyle();
                headerStyle.Borders.All     = new PdfPen(new PdfColor(126, 151, 173));
                headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
                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++)
                {
                    if (i == 0 || i == 1)
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }
                }

                //Applies the header style
                header.ApplyStyle(headerStyle);
                cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
                cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
                cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(131, 130, 136));
                //Creates the layout format for grid
                layoutFormat = new PdfGridLayoutFormat();
                // Creates layout format settings to allow the table pagination
                layoutFormat.Layout = PdfLayoutType.Paginate;
                //Draws the grid to the PDF page.
                gridResult = grid.Draw(page, new RectangleF
                                           (new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 50)),
                                       layoutFormat);
                page          = document.Pages.Add();
                element       = new PdfTextElement(" ", subHeadingFont);
                element.Brush = PdfBrushes.White;
                graphics      = page.Graphics;
                result        = element.Draw(page, new PointF(10, 10));
            }
            if (person.Languages != null && person.Languages.Count > 0)
            {
                Details = new DataTable();

                //Creates the datasource for the table
                Details = CreateDataTable(person.Languages);
                //Creates a PDF grid
                grid = new PdfGrid();
                //Adds the data source
                grid.DataSource = Details;
                //Creates the grid cell styles
                cellStyle             = new PdfGridCellStyle();
                cellStyle.Borders.All = PdfPens.White;
                header = grid.Headers[0];
                //Creates the header style
                headerStyle                 = new PdfGridCellStyle();
                headerStyle.Borders.All     = new PdfPen(new PdfColor(126, 151, 173));
                headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
                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++)
                {
                    if (i == 0 || i == 1)
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }
                }

                //Applies the header style
                header.ApplyStyle(headerStyle);
                cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
                cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
                cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(131, 130, 136));
                //Creates the layout format for grid
                layoutFormat = new PdfGridLayoutFormat();
                // Creates layout format settings to allow the table pagination
                layoutFormat.Layout = PdfLayoutType.Paginate;
                //Draws the grid to the PDF page.
                gridResult = grid.Draw(page, new RectangleF
                                           (new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 50)),
                                       layoutFormat);
                page          = document.Pages.Add();
                element       = new PdfTextElement(" ", subHeadingFont);
                element.Brush = PdfBrushes.White;
                graphics      = page.Graphics;
                result        = element.Draw(page, new PointF(10, 10));
            }

            if (person.gainedExperience != null && person.gainedExperience.Count > 0)
            {
                Details = new DataTable();

                //Creates the datasource for the table
                Details = CreateDataTable(person.gainedExperience);
                //Creates a PDF grid
                grid = new PdfGrid();
                //Adds the data source
                grid.DataSource = Details;
                //Creates the grid cell styles
                cellStyle             = new PdfGridCellStyle();
                cellStyle.Borders.All = PdfPens.White;
                header = grid.Headers[0];
                //Creates the header style
                headerStyle                 = new PdfGridCellStyle();
                headerStyle.Borders.All     = new PdfPen(new PdfColor(126, 151, 173));
                headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
                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++)
                {
                    if (i == 0 || i == 1)
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }
                }

                //Applies the header style
                header.ApplyStyle(headerStyle);
                cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
                cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
                cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(131, 130, 136));
                //Creates the layout format for grid
                layoutFormat = new PdfGridLayoutFormat();
                // Creates layout format settings to allow the table pagination
                layoutFormat.Layout = PdfLayoutType.Paginate;
                //Draws the grid to the PDF page.
                gridResult = grid.Draw(page, new RectangleF
                                           (new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 50)),
                                       layoutFormat);
            }



            //FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);
            ////Save and close the PDF document
            //document.Save(fileStream);
            ////document.Close(true);
            MemoryStream stream = new MemoryStream();

            document.Save(stream);

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

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

            fileStreamResult.FileDownloadName = "YourCV.pdf";
            return(fileStreamResult);



            ////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;

            ////Set the standard font
            //PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

            ////Draw the text
            //graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));

            ////Saving the PDF to the MemoryStream
            //MemoryStream stream = new MemoryStream();

            //document.Save(stream);

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

            ////Download the PDF document in the browser.
            //FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
            //fileStreamResult.FileDownloadName = "YourCV.pdf";
            //return fileStreamResult;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates PDF
        /// </summary>
        public async void CreatePDF(IList <InvoiceItem> dataSource, BillingInformation billInfo, double totalDue)
        {
            PdfDocument document = new PdfDocument();

            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            PdfPage        page    = document.Pages.Add();
            PdfGraphics    g       = page.Graphics;
            PdfTextElement element = new PdfTextElement(@"Syncfusion Software 
2501 Aerial Center Parkway 
Suite 200 Morrisville, NC 27560 USA 
Tel +1 888.936.8638 Fax +1 919.573.0306");

            element.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            PdfLayoutResult result = element.Draw(page, new RectangleF(0, 0, page.Graphics.ClientSize.Width / 2, 200));

            Stream imgStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Invoice.Assets.SyncfusionLogo.jpg");

            PdfImage img = PdfImage.FromStream(imgStream);

            page.Graphics.DrawImage(img, new RectangleF(g.ClientSize.Width - 200, result.Bounds.Y, 190, 45));
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);

            g.DrawRectangle(new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(0, result.Bounds.Bottom + 40, g.ClientSize.Width, 30));
            element       = new PdfTextElement("INVOICE " + billInfo.InvoiceNumber.ToString(), subHeadingFont);
            element.Brush = PdfBrushes.White;
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 48));
            string currentDate = "DATE " + billInfo.Date.ToString("d");
            SizeF  textSize    = subHeadingFont.MeasureString(currentDate);

            g.DrawString(currentDate, subHeadingFont, element.Brush, new PointF(g.ClientSize.Width - textSize.Width - 10, result.Bounds.Y));

            element       = new PdfTextElement("BILL TO ", new PdfStandardFont(PdfFontFamily.TimesRoman, 12));
            element.Brush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));

            g.DrawLine(new PdfPen(new PdfColor(34, 83, 142), 0.70f), new PointF(0, result.Bounds.Bottom + 3), new PointF(g.ClientSize.Width, result.Bounds.Bottom + 3));

            element       = new PdfTextElement(billInfo.Name, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 5, g.ClientSize.Width / 2, 100));

            element       = new PdfTextElement(billInfo.Address, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 3, g.ClientSize.Width / 2, 100));
            string[] headers = new string[] { "Item", "Quantity", "Rate", "Taxes", "Amount" };
            PdfGrid  grid    = new PdfGrid();

            grid.Columns.Add(headers.Length);
            //Adding headers in to the grid
            grid.Headers.Add(1);
            PdfGridRow headerRow = grid.Headers[0];
            int        count     = 0;

            foreach (string columnName in headers)
            {
                headerRow.Cells[count].Value = columnName;
                count++;
            }
            //Adding rows into the grid
            foreach (var item in dataSource)
            {
                PdfGridRow row = grid.Rows.Add();
                row.Cells[0].Value = item.ItemName;
                row.Cells[1].Value = item.Quantity.ToString();
                row.Cells[2].Value = "$" + item.Rate.ToString("#,###.00", CultureInfo.InvariantCulture);
                row.Cells[3].Value = "$" + item.Taxes.ToString("#,###.00", CultureInfo.InvariantCulture);
                row.Cells[4].Value = "$" + item.TotalAmount.ToString("#,###.00", CultureInfo.InvariantCulture);
            }

            PdfGridCellStyle cellStyle = new PdfGridCellStyle();

            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];

            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

            headerStyle.Borders.All     = new PdfPen(new PdfColor(34, 83, 142));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            headerStyle.TextBrush       = PdfBrushes.White;
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            for (int i = 0; i < header.Cells.Count; i++)
            {
                if (i == 0)
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }

            header.Cells[0].Value = "ITEM";
            header.Cells[1].Value = "QUANTITY";
            header.Cells[2].Value = "RATE";
            header.Cells[3].Value = "TAXES";
            header.Cells[4].Value = "AMOUNT";
            header.ApplyStyle(headerStyle);
            grid.Columns[0].Width    = 180;
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(34, 83, 142), 0.70f);
            cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f);
            cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(0, 0, 0));
            foreach (PdfGridRow row in grid.Rows)
            {
                row.ApplyStyle(cellStyle);
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    PdfGridCell cell = row.Cells[i];
                    if (i == 0)
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }

                    if (i > 1)
                    {
                        if (cell.Value.ToString().Contains("$"))
                        {
                            cell.Value = cell.Value.ToString();
                        }
                        else
                        {
                            if (cell.Value is double)
                            {
                                cell.Value = "$" + ((double)cell.Value).ToString("#,###.00", CultureInfo.InvariantCulture);
                            }
                            else
                            {
                                cell.Value = "$" + cell.Value.ToString();
                            }
                        }
                    }
                }
            }

            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            layoutFormat.Layout = PdfLayoutType.Paginate;

            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(g.ClientSize.Width, g.ClientSize.Height - 100)), layoutFormat);
            float pos = 0.0f;

            for (int i = 0; i < grid.Columns.Count - 1; i++)
            {
                pos += grid.Columns[i].Width;
            }

            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);

            gridResult.Page.Graphics.DrawString("TOTAL DUE", font, new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 10), new SizeF(grid.Columns[3].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right));
            gridResult.Page.Graphics.DrawString("Thank you for your business!", new PdfStandardFont(PdfFontFamily.TimesRoman, 12), new PdfSolidBrush(new PdfColor(0, 0, 0)), new PointF(pos - 210, gridResult.Bounds.Bottom + 60));
            pos += grid.Columns[4].Width;
            gridResult.Page.Graphics.DrawString("$" + totalDue.ToString("#,###.00", CultureInfo.InvariantCulture), font, new PdfSolidBrush(new PdfColor(0, 0, 0)), new RectangleF(pos, gridResult.Bounds.Bottom + 10, grid.Columns[4].Width - pos, 20), new PdfStringFormat(PdfTextAlignment.Right));
            StorageFile stFile = null;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.DefaultFileExtension = ".pdf";
                savePicker.SuggestedFileName    = "Invoice";
                savePicker.FileTypeChoices.Add("Adobe PDF Document", new List <string>()
                {
                    ".pdf"
                });
                stFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                stFile = await local.CreateFileAsync("Invoice.pdf", CreationCollisionOption.ReplaceExisting);
            }

            if (stFile != null)
            {
                Stream stream = await stFile.OpenStreamForWriteAsync();

                await document.SaveAsync(stream);

                stream.Flush();
                stream.Dispose();
                document.Close(true);

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(stFile);
                }
            }
        }
Exemplo n.º 16
0
        internal static PdfDocument Generate()
        {
            PdfDocument document = new PdfDocument();

            document.PageSettings.Size    = new SizeF((float)Helper.MM2PX(80), (float)Helper.MM2PX(200));
            document.PageSettings.Margins = new PdfMargins {
                All = 0
            };

            //Add a page to the document.

            PdfPage page = document.Pages.Add();

            //Create PDF graphics for the page.

            PdfGraphics graphics = page.Graphics;

            // Logo

            PdfImage image = new PdfBitmap("Logo.png");

            float PageWidth  = (float)Helper.MM2PX(60);
            float PageHeight = (float)Helper.MM2PX(30);
            float myWidth    = image.Width;
            float myHeight   = image.Height;

            float shrinkFactor;

            if (myWidth > PageWidth)
            {
                shrinkFactor = myWidth / PageWidth;
                myWidth      = PageWidth;
                myHeight     = myHeight / shrinkFactor;
            }

            if (myHeight > PageHeight)
            {
                shrinkFactor = myHeight / PageHeight;
                myHeight     = PageHeight;
                myWidth      = myWidth / shrinkFactor;
            }

            float XPosition = ((float)Helper.MM2PX(80) - myWidth) / 2;
            float YPosition = ((float)Helper.MM2PX(40) - myHeight) / 2;

            graphics.DrawImage(image, XPosition, YPosition, myWidth, myHeight);

            // Titulo.
            graphics.DrawRectangle(
                new PdfPen(new PdfColor(0, 0, 0), 0.5F),
                new RectangleF((float)Helper.MM2PX(10), (float)Helper.MM2PX(40), (float)Helper.MM2PX(60), (float)Helper.MM2PX(12)));
            graphics.DrawRectangle(
                new PdfPen(new PdfColor(0, 0, 0), 0.5F),
                new RectangleF((float)Helper.MM2PX(11), (float)Helper.MM2PX(41), (float)Helper.MM2PX(58), (float)Helper.MM2PX(10)));
            graphics.DrawString(
                "WIFI Free",
                new PdfTrueTypeFont("Ubuntu-Regular.ttf", 21),
                PdfBrushes.Black,
                new RectangleF((float)Helper.MM2PX(11), (float)Helper.MM2PX(41), (float)Helper.MM2PX(58), (float)Helper.MM2PX(10)),
                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

            // Habitacion
            graphics.DrawRectangle(
                PdfBrushes.Black,
                new RectangleF((float)Helper.MM2PX(10), (float)Helper.MM2PX(55), (float)Helper.MM2PX(60), (float)Helper.MM2PX(5)));
            graphics.DrawString("SANTO DOMINGO",
                                new PdfTrueTypeFont("Ubuntu-Regular.ttf", 11),
                                PdfBrushes.White,
                                new RectangleF((float)Helper.MM2PX(10), (float)Helper.MM2PX(55), (float)Helper.MM2PX(60), (float)Helper.MM2PX(5)),
                                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

            // Instrucciones
            graphics.DrawString(
                "INSTRUCCIONES E INFORMACION PARA CONECTARSE A LA RED GRATUITA.",
                new PdfTrueTypeFont("Ubuntu-Regular.ttf", 11),
                PdfBrushes.Black,
                new RectangleF((float)Helper.MM2PX(10), (float)Helper.MM2PX(62), (float)Helper.MM2PX(60), (float)Helper.MM2PX(14)),
                new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Top));


            graphics.DrawString(
                "1 - Conectarse a la red WIFI “El Descubrimiento”\n" +
                "2 - Se debería abrir una página web en donde se solicitarán los siguientes datos.\n" +
                "\n" +
                $"LOGIN: 12345678\n" +
                $"CONTRASEÑA: 12345678\n" +
                "\n" +
                "3 - En caso de no abrirse dicha página web, abra en un navegador http://192.168.88.1 e ingrese los datos proporcionados anteriormente.\n" +
                "4 - Para desconectarse de la red WIFI debe primero ingresar en http://192.168.88.1/logout.html y luego desconectarse de la red WIFI “El Descubrimiento”.\n" +
                "\n" +
                "Éste usuario es brindado de forma gratuita, y cuenta con conexión para 2 dispositivos simultaneamente.\n" +
                "\n" +
                "Para contratar nuestro servicio de WIFI PLUS  sirvase pasar por RECEPCIÓN",
                new PdfTrueTypeFont("Ubuntu-Regular.ttf", 10),
                PdfBrushes.Black,
                new RectangleF((float)Helper.MM2PX(10), (float)Helper.MM2PX(80), (float)Helper.MM2PX(60), (float)Helper.MM2PX(114)),
                new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Top));

            return(document);
        }
        public ActionResult DrawingShapes(string InsideBrowser)
        {
            // Create a new PDF document.
            PdfDocument doc = new PdfDocument();
            int         i;
            // Create a new page.
            PdfPage page = doc.Pages.Add();
            // Obtain PdfGraphics object.
            PdfGraphics g    = page.Graphics;
            PdfFont     font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);

            #region Polygon
            PdfPen pen = new PdfPen(Color.Black);
            pen.Width = 3;
            PointF p1 = new PointF(05, 10);
            PointF p2 = new PointF(05, 10);
            PointF p3 = new PointF(60, 70);
            PointF p4 = new PointF(40, 70);

            PointF[] points = { p1, p2, p3, p4 };

            int pointNum = 16;
            points = new PointF[pointNum];
            double       f      = 360.0 / pointNum * Math.PI / 180.0;
            const double r      = 100;
            PointF       center = new PointF(140, 140);

            for (i = 0; i < pointNum; ++i)
            {
                PointF p     = new PointF();
                double theta = i * f;

                p.Y = (float)(Math.Sin(theta) * r + center.Y);
                p.X = (float)(Math.Cos(theta) * r + center.X);

                points[i] = p;
            }

            PdfSolidBrush brush = new PdfSolidBrush(Color.Green);
            pen.Color    = Color.Brown;
            pen.Width    = 10;
            pen.LineJoin = PdfLineJoin.Round;
            g.DrawString("Polygon", font, PdfBrushes.DarkBlue, new PointF(50, 0));
            g.DrawPolygon(pen, brush, points);

            #endregion

            #region  Pie

            RectangleF rect = new RectangleF(200, 50, 200, 200);
            brush.Color = Color.Green;
            pen.Color   = Color.Brown;
            pen.Width   = 10;

            rect.Location = new PointF(20, 280);
            pen.LineJoin  = PdfLineJoin.Round;
            g.DrawString("Pie shape", font, PdfBrushes.DarkBlue, new PointF(50, 250));
            g.DrawPie(pen, brush, rect, 180, 60);
            g.DrawPie(pen, brush, rect, 360 - 60, 60);
            g.DrawPie(pen, brush, rect, 60, 60);

            #endregion

            #region Arc

            g.DrawString("Arcs", font, PdfBrushes.DarkBlue, new PointF(330, 0));
            pen         = new PdfPen(Color.Black);
            pen.Width   = 11;
            pen.LineCap = PdfLineCap.Round;
            pen.Color   = Color.Brown;
            rect        = new RectangleF(310, 40, 200, 200);
            g.DrawArc(pen, rect, 0, 90);

            pen.Color = Color.DarkGreen;
            rect.X   -= 10;
            g.DrawArc(pen, rect, 90, 90);

            pen.Color = Color.Brown;
            rect.Y   -= 10;
            g.DrawArc(pen, rect, 180, 90);

            pen.Color = Color.DarkGreen;
            rect.X   += 10;
            g.DrawArc(pen, rect, 270, 90);

            #endregion

            #region Rectangle
            rect        = new RectangleF(310, 280, 200, 100);
            brush.Color = Color.Green;
            pen.Color   = Color.Brown;
            g.DrawString("Simple Rectangle", font, PdfBrushes.DarkBlue, new PointF(310, 255));
            g.DrawRectangle(pen, brush, rect);
            #endregion

            #region ellipse
            pen  = new PdfPen(Color.Black);
            rect = new RectangleF(270, 400, 160, 1000);
            g.DrawString("Shape with pagination", font, PdfBrushes.DarkBlue, new PointF(300, 390));
            PdfEllipse      ellipse = new PdfEllipse(rect);
            PdfLayoutFormat format  = new PdfLayoutFormat();
            format.Break  = PdfLayoutBreakType.FitPage;
            format.Layout = PdfLayoutType.Paginate;
            ellipse.Brush = PdfBrushes.Brown;
            ellipse.Draw(page, 20, 20, format);

            brush         = new PdfSolidBrush(Color.Black);
            ellipse.Brush = PdfBrushes.DarkGreen;
            ellipse.Draw(page, 40, 40, format);

            #endregion

            #region Transaparency

            page = doc.Pages[1];
            g    = page.Graphics;
            g.DrawString("Transparent Rectangles", font, PdfBrushes.DarkBlue, new PointF(50, 80));
            PdfBrush gBrush;
            rect = new RectangleF(10, 150, 100, 100);

            pen    = new PdfPen(Color.Black);
            gBrush = new PdfSolidBrush(Color.DarkGreen);

            g.DrawRectangle(pen, gBrush, rect);
            gBrush  = new PdfSolidBrush(Color.Brown);
            rect.X += 20;
            rect.Y += 20;
            pen     = new PdfPen(Color.Brown);
            g.SetTransparency(0.7f);
            g.DrawRectangle(pen, gBrush, rect);

            rect.X += 20;
            rect.Y += 20;
            gBrush  = new PdfLinearGradientBrush(rect, Color.DarkGreen, Color.Brown, PdfLinearGradientMode.BackwardDiagonal);
            g.SetTransparency(0.5f);
            g.DrawRectangle(pen, gBrush, rect);

            rect.X += 20;
            rect.Y += 20;
            pen     = new PdfPen(Color.Blue);
            gBrush  = new PdfSolidBrush(Color.Gray);
            g.SetTransparency(0.25f);
            g.DrawRectangle(pen, gBrush, rect);

            rect.X += 20;
            rect.Y += 20;
            pen     = new PdfPen(Color.Black);
            gBrush  = new PdfSolidBrush(Color.Green);
            g.SetTransparency(0.1f);
            g.DrawRectangle(pen, gBrush, rect);

            #endregion

            #region Rectangle with Color space



            PointF location = new PointF(10, 50);
            page = doc.Pages.Add();
            g    = page.Graphics;

            doc.ColorSpace = (PdfColorSpace)i;

            // SolidBrush
            gBrush = new PdfSolidBrush(Color.Red);
            DrawRectangles(location, g, font, gBrush, pen, doc);

            // LinearGradient
            location = new PointF(180, 50);

            PointF point2 = location;

            point2.X += 180;
            gBrush    = new PdfLinearGradientBrush(location, point2, Color.Blue, Color.Red);
            DrawRectangles(location, g, font, gBrush, pen, doc);

            // Raidal Gradient
            location = new PointF(360, 50);
            point2   = location;

            point2 = new PointF(location.X + 50, location.Y + 50);
            //point2.Y += 250;
            //point2.X = 150;
            gBrush = new PdfRadialGradientBrush(point2, 0, point2, 100, Color.Blue, Color.Red);
            (gBrush as PdfRadialGradientBrush).Extend = PdfExtend.Both;
            DrawRectangles(location, g, font, gBrush, pen, doc);

            g.DrawString("Rectangle with color spaces", font, PdfBrushes.DarkBlue, new PointF(150, 0));
            #endregion

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            doc.Save(ms);

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

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

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
            fileStreamResult.FileDownloadName = "Shapes.pdf";
            return(fileStreamResult);
        }
Exemplo n.º 18
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.digital_signature_template.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);
            //Get the .pfx certificate file stream.
            Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.certificate.pfx");
            //Get the signature field to add digital signature.
            PdfLoadedSignatureField signatureField = loadedDocument.Form.Fields[6] as PdfLoadedSignatureField;
            //Get the signature bounds.
            RectangleF bounds = signatureField.Bounds;

            //Create PDF certificate using certificate stream and password.
            PdfCertificate pdfCertificate = new PdfCertificate(certificateStream, "password123");

            //Add certificate to first page of the document.
            PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCertificate, "", signatureField);

            signature.ContactInfo  = "*****@*****.**";
            signature.LocationInfo = "Honolulu, Hawaii";
            signature.Reason       = "I am author of this document.";

            //Set the cryptographic standard to signature settings.
            if ((bool)cms.IsChecked)
            {
                signature.Settings.CryptographicStandard = CryptographicStandard.CMS;
            }
            else
            {
                signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
            }

            //Set the digest algorithm to signature settings.
            if ((bool)sha1.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA1;
            }
            else if ((bool)sha256.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA256;
            }
            else if ((bool)sha384.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA384;
            }
            else if ((bool)sha512.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;
            }

            //Get the signature field appearance graphics.
            PdfGraphics graphics = signature.Appearance.Normal.Graphics;

            if (graphics != null)
            {
                //Draw the rectangle in appearance graphics.
                graphics.DrawRectangle(PdfPens.Black, bounds);

                //Get the image file stream from assembly.
                Stream imageStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.signature.png");
                //Create the PDF bitmap image from stream.
                PdfBitmap bitmap = new PdfBitmap(imageStream, true);
                //Draw image to appearance graphics.
                graphics.DrawImage(bitmap, new RectangleF(2, 1, 30, 30));

                //Get certificate subject name.
                string subject = pdfCertificate.SubjectName;

                //Create a new font instance and draw a text to appearance graphics.
                PdfFont         font     = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
                RectangleF      textRect = new RectangleF(45, 0, bounds.Width - 45, bounds.Height);
                PdfStringFormat format   = new PdfStringFormat(PdfTextAlignment.Justify);
                graphics.DrawString("Digitally signed by " + subject + " \r\nReason: Testing signature \r\nLocation: USA", font, PdfBrushes.Black, textRect, format);
            }

            //Set the digital signature to signing the field.
            signatureField.Signature = signature;

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

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("DigitalSignature.pdf", stream);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Creates PDF
        /// </summary>
        public void CreatePDF(IList <InvoiceItem> dataSource, BillingInformation billInfo, double totalDue)
        {
            PdfDocument document = new PdfDocument();

            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            PdfPage        page    = document.Pages.Add();
            PdfGraphics    g       = page.Graphics;
            PdfTextElement element = new PdfTextElement(@"Syncfusion Software 
2501 Aerial Center Parkway 
Suite 200 Morrisville, NC 27560 USA 
Tel +1 888.936.8638 Fax +1 919.573.0306");

            element.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            PdfLayoutResult result    = element.Draw(page, new RectangleF(0, 0, page.Graphics.ClientSize.Width / 2, 200));
            Assembly        assembly  = typeof(MainPage).Assembly;
            Stream          imgStream = assembly.GetManifestResourceStream("Invoice.Assets.SyncfusionLogo.jpg");
            PdfImage        img       = PdfImage.FromStream(imgStream);

            page.Graphics.DrawImage(img, new RectangleF(g.ClientSize.Width - 200, result.Bounds.Y, 190, 45));
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);

            g.DrawRectangle(new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(0, result.Bounds.Bottom + 40, g.ClientSize.Width, 30));
            element       = new PdfTextElement("INVOICE " + billInfo.InvoiceNumber.ToString(), subHeadingFont);
            element.Brush = PdfBrushes.White;
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 48));
            string currentDate = "DATE " + billInfo.Date.ToString("d");
            SizeF  textSize    = subHeadingFont.MeasureString(currentDate);

            g.DrawString(currentDate, subHeadingFont, element.Brush, new PointF(g.ClientSize.Width - textSize.Width - 10, result.Bounds.Y));

            element       = new PdfTextElement("BILL TO ", new PdfStandardFont(PdfFontFamily.TimesRoman, 12));
            element.Brush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));

            g.DrawLine(new PdfPen(new PdfColor(34, 83, 142), 0.70f), new PointF(0, result.Bounds.Bottom + 3), new PointF(g.ClientSize.Width, result.Bounds.Bottom + 3));

            element       = new PdfTextElement(billInfo.Name, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 5, g.ClientSize.Width / 2, 100));

            element       = new PdfTextElement(billInfo.Address, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 3, g.ClientSize.Width / 2, 100));

            PdfGrid grid = new PdfGrid();

            grid.DataSource = ConvertToDataTable(dataSource);
            PdfGridCellStyle cellStyle = new PdfGridCellStyle();

            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];

            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

            headerStyle.Borders.All     = new PdfPen(new PdfColor(34, 83, 142));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            headerStyle.TextBrush       = PdfBrushes.White;
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            for (int i = 0; i < header.Cells.Count; i++)
            {
                if (i == 0)
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }
            header.Cells[0].Value = "ITEM";
            header.Cells[1].Value = "QUANTITY";
            header.Cells[2].Value = "RATE";
            header.Cells[3].Value = "TAXES";
            header.Cells[4].Value = "AMOUNT";
            header.ApplyStyle(headerStyle);
            grid.Columns[0].Width    = 180;
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(34, 83, 142), 0.70f);
            cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f);
            cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(0, 0, 0));
            foreach (PdfGridRow row in grid.Rows)
            {
                row.ApplyStyle(cellStyle);
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    PdfGridCell cell = row.Cells[i];
                    if (i == 0)
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }

                    if (i > 1)
                    {
                        if (cell.Value.ToString().Contains("$"))
                        {
                            cell.Value = cell.Value.ToString();
                        }
                        else
                        {
                            if (cell.Value is double)
                            {
                                cell.Value = "$" + ((double)cell.Value).ToString("#,###.00", CultureInfo.InvariantCulture);
                            }
                            else
                            {
                                cell.Value = "$" + cell.Value.ToString();
                            }
                        }
                    }
                }
            }

            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            layoutFormat.Layout = PdfLayoutType.Paginate;

            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(g.ClientSize.Width, g.ClientSize.Height - 100)), layoutFormat);
            float pos = 0.0f;

            for (int i = 0; i < grid.Columns.Count - 1; i++)
            {
                pos += grid.Columns[i].Width;
            }

            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);

            gridResult.Page.Graphics.DrawString("TOTAL DUE", font, new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 10), new SizeF(grid.Columns[3].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right));
            gridResult.Page.Graphics.DrawString("Thank you for your business!", new PdfStandardFont(PdfFontFamily.TimesRoman, 12), new PdfSolidBrush(new PdfColor(0, 0, 0)), new PointF(pos - 210, gridResult.Bounds.Bottom + 60));
            pos += grid.Columns[4].Width;
            gridResult.Page.Graphics.DrawString("$" + totalDue.ToString("#,###.00", CultureInfo.InvariantCulture), font, new PdfSolidBrush(new PdfColor(0, 0, 0)), new RectangleF(pos, gridResult.Bounds.Bottom + 10, grid.Columns[4].Width - pos, 20), new PdfStringFormat(PdfTextAlignment.Right));

            document.Save("Invoice.pdf");
            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
                System.Diagnostics.Process.Start("Invoice.pdf");
                //this.Close();
            }
            //else
            // Exit
            //this.Close();

            document.Close(true);
        }
Exemplo n.º 20
0
        public bool CreatePDF(Movimientos movimientos, DataTable tablacarrito, Model.Usuario User)
        {
            try
            {
                PdfDocument document = new PdfDocument();
                //Adds page settings
                document.PageSettings.Orientation = PdfPageOrientation.Portrait;
                document.PageSettings.Margins.All = 50;
                //Adds a page to the document
                PdfPage page = document.Pages.Add();

                PdfGraphics graphics = page.Graphics;

                //Loads the image from disk
                //PdfImage image = PdfImage.FromFile("Logo.png");

                Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("Inventario2.Assets.NewLogo.jpeg");
                //Load the image from the disk.
                PdfBitmap image = new PdfBitmap(imageStream);
                //Draw the image
                RectangleF bounds = new RectangleF(0, 0, 110, 110);
                //Draws the image to the PDF page
                page.Graphics.DrawImage(image, bounds);


                //DRAW THE MAIN TITLE
                PdfFont Headfont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
                //Creates a text element to add the invoice number
                PdfTextElement headelement = new PdfTextElement("AUDIO VIDEO STUDIOS ", Headfont);
                headelement.Brush = PdfBrushes.Red;
                PdfLayoutResult result = headelement.Draw(page, new PointF(graphics.ClientSize.Width - 350, graphics.ClientSize.Height - 740));


                PdfFont Subtitle = new PdfStandardFont(PdfFontFamily.Helvetica, 14);
                //Creates a text element to add the invoice number
                PdfTextElement subtitelement = new PdfTextElement("ORDEN DE SALIDA ", Subtitle);
                subtitelement.Brush = PdfBrushes.Red;
                PdfLayoutResult Subresult = subtitelement.Draw(page, new PointF(graphics.ClientSize.Width - 300, graphics.ClientSize.Height - 710));


                PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(222, 237, 242));
                bounds = new RectangleF(bounds.Right, Subresult.Bounds.Bottom, graphics.ClientSize.Width - 300, 50);
                //Draws a rectangle to place the heading in that region.
                graphics.DrawRectangle(solidBrush, bounds);

                //creating fields, folio, fecha, lugar
                PdfFont        campofont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement lblugar   = new PdfTextElement("EVENTO: ", campofont);
                lblugar.Brush = PdfBrushes.Black;
                PdfLayoutResult reslblugar = lblugar.Draw(page, new PointF(bounds.Left + 40, bounds.Top));

                PdfTextElement lbfecha = new PdfTextElement("FECHA: ", campofont);
                lbfecha.Brush = PdfBrushes.Black;
                PdfLayoutResult reslbfecha = lbfecha.Draw(page, new PointF(bounds.Left + 40, bounds.Top + 16));

                PdfTextElement lbfolio = new PdfTextElement("FOLIO: ", campofont);
                lbfolio.Brush = PdfBrushes.Black;
                PdfLayoutResult reslbfolio = lbfolio.Draw(page, new PointF(bounds.Left + 40, bounds.Top + 32));


                PdfBrush solidBrush2 = new PdfSolidBrush(new PdfColor(190, 220, 228));
                bounds = new RectangleF(bounds.Right, Subresult.Bounds.Bottom, graphics.ClientSize.Width - 300, 50);
                //Draws a rectangle to place the heading in that region.
                graphics.DrawRectangle(solidBrush2, bounds);


                //variables de campos
                PdfTextElement lugar = new PdfTextElement(movimientos.lugar, campofont);
                lugar.Brush = PdfBrushes.Black;
                PdfLayoutResult reslugar = lugar.Draw(page, new PointF(bounds.Left + 40, bounds.Top));

                PdfTextElement fecha = new PdfTextElement(DateTime.Now.ToString(), campofont);
                fecha.Brush = PdfBrushes.Black;
                PdfLayoutResult resfecha = fecha.Draw(page, new PointF(bounds.Left + 40, bounds.Top + 16));

                PdfTextElement folio = new PdfTextElement(movimientos.ID, campofont);
                folio.Brush = PdfBrushes.Black;
                PdfLayoutResult resfolio = folio.Draw(page, new PointF(bounds.Left + 40, bounds.Top + 32));

                //create table

                //Creates the datasource for the table
                DataTable invoiceDetails = tablacarrito;
                //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, 151, 173));
                headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
                headerStyle.TextBrush       = PdfBrushes.White;
                headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 16f, PdfFontStyle.Regular);

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

                //Applies the header style
                header.ApplyStyle(headerStyle);
                cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
                cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 10f);
                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 + 150), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 100)), layoutFormat);

                PdfGraphics graphicsSecond = gridResult.Page.Graphics;

                PdfPen linePen    = new PdfPen(new PdfColor(126, 151, 173), 1.0f);
                PointF startPoint = new PointF(0, gridResult.Bounds.Bottom + 60);
                PointF endPoint   = new PointF(150, gridResult.Bounds.Bottom + 60);
                //Draws a line at the bottom of the address
                graphicsSecond.DrawLine(linePen, startPoint, endPoint);


                PdfFont        entregafont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement lbentrega   = new PdfTextElement("ENTREGA: ", entregafont);
                lbentrega.Brush = PdfBrushes.Black;
                PdfLayoutResult reslbentrega = lbentrega.Draw(gridResult.Page, new PointF(linePen.Width / 2.0f, startPoint.Y + 5));

                //texto de quien entrega
                PdfFont        usuarioentregafont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement lbusuarioentrega   = new PdfTextElement(Model.User.nombre + " " + Model.User.apellido_paterno, usuarioentregafont);
                lbusuarioentrega.Brush = PdfBrushes.Black;
                PdfLayoutResult reslbusuarioentrega = lbusuarioentrega.Draw(gridResult.Page, new PointF(linePen.Width / 2.0f, startPoint.Y - 20));


                PdfPen linePenfinal    = new PdfPen(new PdfColor(126, 151, 173), 1.0f);
                PointF startPointfinal = new PointF(350, gridResult.Bounds.Bottom + 60);
                PointF endPointfinal   = new PointF(graphics.ClientSize.Width, gridResult.Bounds.Bottom + 60);
                //Draws a line at the bottom of the address
                graphicsSecond.DrawLine(linePenfinal, startPointfinal, endPointfinal);

                PdfFont        recibefont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement lbrecibe   = new PdfTextElement("RECIBE: ", recibefont);
                lbrecibe.Brush = PdfBrushes.Black;
                PdfLayoutResult reslbrecibe = lbrecibe.Draw(gridResult.Page, new PointF(350.0f + (linePenfinal.Width / 2.0f), startPoint.Y + 5));

                //texto de quien recibe
                PdfFont        usuariofont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
                PdfTextElement lbusuario   = new PdfTextElement(User.nombre + " " + User.apellido_paterno, usuariofont);
                lbusuario.Brush = PdfBrushes.Black;
                PdfLayoutResult reslbusuario = lbusuario.Draw(gridResult.Page, new PointF(350.0f + (linePenfinal.Width / 2.0f), startPoint.Y - 20));


                MemoryStream stream = new MemoryStream();

                //Save the document.
                document.Save(stream);
                streamPDF = stream;
                //Close the document.
                document.Close(true);

                byte[] bytes = stream.ToArray();


                bool   res  = SendSTMPT(bytes, correo);
                string save = "OrdenDeSalida-" + movimientos.ID;
                //Save the stream as a file in the device and invoke it for viewing
                // Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView(save + ".pdf", "application/pdf", stream);
                //The operation in Save under Xamarin varies between Windows Phone, Android and iOS platforms. Please refer PDF/Xamarin section for respective code samples.

                if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                {
                    // Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Output.pdf", "application/pdf", stream);
                    Xamarin.Forms.DependencyService.Get <ISave>().SaveAndView(save + ".pdf", "application/pdf", stream);
                }
                else
                {
                    Xamarin.Forms.DependencyService.Get <ISave>().SaveAndView(save + ".pdf", "application/pdf", stream);
                }


                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public async Task <IActionResult> CreateDocument()
        {
            string user        = User.FindFirst("Index").Value;
            var    Currentuser = await _taskRepository.GetCurrentUser(user);

            ViewBag.photo = Currentuser.PhotoURL;
            //Creates a new PDF document
            PdfDocument document = new PdfDocument();

            //Adds page settings
            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            //Adds a page to the document
            PdfPage     page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;
            //Loads the image as stream
            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 24);

            graphics.DrawString("Daily Time Sheet  -  ", font, PdfBrushes.Blue, new PointF(170, 30));
            string  Date        = DateTime.Now.ToString("MM/dd/yyyy");
            PdfFont font4       = new PdfStandardFont(PdfFontFamily.Helvetica, 18);
            string  currentDate = "DATE " + DateTime.Now.ToString("MM/dd/yyyy");

            graphics.DrawString(Date, font4, PdfBrushes.Blue, new PointF(370, 33));

            PdfFont font2 = new PdfStandardFont(PdfFontFamily.Helvetica, 16);

            graphics.DrawString("Ishara Maduhansi", font2, PdfBrushes.Black, new PointF(190, 70));

            PdfFont font3 = new PdfStandardFont(PdfFontFamily.Helvetica, 13);

            graphics.DrawString("Software Engineer", font3, PdfBrushes.Black, new PointF(190, 95));

            FileStream imageStream = new FileStream("wwwroot/images/bell.jpg", FileMode.Open, FileAccess.Read);
            RectangleF bounds      = new RectangleF(10, 0, 150, 150);
            PdfImage   image       = PdfImage.FromStream(imageStream);

            //Draws the image to the PDF page
            page.Graphics.DrawImage(image, bounds);
            PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));

            bounds = new RectangleF(0, 160, graphics.ClientSize.Width, 30);
            //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 element = new PdfTextElement("Time Sheet ", subHeadingFont);

            element.Brush = PdfBrushes.White;

            //Draws the heading on the page
            PdfLayoutResult result = element.Draw(page, new PointF(10, 165));
            //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, 165);

            //Draws the date by using DrawString method
            graphics.DrawString(currentDate, subHeadingFont, element.Brush, textPosition);

            //Creates text elements to add the address and draw it to the page.
            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);
            //Creates the datasource for the table
            // Creates a PDF grid
            // Creates the grid cell styles
            //Create a PdfGrid.
            PdfGrid pdfGrid = new PdfGrid();
            //Add values to list

            List <object> data = new List <object>();

            object[] ary  = new object[2];
            Object   row1 = new { task = "Login", Start_Date = Date, End_Date = Date, Effort = "2 h 40 Min" };
            Object   row2 = new { task = "Time Sheet", Start_Date = Date, End_Date = Date, Effort = "3 h " };
            Object   row3 = new { task = "Employee", Start_Date = Date, End_Date = Date, Effort = "2 h 40 Min" };
            Object   row4 = new { task = "Leave Part", Start_Date = Date, End_Date = Date, Effort = "4 h 20 Min" };
            Object   row5 = new { task = "Attendence Part", Start_Date = Date, End_Date = Date, Effort = "1 h 40 Min" };

            data.Add(row1);
            data.Add(row2);
            data.Add(row3);
            data.Add(row4);
            data.Add(row5);
            //Add list to IEnumerable
            IEnumerable <object> dataTable = data;

            //Assign data source.
            pdfGrid.DataSource = dataTable;
            //Draw grid to the page of PDF document.
            pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(10, 230));

            MemoryStream stream = new MemoryStream();

            document.Save(stream);
            //If the position is not set to '0' then the PDF will be empty.
            stream.Position = 0;
            //Close the document.
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

            //Creates a FileContentResult object by using the file contents, content type, and file name.
            return(fileStreamResult);
        }
Exemplo n.º 22
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"));
        }
Exemplo n.º 23
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);
        }
        public ActionResult DrawingShapes(string InsideBrowser)
        {
            // Create a new PDF document.
            PdfDocument doc = new PdfDocument();
            int         i;
            // Create a new page.
            PdfPage page = doc.Pages.Add();
            // Obtain PdfGraphics object.
            PdfGraphics g    = page.Graphics;
            PdfFont     font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);

            #region Polygon
            PdfPen pen = new PdfPen(Color.Black);
            pen.Width = 3;
            PointF p1 = new PointF(05, 10);
            PointF p2 = new PointF(05, 10);
            PointF p3 = new PointF(60, 70);
            PointF p4 = new PointF(40, 70);

            PointF[] points = { p1, p2, p3, p4 };

            int pointNum = 16;
            points = new PointF[pointNum];
            double       f      = 360.0 / pointNum * Math.PI / 180.0;
            const double r      = 100;
            PointF       center = new PointF(140, 140);

            for (i = 0; i < pointNum; ++i)
            {
                PointF p     = new PointF();
                double theta = i * f;

                p.Y = (float)(Math.Sin(theta) * r + center.Y);
                p.X = (float)(Math.Cos(theta) * r + center.X);

                points[i] = p;
            }

            PdfSolidBrush brush = new PdfSolidBrush(Color.Green);
            pen.Color    = Color.Brown;
            pen.Width    = 10;
            pen.LineJoin = PdfLineJoin.Round;
            g.DrawString("Polygon", font, PdfBrushes.DarkBlue, new PointF(50, 0));
            g.DrawPolygon(pen, brush, points);

            #endregion

            #region  Pie

            RectangleF rect = new RectangleF(200, 50, 200, 200);
            brush.Color = Color.Green;
            pen.Color   = Color.Brown;
            pen.Width   = 10;

            rect.Location = new PointF(20, 280);
            pen.LineJoin  = PdfLineJoin.Round;
            g.DrawString("Pie shape", font, PdfBrushes.DarkBlue, new PointF(50, 250));
            g.DrawPie(pen, brush, rect, 180, 60);
            g.DrawPie(pen, brush, rect, 360 - 60, 60);
            g.DrawPie(pen, brush, rect, 60, 60);

            #endregion

            #region Arc

            g.DrawString("Arcs", font, PdfBrushes.DarkBlue, new PointF(330, 0));
            pen         = new PdfPen(Color.Black);
            pen.Width   = 11;
            pen.LineCap = PdfLineCap.Round;
            pen.Color   = Color.Brown;
            rect        = new RectangleF(310, 40, 200, 200);
            g.DrawArc(pen, rect, 0, 90);

            pen.Color = Color.DarkGreen;
            rect.X   -= 10;
            g.DrawArc(pen, rect, 90, 90);

            pen.Color = Color.Brown;
            rect.Y   -= 10;
            g.DrawArc(pen, rect, 180, 90);

            pen.Color = Color.DarkGreen;
            rect.X   += 10;
            g.DrawArc(pen, rect, 270, 90);

            #endregion

            #region Rectangle
            rect        = new RectangleF(310, 280, 200, 100);
            brush.Color = Color.Green;
            pen.Color   = Color.Brown;
            g.DrawString("Simple Rectangle", font, PdfBrushes.DarkBlue, new PointF(310, 255));
            g.DrawRectangle(pen, brush, rect);
            #endregion

            #region ellipse

            // Draw a simple ellipse.
            pen  = new PdfPen(Color.Black);
            rect = new RectangleF(80, 520, 100, 200);
            //page = doc.Pages[0];
            //g = page.Graphics;
            PdfLinearGradientBrush lgBrush = new PdfLinearGradientBrush(rect, Color.DarkGreen, Color.White, 90);

            brush       = new PdfSolidBrush(Color.Black);
            brush.Color = Color.DarkGreen;
            pen.Color   = Color.Brown;
            pen.Width   = 10.0f;
            g.DrawString("Ellipse with Gradient", font, PdfBrushes.DarkBlue, new PointF(50, 490));
            g.DrawEllipse(pen, lgBrush, rect);


            rect = new RectangleF(270, 400, 160, 1000);
            g.DrawString("Shape with pagination", font, PdfBrushes.DarkBlue, new PointF(300, 390));
            PdfEllipse      ellipse = new PdfEllipse(rect);
            PdfLayoutFormat format  = new PdfLayoutFormat();
            format.Break  = PdfLayoutBreakType.FitPage;
            format.Layout = PdfLayoutType.Paginate;
            ellipse.Brush = PdfBrushes.Brown;
            ellipse.Draw(page, 20, 20, format);

            brush         = new PdfSolidBrush(Color.Black);
            ellipse.Brush = PdfBrushes.DarkGreen;
            ellipse.Draw(page, 40, 40, format);

            #endregion

            #region Transaparency

            page = doc.Pages[1];
            g    = page.Graphics;
            g.DrawString("Transparent Rectangles", font, PdfBrushes.DarkBlue, new PointF(50, 80));
            PdfBrush gBrush;
            rect = new RectangleF(10, 150, 100, 100);

            pen    = new PdfPen(Color.Black);
            gBrush = new PdfSolidBrush(Color.DarkGreen);

            g.DrawRectangle(pen, gBrush, rect);
            gBrush  = new PdfSolidBrush(Color.Brown);
            rect.X += 20;
            rect.Y += 20;
            pen     = new PdfPen(Color.Brown);
            g.SetTransparency(0.7f);
            g.DrawRectangle(pen, gBrush, rect);

            rect.X += 20;
            rect.Y += 20;
            gBrush  = new PdfLinearGradientBrush(rect, Color.DarkGreen, Color.Brown, PdfLinearGradientMode.BackwardDiagonal);
            g.SetTransparency(0.5f);
            g.DrawRectangle(pen, gBrush, rect);

            rect.X += 20;
            rect.Y += 20;
            pen     = new PdfPen(Color.Blue);
            gBrush  = new PdfSolidBrush(Color.Gray);
            g.SetTransparency(0.25f);
            g.DrawRectangle(pen, gBrush, rect);

            rect.X += 20;
            rect.Y += 20;
            pen     = new PdfPen(Color.Black);
            gBrush  = new PdfSolidBrush(Color.Green);
            g.SetTransparency(0.1f);
            g.DrawRectangle(pen, gBrush, rect);

            #endregion

            #region Rectangle with Color space



            PointF location = new PointF(10, 50);
            page = doc.Pages.Add();
            g    = page.Graphics;

            doc.ColorSpace = (PdfColorSpace)i;

            // SolidBrush
            gBrush = new PdfSolidBrush(Color.Red);
            DrawRectangles(location, g, font, gBrush, pen, doc);

            // LinearGradient
            location = new PointF(180, 50);

            PointF point2 = location;

            point2.X += 100;
            gBrush    = new PdfLinearGradientBrush(location, point2, Color.Blue, Color.Red);
            DrawRectangles(location, g, font, gBrush, pen, doc);

            // Raidal Gradient
            location  = new PointF(360, 50);
            point2    = location;
            point2.Y += 250;
            point2.X  = 150;
            gBrush    = new PdfRadialGradientBrush(point2, 210, point2, 400, Color.Blue, Color.Red);
            (gBrush as PdfRadialGradientBrush).Extend = PdfExtend.End;
            DrawRectangles(location, g, font, gBrush, pen, doc);

            g.DrawString("Rectangle with color spaces", font, PdfBrushes.DarkBlue, new PointF(150, 0));
            #endregion
            //Stream the output to the browser.
            if (InsideBrowser == "Browser")
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
        /// <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);
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            doc = new PdfDocument();
            doc.PageSettings.Margins.All = 0;
            page = doc.Pages.Add();
            PdfGraphics g = page.Graphics;

            PdfFont headerFont     = new PdfStandardFont(PdfFontFamily.TimesRoman, 35);
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

            g.DrawRectangle(new PdfSolidBrush(gray), new RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));
            g.DrawRectangle(new PdfSolidBrush(black), new RectangleF(0, 0, page.Graphics.ClientSize.Width, 130));
            g.DrawRectangle(new PdfSolidBrush(white), new RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450));
            g.DrawString("Enterprise", headerFont, new PdfSolidBrush(violet), new PointF(10, 20));
            g.DrawRectangle(new PdfSolidBrush(violet), new RectangleF(10, 63, 140, 35));
            g.DrawString("Reporting Solutions", subHeadingFont, new PdfSolidBrush(black), new PointF(15, 70));

            PdfLayoutResult result = HeaderPoints("Develop cloud-ready reporting applications in as little as 20% of the time.", 15);

            result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15);
            result = HeaderPoints("Microsoft Excel, Word, Adobe PDF, RDL display and editing.", result.Bounds.Bottom + 15);
            result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks", result.Bounds.Bottom + 15);

            result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45);
            result = BodyContent("Our architects and developers have years of reporting experience.", result.Bounds.Bottom + 25);
            result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25);
            result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25);
            result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25);

            PdfPen redPen = new PdfPen(PdfBrushes.Red, 2);

            g.DrawLine(redPen, new PointF(40, result.Bounds.Bottom + 92), new PointF(40, result.Bounds.Bottom + 145));
            float          headerBulletsXposition = 40;
            PdfTextElement txtElement             = new PdfTextElement("The Experts");

            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200));

            PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2);

            g.DrawLine(violetPen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145));
            txtElement      = new PdfTextElement("Accurate Estimates");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200));

            txtElement      = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200));


            txtElement      = new PdfTextElement("Given our expertise, you can expect estimates to be accurate.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200));


            PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2);

            g.DrawLine(greenPen, new PointF(40, result.Bounds.Bottom + 32), new PointF(40, result.Bounds.Bottom + 85));

            txtElement      = new PdfTextElement("Product Licensing");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200));

            PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2);

            g.DrawLine(bluePen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85));
            txtElement      = new PdfTextElement("About Syncfusion");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200));

            txtElement      = new PdfTextElement("Solution packages can be combined with product licensing for great cost savings.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200));


            txtElement      = new PdfTextElement("Syncfusion has more than 7,000 customers including large financial institutions and Fortune 100 companies.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200));

            Stream imgStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Reporting-Edition.jpg");

            g.DrawImage(PdfImage.FromStream(imgStream), 280, 600, 300, 170);

            g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new PointF(10, g.ClientSize.Height - 30));
            PdfTextWebLink linkAnnot = new PdfTextWebLink();

            linkAnnot.Url   = "http://www.syncfusion.com";
            linkAnnot.Text  = "www.syncfusion.com";
            linkAnnot.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic);
            linkAnnot.Brush = PdfBrushes.White;
            linkAnnot.DrawTextWebLink(page, new PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30));
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);
            doc.Close(true);

            if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("GettingStarted.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("GettingStarted.pdf", "application/pdf", stream);
            }
        }
Exemplo n.º 27
0
        public async Task <FileStreamResult> CompleteAsync(int?id)
        {
            var paper = await _context.papers
                        .FirstOrDefaultAsync(m => m.id == id);


            List <StudentData> students = new List <StudentData>();
            List <StudentData> print    = new List <StudentData>();

            students = await _context.studentDatas.ToListAsync();

            StudentData student = null;

            for (int i = 0; i < students.Count(); i++)
            {
                if ((students[i].Studentid).Equals(paper.StudentID))

                {
                    student         = new StudentData();
                    student.Faculty = students[i].Faculty;
                    student.Course  = students[i].Course;
                    student.Note    = students[i].Note;
                    print.Add(student);
                }
            }



            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;

            //Set the standard font
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);



            FileStream imageStream = new FileStream("ua.jpg", FileMode.Open, FileAccess.Read);
            PdfBitmap  image       = new PdfBitmap(imageStream);

            //Draw the image
            graphics.DrawImage(image, 30, 0);



            if (paper.type == "Notes")
            {
                DataTable table = new DataTable("INFO");

                // Declare DataColumn and DataRow variables.
                DataColumn column;
                DataColumn column2;


                // Create column.
                column            = new DataColumn();
                column.DataType   = Type.GetType("System.String");
                column.ColumnName = "Course";
                table.Columns.Add(column);

                column2            = new DataColumn();
                column2.DataType   = Type.GetType("System.Int32");
                column2.ColumnName = "Note";
                table.Columns.Add(column2);

                foreach (StudentData item in print)
                {
                    table.Rows.Add(item.Course, item.Note);
                }



                PdfBrush  solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
                Rectangle bounds     = new RectangleF(0, 200, graphics.ClientSize.Width, 30);
                //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 element = new PdfTextElement("Student " + paper.Firstname + " " + paper.lastname, 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("MM/dd/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("Student ID: " + paper.StudentID, timesRoman);
                element.Brush = new PdfSolidBrush(new PdfColor(126, 155, 203));
                result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));
                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);


                //Creates the datasource for the table

                //Creates a PDF grid
                PdfGrid grid = new PdfGrid();
                //Adds the data source
                grid.DataSource = table;
                //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, 151, 173));
                headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
                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++)
                {
                    if (i == 0 || i == 1)
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }
                }

                //Applies the header style
                header.ApplyStyle(headerStyle);
                cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
                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);
            }

            if (paper.type == "Continue Education")
            {
                int    now   = DateTime.Now.Year;
                int    y     = now - 1;
                String text  = "The student " + paper.Firstname + " " + paper.lastname + " continu his/her education for the year: ";
                String text2 = y + "-" + now;
                graphics.DrawString(text, font, PdfBrushes.Black, new PointF(0, 180));
                graphics.DrawString(text2, font, PdfBrushes.Red, new PointF(0, 210));
            }


            //Saving the PDF to the MemoryStream
            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");

            fileStreamResult.FileDownloadName = paper.StudentID + "_" + paper.type + ".pdf";

            paper.Status = "Complete";

            _context.Update(paper);
            await _context.SaveChangesAsync();

            RedirectToAction("Admin");

            return(fileStreamResult);
        }
Exemplo n.º 28
0
        public IActionResult Index()
        {
            //Creates a new PDF document
            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;

            //Loads the image as stream
            FileStream imageStream = new FileStream("logo.png", FileMode.Open, FileAccess.Read);
            RectangleF bounds      = new RectangleF(176, 0, 390, 130);
            PdfImage   image       = PdfImage.FromStream(imageStream);

            //Draws the image to the PDF page
            page.Graphics.DrawImage(image, bounds);
            PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));

            bounds = new RectangleF(0, bounds.Bottom + 90, graphics.ClientSize.Width, 30);
            //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 element = new PdfTextElement("Purchase Order", 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("MM/dd/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));
            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);
            //Creates the datasource for the table
            var invoiceDetails = GetProductDetailsAsDataTable();
            //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, 151, 173));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
            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++)
            {
                if (i == 0 || i == 1)
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }

            //Applies the header style
            header.ApplyStyle(headerStyle);
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
            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);
            //Save the PDF document to stream
            MemoryStream ms = new MemoryStream();

            document.Save(ms);
            document.Close(true);


            ms.Position = 0;

            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

            fileStreamResult.FileDownloadName = "Sample.pdf";
            return(fileStreamResult);
        }
Exemplo n.º 29
0
        public ActionResult InteractiveFeatures(string InsideBrowser)
        {
            #region Field Definitions
            document = new PdfDocument();
            document.PageSettings.Margins.All = 0;
            document.PageSettings.Size        = new SizeF(PdfPageSize.A4.Width, 600);
            interactivePage = document.Pages.Add();
            PdfGraphics g    = interactivePage.Graphics;
            RectangleF  rect = new RectangleF(0, 0, interactivePage.Graphics.ClientSize.Width, 100);

            PdfBrush whiteBrush  = new PdfSolidBrush(white);
            PdfPen   whitePen    = new PdfPen(white, 5);
            PdfBrush purpleBrush = new PdfSolidBrush(new PdfColor(255, 158, 0, 160));
            PdfFont  font        = new PdfStandardFont(PdfFontFamily.Helvetica, 25);
            Syncfusion.Drawing.Color maroonColor = Color.FromArgb(255, 188, 32, 60);
            Syncfusion.Drawing.Color orangeColor = Color.FromArgb(255, 255, 167, 73);
            #endregion

            #region Header
            g.DrawRectangle(purpleBrush, rect);
            g.DrawPie(whitePen, whiteBrush, new RectangleF(-20, 35, 700, 200), 20, -180);
            g.DrawRectangle(whiteBrush, new RectangleF(0, 99.5f, 700, 200));
            g.DrawString("Invoice", new PdfStandardFont(PdfFontFamily.TimesRoman, 24), PdfBrushes.White, new PointF(500, 10));

            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;
            dataPath = basePath + @"/PDF/";

            //Read the file
            FileStream file = new FileStream(dataPath + "AdventureCycle.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            g.DrawImage(PdfImage.FromStream(file), new RectangleF(100, 70, 390, 130));
            #endregion

            #region Body

            //Invoice Number
            Random invoiceNumber = new Random();
            g.DrawString("Invoice No: " + invoiceNumber.Next().ToString(), new PdfStandardFont(PdfFontFamily.Helvetica, 14), new PdfSolidBrush(maroonColor), new PointF(50, 210));
            g.DrawString("Date: ", new PdfStandardFont(PdfFontFamily.Helvetica, 14), new PdfSolidBrush(maroonColor), new PointF(350, 210));

            //Current Date
            PdfTextBoxField textBoxField = new PdfTextBoxField(interactivePage, "date");
            textBoxField.Font          = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
            textBoxField.Bounds        = new RectangleF(384, 204, 150, 30);
            textBoxField.ForeColor     = new PdfColor(maroonColor);
            textBoxField.ReadOnly      = true;
            document.Actions.AfterOpen = new PdfJavaScriptAction(@"var newdate = new Date(); 
            var thisfieldis = this.getField('date');  
            
            var theday = util.printd('dddd',newdate); 
            var thedate = util.printd('d',newdate); 
            var themonth = util.printd('mmmm',newdate);
            var theyear = util.printd('yyyy',newdate);  
            
            thisfieldis.strokeColor=color.transparent;
            thisfieldis.value = theday + ' ' + thedate + ', ' + themonth + ' ' + theyear ;");
            document.Form.Fields.Add(textBoxField);

            //invoice table
            PdfLightTable table = new PdfLightTable();
            table.Style.ShowHeader = true;
            g.DrawRectangle(new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(238, 238, 238, 248)), new RectangleF(50, 240, 500, 140));

            //Header Style
            PdfCellStyle headerStyle = new PdfCellStyle();
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);
            headerStyle.TextBrush       = whiteBrush;
            headerStyle.StringFormat    = new PdfStringFormat(PdfTextAlignment.Center);
            headerStyle.BackgroundBrush = new PdfSolidBrush(orangeColor);
            headerStyle.BorderPen       = new PdfPen(whiteBrush, 0);
            table.Style.HeaderStyle     = headerStyle;

            //Cell Style
            PdfCellStyle bodyStyle = new PdfCellStyle();
            bodyStyle.Font           = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
            bodyStyle.StringFormat   = new PdfStringFormat(PdfTextAlignment.Left);
            bodyStyle.BorderPen      = new PdfPen(whiteBrush, 0);
            table.Style.DefaultStyle = bodyStyle;
            table.DataSource         = GetProductReport(_hostingEnvironment.WebRootPath);
            table.Columns[0].Width   = 90;
            table.Columns[1].Width   = 160;
            table.Columns[3].Width   = 100;
            table.Columns[4].Width   = 65;
            table.Style.CellPadding  = 3;
            table.BeginCellLayout   += table_BeginCellLayout;

            PdfLightTableLayoutResult result = table.Draw(interactivePage, new RectangleF(50, 240, 500, 140));

            g.DrawString("Grand Total:", new PdfStandardFont(PdfFontFamily.Helvetica, 12), new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 167, 73)), new PointF(result.Bounds.Right - 150, result.Bounds.Bottom));
            CreateTextBox(interactivePage, "GrandTotal", "Grand Total", new RectangleF(result.Bounds.Width - 15, result.Bounds.Bottom - 2, 66, 18), true, "");


            //Send to Server
            PdfButtonField sendButton = new PdfButtonField(interactivePage, "OrderOnline");
            sendButton.Bounds      = new RectangleF(200, result.Bounds.Bottom + 70, 80, 25);
            sendButton.BorderColor = white;
            sendButton.BackColor   = maroonColor;
            sendButton.ForeColor   = white;
            sendButton.Text        = "Order Online";
            PdfSubmitAction submitAction = new PdfSubmitAction("http://stevex.net/dump.php");
            submitAction.DataFormat    = SubmitDataFormat.Html;
            sendButton.Actions.MouseUp = submitAction;
            document.Form.Fields.Add(sendButton);

            //Order by Mail
            PdfButtonField sendMail = new PdfButtonField(interactivePage, "sendMail");
            sendMail.Bounds      = new RectangleF(300, result.Bounds.Bottom + 70, 80, 25);
            sendMail.Text        = "Order By Mail";
            sendMail.BorderColor = white;
            sendMail.BackColor   = maroonColor;
            sendMail.ForeColor   = white;

            // Create a javascript action.
            PdfJavaScriptAction javaAction = new PdfJavaScriptAction("address = app.response(\"Enter an e-mail address.\",\"SEND E-MAIL\",\"\");"
                                                                     + "var aSubmitFields = [];"
                                                                     + "for( var i = 0 ; i < this.numFields; i++){"
                                                                     + "aSubmitFields[i] = this.getNthFieldName(i);"
                                                                     + "}"
                                                                     + "if (address){ cmdLine = \"mailto:\" + address;this.submitForm(cmdLine,true,false,aSubmitFields);}");

            sendMail.Actions.MouseUp = javaAction;
            document.Form.Fields.Add(sendMail);

            //Print
            PdfButtonField printButton = new PdfButtonField(interactivePage, "print");
            printButton.Bounds          = new RectangleF(400, result.Bounds.Bottom + 70, 80, 25);
            printButton.BorderColor     = white;
            printButton.BackColor       = maroonColor;
            printButton.ForeColor       = white;
            printButton.Text            = "Print";
            printButton.Actions.MouseUp = new PdfJavaScriptAction("this.print (true); ");
            document.Form.Fields.Add(printButton);
            file = new FileStream(dataPath + "Product Catalog.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            PdfAttachment attachment = new PdfAttachment("Product Catalog.pdf", file);
            attachment.ModificationDate = DateTime.Now;
            attachment.Description      = "Specification";
            document.Attachments.Add(attachment);

            //Open Specification
            PdfButtonField openSpecificationButton = new PdfButtonField(interactivePage, "openSpecification");
            openSpecificationButton.Bounds          = new RectangleF(50, result.Bounds.Bottom + 20, 87, 15);
            openSpecificationButton.TextAlignment   = PdfTextAlignment.Left;
            openSpecificationButton.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
            openSpecificationButton.BorderStyle     = PdfBorderStyle.Underline;
            openSpecificationButton.BorderColor     = orangeColor;
            openSpecificationButton.BackColor       = new PdfColor(255, 255, 255);
            openSpecificationButton.ForeColor       = orangeColor;
            openSpecificationButton.Text            = "Open Specification";
            openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Product Catalog.pdf', nLaunch: 2 });");
            document.Form.Fields.Add(openSpecificationButton);

            RectangleF     uriAnnotationRectangle = new RectangleF(interactivePage.Graphics.ClientSize.Width - 160, interactivePage.Graphics.ClientSize.Height - 30, 80, 20);
            PdfTextWebLink linkAnnot = new PdfTextWebLink();
            linkAnnot.Url   = "http://www.adventure-works.com";
            linkAnnot.Text  = "http://www.adventure-works.com";
            linkAnnot.Font  = new PdfStandardFont(PdfFontFamily.Helvetica, 8);
            linkAnnot.Brush = PdfBrushes.White;
            linkAnnot.DrawTextWebLink(interactivePage, uriAnnotationRectangle.Location);
            #endregion

            #region Footer
            g.DrawRectangle(purpleBrush, new RectangleF(0, interactivePage.Graphics.ClientSize.Height - 100, interactivePage.Graphics.ClientSize.Width, 100));
            g.DrawPie(whitePen, whiteBrush, new RectangleF(-20, interactivePage.Graphics.ClientSize.Height - 250, 700, 200), 0, 180);
            #endregion

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            document.Save(ms);

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

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

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
            fileStreamResult.FileDownloadName = "Interactive features.pdf";
            return(fileStreamResult);
        }
Exemplo n.º 30
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            doc = new PdfDocument();
            doc.PageSettings.Margins.All = 0;
            page = doc.Pages.Add();
            PdfGraphics g = page.Graphics;

            PdfFont headerFont     = new PdfStandardFont(PdfFontFamily.TimesRoman, 35);
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

            g.DrawRectangle(new PdfSolidBrush(gray), new RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));
            g.DrawRectangle(new PdfSolidBrush(black), new RectangleF(0, 0, page.Graphics.ClientSize.Width, 130));
            g.DrawRectangle(new PdfSolidBrush(white), new RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450));
            g.DrawString("Syncfusion", headerFont, new PdfSolidBrush(violet), new PointF(10, 20));
            g.DrawRectangle(new PdfSolidBrush(violet), new RectangleF(10, 63, 155, 35));
            g.DrawString("File Formats", subHeadingFont, new PdfSolidBrush(black), new PointF(45, 70));

            PdfLayoutResult result = HeaderPoints("Optimized for usage in a server environment where spread and low memory usage in critical.", 15);

            result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15);
            result = HeaderPoints("Microsoft Excel, Word, Presentation, PDF and PDF Viewer.", result.Bounds.Bottom + 15);
            result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks.", result.Bounds.Bottom + 15);

            result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45);
            result = BodyContent("Enable your applications to read and write file formats documents easily.", result.Bounds.Bottom + 25);
            result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25);
            result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25);
            result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25);

            PdfPen redPen = new PdfPen(PdfBrushes.Red, 2);

            g.DrawLine(redPen, new PointF(40, result.Bounds.Bottom + 92), new PointF(40, result.Bounds.Bottom + 145));
            float          headerBulletsXposition = 40;
            PdfTextElement txtElement             = new PdfTextElement("The Experts");

            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200));

            PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2);

            g.DrawLine(violetPen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145));
            txtElement      = new PdfTextElement("Accurate Estimates");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200));

            txtElement      = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200));


            txtElement      = new PdfTextElement("Given our expertise, you can expect estimates to be accurate.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200));


            PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2);

            g.DrawLine(greenPen, new PointF(40, result.Bounds.Bottom + 32), new PointF(40, result.Bounds.Bottom + 85));

            txtElement      = new PdfTextElement("No-Hassle Licensing");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200));

            PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2);

            g.DrawLine(bluePen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85));
            txtElement      = new PdfTextElement("About Syncfusion");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200));

            txtElement      = new PdfTextElement("No royalties, run time, or server deployment fees means no surprises.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200));


            txtElement      = new PdfTextElement("Syncfusion is the enterprise technology partner of choice for software development, delivering a board range of web, mobile, and desktop controls.");
            txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
            result          = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200));

            Stream imgStream = typeof(GettingStartedPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_bannerEdit.jpg");

            g.DrawImage(PdfImage.FromStream(imgStream), 180, 630, 280, 150);

            g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new PointF(10, g.ClientSize.Height - 30));
            PdfTextWebLink linkAnnot = new PdfTextWebLink();

            linkAnnot.Url   = "http://www.syncfusion.com";
            linkAnnot.Text  = "www.syncfusion.com";
            linkAnnot.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic);
            linkAnnot.Brush = PdfBrushes.White;
            linkAnnot.DrawTextWebLink(page, new PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30));
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);
            doc.Close(true);

            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save("GettingStarted.pdf", "application/pdf", stream, m_context);
            }
        }