示例#1
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
        }
示例#2
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            //Create a new PDF Document. The pdfDoc object represents the PDF document.
            //This document has one page by default and additional pages have to be added.
            PdfDocument pdfDoc = new PdfDocument();
            PdfPage     page   = pdfDoc.Pages.Add();

            // Get xmp object.
            XmpMetadata xmp = pdfDoc.DocumentInformation.XmpMetadata;


            // XMP Basic Schema.
            BasicSchema basic = xmp.BasicSchema;

            basic.Advisory.Add("advisory");
            basic.BaseURL     = new Uri("http://google.com");
            basic.CreateDate  = DateTime.Now;
            basic.CreatorTool = "creator tool";
            basic.Identifier.Add("identifier");
            basic.Label        = "label";
            basic.MetadataDate = DateTime.Now;
            basic.ModifyDate   = DateTime.Now;
            basic.Nickname     = "nickname";
            basic.Rating.Add(-25);

            //Setting various Document properties.
            pdfDoc.DocumentInformation.Title        = "Document Properties Information";
            pdfDoc.DocumentInformation.Author       = "Syncfusion";
            pdfDoc.DocumentInformation.Keywords     = "PDF";
            pdfDoc.DocumentInformation.Subject      = "PDF demo";
            pdfDoc.DocumentInformation.Producer     = "Syncfusion Software";
            pdfDoc.DocumentInformation.CreationDate = DateTime.Now;

            PdfFont  font     = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            PdfFont  boldFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            PdfBrush brush    = PdfBrushes.Black;

            PdfGraphics     g      = page.Graphics;
            PdfStringFormat format = new PdfStringFormat();

            format.LineSpacing = 10f;

            g.DrawString("Press Ctrl+D to see Document Properties", boldFont, brush, 10, 10);
            g.DrawString("Basic Schema Xml:", boldFont, brush, 10, 50);
            g.DrawString(basic.XmlData.OuterXml, font, brush, new RectangleF(10, 70, 500, 500), format);

            //Defines and set values for Custom metadata and add them to the Pdf document
            CustomSchema custom = new CustomSchema(xmp, "custom", "http://www.syncfusion.com/");

            custom["Company"] = "Syncfusion";
            custom["Website"] = "http://www.syncfusion.com/";
            custom["Product"] = "Essential PDF";


            //Save the PDF Document to disk.
            pdfDoc.Save("Sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
                System.Diagnostics.Process.Start("Sample.pdf");
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            PdfDocument document = new PdfDocument();

            PdfPageBase page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;

            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 20f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;
            PdfForm         form  = document.Form;

            //Document security
            PdfSecurity security = document.Security;

            //Specify key size and encryption algorithm
            if (encryptionTechnique.SelectionBoxItem.ToString() == "40-Bit RC4")
            {
                //use 40 bits key in RC4 mode
                security.KeySize   = PdfEncryptionKeySize.Key40Bit;
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "128-Bit RC4")
            {
                //use 128 bits key in RC4 mode
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "128-Bit AES")
            {
                //use 128 bits key in RC4 mode
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES")
            {
                //use 256 bits key in AES mode
                security.KeySize   = PdfEncryptionKeySize.Key256Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES Revision 6")
            {
                //use 256 bits key in AES mode with Revision 6
                security.KeySize   = PdfEncryptionKeySize.Key256BitRevision6;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            if (!cmbencryptOption.IsEnabled || cmbencryptOption.SelectedIndex == 0)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (cmbencryptOption.SelectedIndex == 1)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (cmbencryptOption.SelectedIndex == 2)
            {
                //Read the file
                Stream imgStream = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Products.xml");

                PdfAttachment attachment = new PdfAttachment("Products.xml", imgStream);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);

                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
            }
            security.OwnerPassword = txtOwnerPassword.Password;
            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = txtUserPassword.Password;

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);

            if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES Revision 6")
            {
                text += String.Format("\n\nRevision: {0}", "Revision6");
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES")
            {
                text += String.Format("\n\nRevision: {0}", "Revision5");
            }

            graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new PointF(0, 40));

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

            document.Close(true);
            Save(stream, "FormFilling.pdf");
        }
        private void btnSubmitTrans_Click(object sender, RoutedEventArgs e)
        {
            if (TxtPay.Text == "0" || TxtPay.Text == "")
            {
                MessageBox.Show("Fill column pay please", "Alert", MessageBoxButton.OK);
                TxtPay.Focus();
            }
            else
            {
                int change = Convert.ToInt32(TxtPay.Text) - Convert.ToInt32(TxtTotal.Text);
                try
                {
                    int transid = Convert.ToInt32(TxtTransId.Text);
                    var item    = myContext.TransactionItems.FirstOrDefault(i => i.TransactionFK.Id == transid);
                    var trans   = myContext.Transactions.FirstOrDefault(data => data.Id == transid);
                    trans.Total = Convert.ToInt32(TxtTotal.Text);
                    trans.Pay   = Convert.ToInt32(TxtPay.Text);
                    myContext.SaveChanges();
                    TxtChange.Text = "Rp. " + change.ToString("n0") + ",-";
                    foreach (var transItem in TransDetail)
                    {
                        myContext.TransactionItems.Add(transItem);
                        myContext.SaveChanges();
                    }

                    MessageBox.Show("Your change is Rp. " + change.ToString("n0") + ",-", "Message", MessageBoxButton.OK);
                    receipt += item.ItemFK.Name + "\t" + item.Quantity + "\t" + item.SubTotal + "\nTotal: Rp. "
                               + item.TransactionFK.Total.ToString("n0") + ",-\nPay: Rp. "
                               + item.TransactionFK.Pay.ToString("n0") + ",-\nChange: Rp. "
                               + (item.TransactionFK.Pay - item.TransactionFK.Total).ToString("n0") + ",-";
                    using (PdfDocument document = new PdfDocument())
                    {
                        //Add a page to the document
                        PdfPage page = document.Pages.Add();

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

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

                        //Draw the text
                        graphics.DrawString(receipt, font, PdfBrushes.Black, new PointF(0, 0));

                        //Save the document
                        document.Save("Receipt.pdf");
                    }
                }
                catch (Exception)
                {
                }
                //comboBoxItem.Text = "--Choose Item--";
                TxtTransId.Text = "";
                GridTransItem.Items.Clear();
                grandTotal               = 0;
                TxtTotal.Text            = "0";
                TxtChange.Text           = "0";
                TxtPay.IsEnabled         = false;
                btnAddTrans.IsEnabled    = true;
                comboBoxItem.IsEnabled   = false;
                TxtQuantity.IsEnabled    = false;
                btnAddToCart.IsEnabled   = false;
                btnDeleteTrans.IsEnabled = false;
                btnCancel.IsEnabled      = false;
                btnSubmitTrans.IsEnabled = false;
                Load();
            }
        }
示例#5
0
        public ActionResult AddPrescription(PrescriptionViewModel model)
        {
            if (ModelState.IsValid && model.days != null)
            {
                var prescription = _db.Prescriptions.Where(p => p.PrescriptionId == model.Id).FirstOrDefault();

                PdfDocument doc = new PdfDocument();


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

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

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

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

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

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

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

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

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

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


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

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

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


            return(View(model));
        }
示例#6
0
        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);
        }
        private void Draw(PdfGraphics g, TextBlock block)
        {
            var    brush     = new PdfSolidBrush(new PdfColor(GetColor(block.Font.Color)));
            string fontStyle = "";

            if (block.Font.Bold)
            {
                fontStyle += "b";
            }
            if (block.Font.Italic)
            {
                fontStyle += "i";
            }

            string fontFile = Path.Combine(Directory.GetCurrentDirectory(), "Fonts", block.Font.Family, fontStyle + ".ttf");

            if (!File.Exists(fontFile))
            {
                fontFile = Path.Combine(Directory.GetCurrentDirectory(), "Fonts", block.Font.Family + ".ttf");
            }

            Stream  fontStream = new FileStream(fontFile, FileMode.Open, FileAccess.Read);
            PdfFont pdfFont    = new PdfTrueTypeFont(fontStream, (float)block.Font.Size);

            double?width  = block.AutoWidth ? (block.MaxWidth > 0 ? block.MaxWidth : null) : block.Layout.Width;
            double?height = block.AutoHeight ? (block.MaxHeight > 0 ? block.MaxHeight : null) : block.Layout.Height;

            var textProps = GetTextProperties(block.Text, width, height, pdfFont);

            double shiftAmt = 0;

            if (block.AutoHeight)
            {
                shiftAmt            = textProps.Height - block.Layout.Height;
                m_globalShift      += shiftAmt;
                block.Layout.Height = textProps.Height;
            }
            if (block.AutoWidth)
            {
                block.Layout.Width = textProps.Width;
            }

            double lineHeight = block.Font.Size * LINE_HEIGHT_RATIO;
            double yShiftAmt  = 0;

            if (block.VerticallyCenter)
            {
                yShiftAmt += (block.Layout.Height - textProps.Height) / 2;
            }

            PdfStringFormat textSettings = block.Font.Alignment;

            var xPos = (float)block.Layout.X;

            if (textSettings.Alignment == PdfTextAlignment.Center)
            {
                xPos = (float)(block.Layout.X + (block.Layout.Width / 2));
            }
            else if (textSettings.Alignment == PdfTextAlignment.Right)
            {
                xPos = (float)(block.Layout.X + block.Layout.Width);
            }

            for (var lineIdx = 0; lineIdx < textProps.TextLines.Count; ++lineIdx)
            {
                var   line = textProps.TextLines[lineIdx];
                float yPos = (float)((lineIdx * lineHeight) + yShiftAmt + block.Layout.Y);
                g.DrawString(line, pdfFont, brush, new PointF(xPos, yPos), textSettings);
            }

            if (block.AutoHeight)
            {
                g.TranslateTransform(0f, (float)shiftAmt);
            }
        }
示例#8
0
        private PdfDocument createPDF()
        {
            if (startDate.SelectedDate != null && endDate.SelectedDate != null)
            {
                using (PdfDocument document = new PdfDocument())
                {
                    //Add a page to the document
                    PdfPage page = document.Pages.Add();

                    PdfGrid pdfGrid = new PdfGrid();

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

                    //Set the standard font
                    PdfFont fontTitle = new PdfStandardFont(PdfFontFamily.Helvetica, 18);
                    PdfFont fontTable = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
                    PdfFont fontInfo  = new PdfStandardFont(PdfFontFamily.Helvetica, 10, PdfFontStyle.Italic);


                    DateTime sd = (DateTime)startDate.SelectedDate;
                    DateTime ed = (DateTime)endDate.SelectedDate;

                    PdfBitmap image = new PdfBitmap(@"logo.png");

                    //Draw the image
                    graphics.DrawImage(image, 0, 0);
                    graphics.DrawString("Bulevar oslobođenja 100", fontInfo, PdfBrushes.Black, new PointF(20, 70));
                    graphics.DrawString("021/100-100", fontInfo, PdfBrushes.Black, new PointF(20, 85));
                    graphics.DrawString("www.zdravokorporacija.com", fontInfo, PdfBrushes.Black, new PointF(20, 100));

                    //Draw the text
                    graphics.DrawString("Izvještaj o zauzetosti soba za period " + sd.ToShortDateString() + " - " + ed.ToShortDateString(), fontTitle, PdfBrushes.Black, new PointF(0, 150));


                    DataTable dataTable = new DataTable();
                    //Add columns to the DataTable
                    dataTable.Columns.Add("Broj sobe");
                    dataTable.Columns.Add("Namjena");
                    dataTable.Columns.Add("Broj zakazanih pregleda/operacija");
                    //Add rows to the DataTable.
                    dataTable.Rows.Add(new object[] { "104", "Soba za pregled", "25" });
                    dataTable.Rows.Add(new object[] { "125", "Soba za pregled", "32" });
                    dataTable.Rows.Add(new object[] { "260", "Operaciona soba", "8" });
                    dataTable.Rows.Add(new object[] { "307", "Soba za pregled", "53" });
                    dataTable.Rows.Add(new object[] { "445", "Soba za pregled", "32" });
                    dataTable.Rows.Add(new object[] { "528", "Operaciona soba", "84" });
                    dataTable.Rows.Add(new object[] { "560", "Soba za pregled", "55" });
                    dataTable.Rows.Add(new object[] { "660", "Operaciona soba", "22" });
                    dataTable.Rows.Add(new object[] { "699", "Soba za pregled", "18" });
                    dataTable.Rows.Add(new object[] { "701", "Operaciona soba", "33" });
                    dataTable.Rows.Add(new object[] { "789", "Soba za pregled", "10" });
                    dataTable.Rows.Add(new object[] { "850", "Soba za pregled", "21" });
                    //Assign data source.
                    pdfGrid.DataSource = dataTable;
                    pdfGrid.Style.Font = fontTable;
                    //Draw grid to the page of PDF document.

                    pdfGrid.Draw(page, new PointF(0, 220));

                    graphics.DrawString("sekr. Marko Marković", fontInfo, PdfBrushes.Black, new PointF(300, 800));
                    graphics.DrawString("---------------------", fontInfo, PdfBrushes.Black, new PointF(300, 820));


                    //Save the document
                    document.Save("Report.pdf");

                    return(document);
                }
            }
            return(null);
        }
        public IActionResult CreateDocument()
        {
            //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, 10);

            //Load the image as stream.
            FileStream imageStream = new FileStream("wwwroot/images/Melstacorp.jpg", FileMode.Open, FileAccess.Read);
            PdfBitmap  image       = new PdfBitmap(imageStream);

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

            //Draw the text
            graphics.DrawString("Project Overview", font, PdfBrushes.Black, new PointF(0, 0));



            /*  //Creates the datasource for the table
             * System.Data.DataTable invoiceDetails = _repo.ProjectStatus();
             * //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);
             *
             */


            //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 = "Sample.pdf";

            return(fileStreamResult);
        }
示例#10
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);
                }
            }
        }
示例#11
0
        public void OnButtonClicked(object sender, EventArgs e)
        {
            //Create new PDF document.
            PdfDocument document = new PdfDocument();

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

            PdfGraphics graphics = page.Graphics;

            //Create font object.
            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;
            PdfForm         form  = document.Form;

            //Document security
            PdfSecurity security = document.Security;

            if (this.Algorithms.Items[this.Algorithms.SelectedIndex] == "AES")
            {
                security.Algorithm = PdfEncryptionAlgorithm.AES;
                if (this.keysize.SelectedIndex == 0)
                {
                    security.KeySize = PdfEncryptionKeySize.Key128Bit;
                }
                else if (this.keysize.SelectedIndex == 1)
                {
                    security.KeySize = PdfEncryptionKeySize.Key256Bit;
                }
                else if (this.keysize.SelectedIndex == 2)
                {
                    security.KeySize = PdfEncryptionKeySize.Key256BitRevision6;
                }
            }
            else if (this.Algorithms.Items[this.Algorithms.SelectedIndex] == "RC4")
            {
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
                if (this.keysize.SelectedIndex == 0)
                {
                    security.KeySize = PdfEncryptionKeySize.Key40Bit;
                }
                else if (this.keysize.SelectedIndex == 1)
                {
                    security.KeySize = PdfEncryptionKeySize.Key128Bit;
                }
            }

            if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt all contents")
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt all contents except metadata")
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt only attachments")
            {
                //Read the file
#if COMMONSB
                Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Products.xml");
#else
                Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Products.xml");
#endif

                //Creates an attachment
                PdfAttachment attachment = new PdfAttachment("Products.xml", file);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);

                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
            }

            security.OwnerPassword = "******";
            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = "******";

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);
            if (this.Algorithms.SelectedIndex == 1)
            {
                if (this.keysize.SelectedIndex == 2)
                {
                    text += String.Format("\n\nRevision: {0}", "Revision 6");
                }
                else if (this.keysize.SelectedIndex == 1)
                {
                    text += String.Format("\n\nRevision: {0}", "Revision 5");
                }
            }

            graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new PointF(0, 40));

            MemoryStream stream = new MemoryStream();
            //Save the PDF document.
            document.Save(stream);

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Secured.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("Secured.pdf", "application/pdf", stream);
            }
        }
        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);
            }
        }
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream CreatePdfDocument()
        {
            #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);
            PdfColor white = new PdfColor(255, 255, 255);
            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));

            //Read the file
            FileStream file = new FileStream(ResolveApplicationPath("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(ResolveApplicationPath("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);

            return ms;
        }
示例#14
0
        private void btnsave_Click(object sender, RoutedEventArgs e)
        {
            int vpay     = Convert.ToInt32(Txtpay.Text);
            int totalpay = Convert.ToInt32(Txttotalpay.Text);

            if (Txttotalpay.Text == "")
            {
                MessageBox.Show("Payment required !");
                Txtquantity.Focus();
            }
            else if (totalpay <= vpay)
            {
                transid = Convert.ToInt32(TxtID.Text.ToString());
                var trans      = myContext.Transactions.Where(t => t.Id == transid).FirstOrDefault();
                var item       = myContext.Items.Where(i => i.Id == itemId).FirstOrDefault();
                int totalprice = Convert.ToInt32(Txttotalpay.Text);
                trans.Total = totalprice;
                Showdata();
                foreach (var transcart in Transcart)
                {
                    myContext.TransactionItems.Add(transcart);
                    myContext.SaveChanges();
                    struk += transcart.Item.Id.ToString() + "\t" + transcart.Item.Name + "\t" + transcart.Item.Price + "\t" + transcart.Quantity + "\t";
                }
                totalprice = 0;
                MessageBox.Show("Your Change is Rp." + (vpay - totalpay).ToString("n0") + "Thank You", "Notification", MessageBoxButton.OK);
                using (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(struk, font, PdfBrushes.Black, new PointF(0, 0));

                    //Save the document
                    document.Save("Output.pdf");

                    #region View the Workbook
                    //Message box confirmation to view the created document.
                    if (MessageBox.Show("Do you want to view the PDF?", "PDF has been created",
                                        MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        try
                        {
                            //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
                            System.Diagnostics.Process.Start("Output.pdf");

                            //Exit
                            Close();
                        }
                        catch (Win32Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                    else
                    {
                        Close();
                    }
                    #endregion
                }
            }
            else
            {
                MessageBox.Show("Your Payment is Invalid !");
            }
        }
示例#15
0
        public void CreateReport(string reportFileName, List <ServiceItem> itemsToPrint)
        {
            /* create a new page */
            pdfGraphics = CreateNewPage();

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

            blockToPrintOn = -1;
            foreach (var item in itemsToPrint)
            {
                /* update the block */
                UpdateBlockNumber();

                string headerString = "";

                // base header
                //if (item.ItemType.Index == 2)
                //{
                //    headerString = "Service Move From";
                //}
                //else
                //{
                //    headerString = item.ItemType.Description;
                //}

                headerString = string.IsNullOrEmpty(item.HeaderText) ? item.ItemType.Description : item.HeaderText;

                /* add in the date */
                headerString += "           " + item.ServiceStartDate.ToLongDateString();

                pdfGraphics.DrawString(headerString, font, PdfBrushes.Black, PrintLocations.HeaderLocation[blockToPrintOn]);

                pdfGraphics.DrawString(item.CustomerName, font, PdfBrushes.Black, PrintLocations.NameLocation[blockToPrintOn]);
                pdfGraphics.DrawString(item.Address, font, PdfBrushes.Black, PrintLocations.AddressLocation[blockToPrintOn]);
                if (item.City != null)
                {
                    pdfGraphics.DrawString(item.City, font, PdfBrushes.Black, PrintLocations.CityLocation[blockToPrintOn]);
                }
                if (item.Phone != null)
                {
                    pdfGraphics.DrawString(item.Phone, font, PdfBrushes.Black, PrintLocations.PhoneLocation[blockToPrintOn]);
                }
                if (item.BagRate != null)
                {
                    pdfGraphics.DrawString(item.BagRate, font, PdfBrushes.Black, PrintLocations.BagRateLocation[blockToPrintOn]);
                }
                if (item.Amount != null)
                {
                    pdfGraphics.DrawString(item.Amount, font, PdfBrushes.Black, PrintLocations.AmountLocation[blockToPrintOn]);
                }

                /* for new services ... there is no need to list out the Route/Sequence number */
                if (item.ItemType.Index != 1)
                {
                    if (string.IsNullOrEmpty(item.RouteSequenceText) == false)
                    {
                        pdfGraphics.DrawString(item.RouteSequenceText, font, PdfBrushes.Black, PrintLocations.RouteSeqLocation[blockToPrintOn]);
                    }
                }

                /* print the remarks if they are not null */
                if (string.IsNullOrEmpty(item.Remarks) == false)
                {
                    pdfGraphics.DrawString(item.Remarks, font, PdfBrushes.Black, new RectangleF(PrintLocations.RemarksLocation[blockToPrintOn].X, PrintLocations.RemarksLocation[blockToPrintOn].Y, 250, 250));
                }

                /* for moving we need 2 tickets */
                //if (item.ItemType.Index == 2)
                //{
                //    /* update the block */
                //    UpdateBlockNumber();

                //    pdfGraphics.DrawString("Service Move To           " + item.MoveServiceStartDate.ToLongDateString(), font, PdfBrushes.Black, PrintLocations.HeaderLocation[blockToPrintOn]);
                //    pdfGraphics.DrawString(item.CustomerName, font, PdfBrushes.Black, PrintLocations.NameLocation[blockToPrintOn]);
                //    if (string.IsNullOrEmpty(item.SecondaryAddress) == false) pdfGraphics.DrawString(item.SecondaryAddress, font, PdfBrushes.Black, PrintLocations.AddressLocation[blockToPrintOn]);
                //    if (string.IsNullOrEmpty(item.SecondaryCity) == false) pdfGraphics.DrawString(item.SecondaryCity, font, PdfBrushes.Black, PrintLocations.CityLocation[blockToPrintOn]);
                //    if (string.IsNullOrEmpty(item.SecondaryPhone) == false) pdfGraphics.DrawString(item.SecondaryPhone, font, PdfBrushes.Black, PrintLocations.PhoneLocation[blockToPrintOn]);
                //    pdfGraphics.DrawString(item.BagRate, font, PdfBrushes.Black, PrintLocations.BagRateLocation[blockToPrintOn]);
                //    pdfGraphics.DrawString(item.Amount, font, PdfBrushes.Black, PrintLocations.AmountLocation[blockToPrintOn]);

                //    if (string.IsNullOrEmpty(item.SecondaryRemarks) == false)
                //    {
                //        pdfGraphics.DrawString(item.SecondaryRemarks, font, PdfBrushes.Black, new RectangleF(PrintLocations.RemarksLocation[blockToPrintOn].X, PrintLocations.RemarksLocation[blockToPrintOn].Y, 250, 250));
                //    }
                //}
            }

            //Save the new document.
            document.Save(reportFileName);

            //Close the documents
            templatedDocument.Close(true);
            document.Close(true);
        }
示例#16
0
        /// <summary>
        /// Draws the viewmodel on a pdf page.
        /// </summary>
        /// <param name="drawnItems"></param>
        /// <param name="widthHeightRatio"></param>
        public void DrawSingleOntoPage(PdfPage page, KeyValuePair <AnalysableImageViewModel, ExportReportAsPdfArguments> exportableVmToArgs)
        {
            // Setup data.
            var viewModel  = exportableVmToArgs.Key;
            var drawnItems = new List <FrameworkElement>();

            foreach (var o in exportableVmToArgs.Value.DrawnObjects)
            {
                if (o is FrameworkElement el)
                {
                    drawnItems.Add(el);
                }
            }
            var widthHeightRatio = exportableVmToArgs.Value.WidthHeightRatio;

            // Then draw the items onto the image.
            var analysedImage = BitmapHelper.DrawFrameworkElementsOntoBitmap(
                drawnItems,
                BitmapHelper.BitmapImage2Bitmap(viewModel.CleanImageCopy),
                widthHeightRatio.Item1,
                widthHeightRatio.Item2);

            // Draw Image ============================================================================================================
            #region Setup and draw image
            //Create PDF graphics for a page
            PdfGraphics graphics = page.Graphics;

            // Draw name of the image.
            var subheaderFont     = new PdfStandardFont(PdfFontFamily.Courier, 14);
            var subheader         = viewModel.ImageName;
            var subheaderFontSize = subheaderFont.MeasureString(subheader);
            graphics.DrawString(subheader, subheaderFont, PdfBrushes.Black, new PointF(260 - subheaderFontSize.Width / 2, 0));

            //Draw the analysed image
            PdfBitmap pdfImage = new PdfBitmap(analysedImage);
            // Scale the picture right so its not uneven
            double widthHeightRate = (double)analysedImage.Width / (double)analysedImage.Height;
            float  height          = (float)(520 / widthHeightRate); // +10 because of the title we draw before it.
            graphics.DrawImage(pdfImage, 0, 20, 520, (int)height);   // max width of pdf: 520! Adjust the height accordingly.
            height += 20;
            #endregion

            // Draw Comments =========================================================================================================
            #region Draw comments
            // Draw the comments ====================================================================================
            // table
            var pdfGrid   = new PdfGrid();
            var dataTable = new DataTable();
            dataTable.Columns.Add("Comments");

            foreach (var comment in viewModel.Comments)
            {
                dataTable.Rows.Add(comment);
            }

            pdfGrid.DataSource       = dataTable;
            pdfGrid.Headers[0].Style = new PdfGridCellStyle()
            {
                BackgroundBrush = PdfBrushes.LightBlue
            };
            pdfGrid.Style.Font = new PdfStandardFont(PdfFontFamily.Courier, 10);

            // pdfGridLayout contains x,y,widht and height coordiantes of the drawn datatable!
            var pdfGridLayout = pdfGrid.Draw(page, new PointF(0, height + 10));
            height += pdfGridLayout.Bounds.Height;
            #endregion

            //Draw the metadata as a table ===========================================================================================
            #region Draw metadata
            // title first
            subheaderFont     = new PdfStandardFont(PdfFontFamily.Courier, 14);
            subheader         = "Metadata";
            subheaderFontSize = subheaderFont.MeasureString(subheader);
            height           += 10;
            graphics.DrawString(subheader, subheaderFont, PdfBrushes.Black, new PointF(260 - subheaderFontSize.Width / 2, height));

            // then table
            pdfGrid   = new PdfGrid();
            dataTable = new DataTable();
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Value");

            foreach (var pair in viewModel.Metadata)
            {
                dataTable.Rows.Add(pair.Key, pair.Value);
            }

            pdfGrid.DataSource       = dataTable;
            pdfGrid.Headers[0].Style = new PdfGridCellStyle()
            {
                BackgroundBrush = PdfBrushes.LightBlue
            };
            pdfGrid.Style.Font = new PdfStandardFont(PdfFontFamily.Courier, 10);

            // Keep track of the currently used height
            height += subheaderFontSize.Height + 10;
            // pdfGridLayout contains x,y,widht and height coordiantes of the drawn datatable!
            pdfGridLayout = pdfGrid.Draw(page, new PointF(0, height));
            #endregion

            //Draw the additonal information as a table ==============================================================================
            #region Draw Additional Information
            // title
            var pdfTextElement = new PdfTextElement("Additonal Information", new PdfStandardFont(PdfFontFamily.Courier, 14));
            subheaderFontSize = subheaderFont.MeasureString(pdfTextElement.Text);
            pdfTextElement.Draw(pdfGridLayout.Page, new PointF(260 - subheaderFontSize.Width / 2, pdfGridLayout.Bounds.Height + 10));

            dataTable = new DataTable();
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Value");
            foreach (var tuple in viewModel.AdditionalInformation)
            {
                dataTable.Rows.Add(tuple.Item1, tuple.Item2);
            }

            pdfGrid.DataSource       = dataTable;
            pdfGrid.Headers[0].Style = new PdfGridCellStyle()
            {
                BackgroundBrush = PdfBrushes.LightBlue
            };
            // Keep track of the currently used height
            pdfGridLayout = pdfGrid.Draw(pdfGridLayout.Page, new PointF(0, pdfGridLayout.Bounds.Height + 30));
            #endregion
        }
        public ActionResult BulletsLists(string InsideBrowser)
        {
            //Create a new PDf document
            PdfDocument document = new PdfDocument();

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

            //Create a unordered list
            PdfUnorderedList list = new PdfUnorderedList();

            //Set the marker style
            list.Marker.Style = PdfUnorderedMarkerStyle.Disk;

            //Create a font and write title
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);

            graphics.DrawString("List Features", font, PdfBrushes.DarkBlue, new PointF(225, 10));

            string[] products = { "Tools", "Grid", "Chart", "Edit", "Diagram", "XlsIO", "Grouping", "Calculate", "PDF", "HTMLUI", "DocIO" };
            string[] IO       = { "XlsIO", "PDF", "DocIO" };

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Regular);
            graphics.DrawString("This sample demonstrates various features of bullets and lists. A list can be ordered and Unordered. Essential PDF provides support for creating and formatting ordered and unordered lists.", font, PdfBrushes.Black, new RectangleF(0, 50, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));

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

            format.LineSpacing = 10f;

            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold);

            //Apply formattings to list
            list.Font         = font;
            list.StringFormat = format;

            //Set list indent
            list.Indent = 10;

            //Add items to the list
            list.Items.Add("List of Essential Studio products");
            list.Items.Add("IO products");

            //Set text indent
            list.TextIndent = 10;

            //Create Ordered list as sublist of parent list
            PdfOrderedList subList = new PdfOrderedList();

            subList.Marker.Brush  = PdfBrushes.Black;
            subList.Indent        = 20;
            list.Items[0].SubList = subList;

            //Set format for sub list
            font                 = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Italic);
            subList.Font         = font;
            subList.StringFormat = format;
            foreach (string s in products)
            {
                //Add items
                subList.Items.Add(string.Concat("Essential ", s));
            }

            //Create unorderd sublist for the second item of parent list
            PdfUnorderedList SubsubList = new PdfUnorderedList();

            SubsubList.Marker.Brush = PdfBrushes.Black;
            SubsubList.Indent       = 20;
            list.Items[1].SubList   = SubsubList;

            PdfImage image = PdfImage.FromFile(ResolveApplicationImagePath("syncfusion_logo.gif"));

            font                    = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Regular);
            SubsubList.Font         = font;
            SubsubList.StringFormat = format;

            //Add subitems
            SubsubList.Items.Add("Essential PDF: It is a .NET library with the capability to produce Adobe PDF files. It features a full-fledged object model for the easy creation of PDF files from any .NET language. It does not use any external libraries and is built from scratch in C#. It can be used on the server side (ASP.NET or any other environment) or with Windows Forms applications. Essential PDF supports many features for creating a PDF document. Drawing Text, Images, Shapes, etc can be drawn easily in the PDF document.");
            SubsubList.Items.Add("Essential DocIO: It is a .NET library that can read and write Microsoft Word files. It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Word installed. Here are some of the most common questions that arise regarding the usage and functionality of Essential DocIO.");
            SubsubList.Items.Add("Essential XlsIO: It is a .NET library that can read and write Microsoft Excel files (BIFF 8 format). It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Excel installed, making it an excellent reporting engine for tabular data. ");

            //Set image as marker
            SubsubList.Marker.Image = image;

            //Draw list
            list.Draw(page, new RectangleF(0, 130, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));

            //Stream the output to the browser.
            if (InsideBrowser == "Browser")
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
示例#18
0
        async private void btnShare_Clicked(object sender, EventArgs e)
        {
            var s             = sender as Xamarin.Forms.Button;
            var selectedOrder = s.BindingContext;
            var orderModel    = (OrderDetailForSearchViewModel)selectedOrder;
            int orderId       = orderModel.OrderId;

            var order = await SandoghcheController.GetConnection().Table <Order>().FirstOrDefaultAsync(o => o.OrderId == orderId);

            order.OrderDetails = await SandoghcheController.GetConnection().Table <OrderDetail>().Where(od => od.OrderId == orderModel.OrderId).ToListAsync();

            var products = await SandoghcheController.GetConnection().Table <Product>().ToListAsync();

            var client = await SandoghcheController.GetConnection().Table <Client>().FirstOrDefaultAsync(c => c.ClientId == order.ClientId);

            int rownum = 0;

            foreach (var item in order.OrderDetails)
            {
                rownum++;
                item.ProductText = products.FirstOrDefault(p => p.ProductId == item.ProductId).ProductText;
                item.RowNumber   = rownum;
            }

            List <orderDetailViewModel> orderDetails = new List <orderDetailViewModel>();

            foreach (var item in order.OrderDetails)
            {
                orderDetails.Add(new orderDetailViewModel {
                    RowNumber = item.RowNumber, ProductText = item.ProductText, Number = item.Number, Price = item.Price, TotalPrice = item.TotalPrice
                });
            }


            PdfDocument doc = new PdfDocument();

            doc.PageSettings.Size = new Syncfusion.Drawing.SizeF(300, 800);
            PdfMargins margins = new PdfMargins();

            margins.All = 10;
            doc.PageSettings.Margins = margins;
            PdfPage page = doc.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //var test = GetType().GetTypeInfo().Assembly.GetManifestResourceNames();
            Stream  fontStream = typeof(EditPage).GetTypeInfo().Assembly.GetManifestResourceStream("Sandoghche.Images.IRANSans(FaNum).ttf");
            PdfFont font       = new PdfTrueTypeFont(fontStream, 10);


            PdfStringFormat format = new PdfStringFormat();

            format.TextDirection = PdfTextDirection.RightToLeft;
            format.Alignment     = PdfTextAlignment.Center;

            PdfStringFormat format2 = new PdfStringFormat();

            format2.TextDirection = PdfTextDirection.RightToLeft;
            format2.Alignment     = PdfTextAlignment.Right;

            PdfStringFormat format3 = new PdfStringFormat();

            format3.TextDirection = PdfTextDirection.RightToLeft;
            format3.Alignment     = PdfTextAlignment.Left;


            graphics.DrawString(client.ClientName, font, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), format);
            graphics.DrawString("فاکتور فروش", font, PdfBrushes.Black, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, 40), new PointF(300, 40));
            graphics.DrawString("تاریخ :" + SandoghcheController.GetPersianDate(Convert.ToDateTime(order.DateCreated)), font, PdfBrushes.Black, new RectangleF(0, 42, page.GetClientSize().Width, page.GetClientSize().Height), format);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, 60), new PointF(300, 60));
            graphics.DrawString("ردیف عنوان                                    تعداد   قیمت واحد   قیمت کل          ", font, PdfBrushes.Black, new RectangleF(0, 60, page.GetClientSize().Width, page.GetClientSize().Height), format);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, 75), new PointF(300, 75));


            string source = "";
            int    length = 5;
            string result = source.PadRight(length).Substring(0, length);


            int height = 75;

            foreach (var item in order.OrderDetails)
            {
                string rowNumber   = item.RowNumber.ToString().PadLeft(5).Substring(0, 5);
                string productText = item.ProductText.PadRight(20).Substring(0, 20);
                string Number      = item.Number.ToString().PadLeft(5).Substring(0, 5);
                string Price       = item.Price.ToString().PadLeft(12).Substring(0, 12);
                string TotalPrice  = item.TotalPrice.ToString().PadLeft(12).Substring(0, 12);
                graphics.DrawString(rowNumber, font, PdfBrushes.Black, 285, height, format2);
                graphics.DrawString(productText, font, PdfBrushes.Black, 255, height, format2);
                graphics.DrawString(Number, font, PdfBrushes.Black, 130, height, format2);
                graphics.DrawString(Price, font, PdfBrushes.Black, 110, height, format2);
                graphics.DrawString(TotalPrice, font, PdfBrushes.Black, 55, height, format2);
                height += 15;
                graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(300, height));
                productText = "";
            }
            graphics.DrawString("مالیات : " + (order.Tax1 + order.Tax2).ToString(), font, PdfBrushes.Black, new RectangleF(0, height, page.GetClientSize().Width, page.GetClientSize().Height), format3);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(100, height));
            height += 15;
            graphics.DrawString("سرویس : " + order.TotalServiceFee.ToString(), font, PdfBrushes.Black, new RectangleF(0, height, page.GetClientSize().Width, page.GetClientSize().Height), format3);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(100, height));
            height += 15;
            graphics.DrawString("پیک : " + order.DeliveryFee.ToString(), font, PdfBrushes.Black, new RectangleF(0, height, page.GetClientSize().Width, page.GetClientSize().Height), format3);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(100, height));
            height += 15;
            graphics.DrawString‍("تخفیف : " + order.TotalDiscount.ToString(), font, PdfBrushes.Black, new RectangleF(0, height, page.GetClientSize().Width, page.GetClientSize().Height), format3);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(100, height));
            height += 15;
            graphics.DrawString‍("توضیحات : " + order.Comment, font, PdfBrushes.Black, new RectangleF(0, height, page.GetClientSize().Width, page.GetClientSize().Height), format3);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(100, height));
            height += 15;
            graphics.DrawString("جمع کل : " + order.FinalPayment.ToString(), font, PdfBrushes.Black, new RectangleF(0, height, page.GetClientSize().Width, page.GetClientSize().Height), format3);
            graphics.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, height), new PointF(300, height));


            MemoryStream stream = new MemoryStream();

            doc.Save(stream);
            byte[] test = stream.ToArray();
            doc.Close(true);


            var fn   = order.OrderId.ToString() + ".pdf";
            var file = Path.Combine(FileSystem.CacheDirectory, fn);

            File.WriteAllBytes(file, test);

            await Share.RequestAsync(new ShareFileRequest
            {
                Title = "فاکتور فروش",
                File  = new ShareFile(file)
            });


            // await Xamarin.Forms.DependencyService.Get<ISave>().Save(order.OrderId.ToString(), "application/pdf", stream);
        }
示例#19
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);
        }
示例#20
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(PdfExport).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]
#if !NETCORE
                System.Diagnostics.Process.Start("Invoice.pdf");
#else
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName        = "cmd",
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                    CreateNoWindow  = true,
                    Arguments       = "/c start Invoice.pdf"
                };
                Process.Start(psi);
#endif
                //this.Close();
            }
            //else
            // Exit
            //this.Close();

            document.Close(true);
        }
示例#21
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;

            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 20f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;
            PdfForm         form  = document.Form;

            //Document security
            PdfSecurity security = document.Security;

            //Specify key size and encryption algorithm
            if (rdButton40Bit.Checked)
            {
                //use 40 bits key in RC4 mode
                security.KeySize = PdfEncryptionKeySize.Key40Bit;
            }
            else if (rdButton128Bit.Checked && rdButtonRC4.Checked)
            {
                //use 128 bits key in RC4 mode
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
            }
            else if (rdButton128Bit.Checked && rdButtonAES.Checked)
            {
                //use 128 bits key in AES mode
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (rdButton256Bit.Checked)
            {
                //use 256 bits key in AES mode
                security.KeySize   = PdfEncryptionKeySize.Key256Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (rdButton256BitRevision6.Checked)
            {
                security.KeySize   = PdfEncryptionKeySize.Key256BitRevision6;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            if (cmbEncrypt.SelectedIndex == 0 || !cmbEncrypt.Enabled)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (cmbEncrypt.SelectedIndex == 1)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (cmbEncrypt.SelectedIndex == 2)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
                //Read the file
                FileStream file = new FileStream(GetFullTemplatePath("Products.xml", false), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                //Creates an attachment
                PdfAttachment attachment = new PdfAttachment("Products.xml", file);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);
            }

            security.OwnerPassword = "******";
            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = "******";

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);

            if (rdButton256BitRevision6.Checked)
            {
                text += String.Format("\n\nRevision: {0}", "Revision6");
            }
            else if (rdButton256Bit.Checked)
            {
                text += String.Format("\n\nRevision: {0}", "Revision5");
            }

            graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new PointF(0, 40));

            document.Save("Sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                System.Diagnostics.Process.Start("Sample.pdf");
#endif
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
示例#22
0
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream BulletsAndListPDF()
        {
            //Create a new Pdf document
            PdfDocument document = new PdfDocument();

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

            //Create a unordered list
            PdfUnorderedList list = new PdfUnorderedList();

            //Set the marker style
            list.Marker.Style = PdfUnorderedMarkerStyle.Disk;

            //Create a font and write title
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);

            graphics.DrawString("List Features", font, PdfBrushes.DarkBlue, new PointF(225, 10));

            string[] products = { "Tools", "Grid", "Chart", "Edit", "Diagram", "XlsIO", "Grouping", "Calculate", "PDF", "HTMLUI", "DocIO" };
            string[] IO       = { "XlsIO", "PDF", "DocIO" };

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Regular);
            graphics.DrawString("This sample demonstrates various features of bullets and lists. A list can be ordered and Unordered. Essential PDF provides support for creating and formatting ordered and unordered lists.", font, PdfBrushes.Black, new RectangleF(0, 50, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));

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

            format.LineSpacing = 10f;

            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold);

            //Apply formattings to list
            list.Font         = font;
            list.StringFormat = format;

            //Set list indent
            list.Indent = 10;

            //Add items to the list
            list.Items.Add("List of Essential Studio products");
            list.Items.Add("IO products");

            //Set text indent
            list.TextIndent = 10;

            //Create Ordered list as sublist of parent list
            PdfOrderedList subList = new PdfOrderedList();

            subList.Marker.Brush  = PdfBrushes.Black;
            subList.Indent        = 20;
            list.Items[0].SubList = subList;

            //Set format for sub list
            font                 = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Italic);
            subList.Font         = font;
            subList.StringFormat = format;
            foreach (string s in products)
            {
                //Add items
                subList.Items.Add(string.Concat("Essential ", s));
            }

            //Create unorderd sublist for the second item of parent list
            PdfUnorderedList SubsubList = new PdfUnorderedList();

            SubsubList.Marker.Brush = PdfBrushes.Black;
            SubsubList.Indent       = 20;
            list.Items[1].SubList   = SubsubList;

            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";

            //Read the file
            FileStream file = new FileStream(ResolveApplicationPath("logo.png"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            PdfImage image = PdfImage.FromStream(file);

            font                    = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Regular);
            SubsubList.Font         = font;
            SubsubList.StringFormat = format;

            //Add sub items
            SubsubList.Items.Add("Essential PDF: It is a .NET library with the capability to produce Adobe PDF files. It features a full-fledged object model for the easy creation of PDF files from any .NET language. It does not use any external libraries and is built from scratch in C#. It can be used on the server side (ASP.NET or any other environment) or with Windows Forms applications. Essential PDF supports many features for creating a PDF document. Drawing Text, Images, Shapes, etc can be drawn easily in the PDF document.");
            SubsubList.Items.Add("Essential DocIO: It is a .NET library that can read and write Microsoft Word files. It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Word installed. Here are some of the most common questions that arise regarding the usage and functionality of Essential DocIO.");
            SubsubList.Items.Add("Essential XlsIO: It is a .NET library that can read and write Microsoft Excel files (BIFF 8 format). It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Excel installed, making it an excellent reporting engine for tabular data. ");

            //Set image as marker
            SubsubList.Marker.Image = image;

            //Draw list
            list.Draw(page, new RectangleF(0, 130, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height));

            //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);
            return(ms);
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            // Create a new instance of PdfDocument class.
            PdfDocument document = new PdfDocument();

            // Add a new page to the newly created document.
            PdfPage page = document.Pages.Add();

            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);

            PdfGraphics g = page.Graphics;

            g.DrawString("JPEG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 40));

            //Load JPEG image to stream.
#if COMMONSB
            Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Xamarin_JPEG.jpg");
#else
            Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Xamarin_JPEG.jpg");
#endif

            //Load the JPEG image
            PdfImage jpgImage = new PdfBitmap(jpgImageStream);

            //Draw the JPEG image
            g.DrawImage(jpgImage, new Syncfusion.Drawing.RectangleF(0, 70, 515, 215));

            g.DrawString("PNG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 355));

            //Load PNG image to stream.
#if COMMONSB
            Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Xamarin_PNG.png");
#else
            Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Xamarin_PNG.png");
#endif

            //Load the PNG image
            PdfImage pngImage = new PdfBitmap(pngImageStream);

            //Draw the PNG image
            g.DrawImage(pngImage, new Syncfusion.Drawing.RectangleF(0, 365, 199, 300));

            MemoryStream stream = new MemoryStream();

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

            stream.Position = 0;

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

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("ImageInsertion.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("ImageInsertion.pdf", "application/pdf", stream);
            }
        }
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            //Create a new instance of PdfDocument class.
            doc = new PdfDocument();
            //Add a new page to the document.
            page = doc.Pages.Add();
            PdfGraphics graphics = page.Graphics;
            SizeF       sizef    = page.Graphics.ClientSize;

            //Create an unordered list
            PdfUnorderedList list = new PdfUnorderedList();

            //Set the marker style
            list.Marker.Style = PdfUnorderedMarkerStyle.Disk;

            //Create font and write title
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);

            graphics.DrawString("List Features", font, PdfBrushes.DarkBlue, new PointF(225, 10));

            string[] products = { "Tools", "Grid", "Chart", "Edit", "Diagram", "XlsIO", "Grouping", "Calculate", "PDF", "HTMLUI", "DocIO" };
            string[] IO       = { "XlsIO", "PDF", "DocIO" };

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Regular);
            graphics.DrawString("This sample demonstrates various features of bullets and lists. A list can be ordered and unordered. Essential PDF provides support for creating and formatting ordered and unordered lists.", font, PdfBrushes.Black, new RectangleF(0, 50, sizef.Width, sizef.Height));

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

            format.LineSpacing = 10f;

            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold);

            // Format list
            list.Font         = font;
            list.StringFormat = format;

            //Set list indent
            list.Indent = 10;

            //Add items to the list
            list.Items.Add("List of Essential Studio products");
            list.Items.Add("IO products");

            //Set text indent
            list.TextIndent = 10;

            //Create Ordered list as sublist of parent list
            PdfOrderedList subList = new PdfOrderedList();

            subList.Marker.Brush  = PdfBrushes.Black;
            subList.Indent        = 20;
            list.Items[0].SubList = subList;

            //Set format for sub list
            font                 = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Italic);
            subList.Font         = font;
            subList.StringFormat = format;
            foreach (string s in products)
            {
                //Add items
                subList.Items.Add(string.Concat("Essential ", s));
            }

            //Create unorderd sublist for the second item of parent list
            PdfUnorderedList SubsubList = new PdfUnorderedList();

            SubsubList.Marker.Brush = PdfBrushes.Black;
            SubsubList.Indent       = 20;
            list.Items[1].SubList   = SubsubList;

            Stream pngImage = typeof(BulletsAndLists).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.syncfusion_logo.png");

            font                    = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Regular);
            SubsubList.Font         = font;
            SubsubList.StringFormat = format;

            //Add subitems
            SubsubList.Items.Add("Essential PDF: It is a .NET library with the capability to produce Adobe PDF files. It features a full-fledged object model for the easy creation of PDF files from any .NET language. It does not use any external libraries and is built from scratch in C#. It can be used on the server side (ASP.NET or any other environment) or with Windows Forms applications. Essential PDF supports many features for creating a PDF document. Drawing Text, Images, Shapes, etc can be drawn easily in the PDF document.");
            SubsubList.Items.Add("Essential DocIO: It is a .NET library that can read and write Microsoft Word files. It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Word installed. Here are some of the most common questions that arise regarding the usage and functionality of Essential DocIO.");
            SubsubList.Items.Add("Essential XlsIO: It is a .NET library that can read and write Microsoft Excel files (BIFF 8 format). It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Excel installed, making it an excellent reporting engine for tabular data. ");

            //convert to PdfImage
            PdfImage image = new PdfBitmap(pngImage);

            //Set image as marker
            SubsubList.Marker.Image = image;

            //Draw list
            list.Draw(page, new RectangleF(0, 130, sizef.Width, sizef.Height));

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

            doc.Close(true);
            Save(stream, "BulletsAndLists.pdf");
        }
示例#25
0
        //invoice
        private void btnGenerateInvoice_Click(object sender, RoutedEventArgs e)
        {
            SelectedSalesOrder = lvSalesOrders.SelectedItem as SalesOrder;

            if (SelectedSalesOrder != null)
            {
                Invoice invoice = new Invoice()
                {
                    SalesOrder = SelectedSalesOrder,
                    Date       = DateTime.Now,
                    Paid       = SelectedSalesOrder.Paid
                };


                //create pdf invoice
                using (PdfDocument document = new PdfDocument())
                {
                    PdfPage page = document.Pages.Add();

                    PdfGraphics graphics = page.Graphics;

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

                    PdfImage image = PdfImage.FromFile("../../Images/coolblue_banner.jpg");

                    graphics.DrawImage(image, 0, 0, 300, 100);

                    graphics.DrawString("Order Invoice", font, PdfBrushes.Black, new PointF(0, 100));

                    graphics.DrawString("Reference Number: " + SelectedSalesOrder.SalesOrderId.ToString(), font, PdfBrushes.Black, new PointF(0, 120));

                    graphics.DrawString("Date: " + SelectedSalesOrder.OrderDate.ToString(), font, PdfBrushes.Black, new PointF(0, 140));

                    graphics.DrawString("Total: £" + SelectedSalesOrder.TotalPrice.ToString(), font, PdfBrushes.Black, new PointF(0, 160));
                    graphics.DrawString("BTW: £" + UtilityClass.BTW(SelectedSalesOrder.TotalPrice).ToString(), font, PdfBrushes.Black, new PointF(100, 160));
                    graphics.DrawString("Total (inc BTW): £" + UtilityClass.PriceWithBTW(SelectedSalesOrder.TotalPrice).ToString(), font, PdfBrushes.Black, new PointF(200, 160));

                    PdfGrid pdfGrid = new PdfGrid();

                    DataTable datatable = new DataTable();

                    datatable.Columns.Add("Product");
                    datatable.Columns.Add("Description");
                    datatable.Columns.Add("Quantity");
                    datatable.Columns.Add("Price");


                    //grouped products for invoice
                    var groupedProducts = SelectedSalesOrder.SalesOrderProducts.GroupBy(product => product.Product.Name);

                    //create 1 row for each group of products
                    foreach (var group in groupedProducts)
                    {
                        datatable.Rows.Add(new Object[] { group.Key, group.First().Product.Description, group.Count().ToString(), (group.First().Product.Price *group.Count()).ToString() });
                    }

                    pdfGrid.DataSource = datatable;
                    pdfGrid.Draw(page, new PointF(0, 200));



                    //allow user to select where to save document-  savefiledialog
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter       = "Files(*.pdf)|*.pdf";
                    saveFileDialog.AddExtension = true;
                    saveFileDialog.DefaultExt   = ".pdf";

                    if (saveFileDialog.ShowDialog() == true && saveFileDialog.CheckPathExists)
                    {
                        document.Save(saveFileDialog.FileName);
                        document.Close();

                        MessageBoxResult result = MessageBox.Show("Do you want to view the invoice?", "Invoice Created", MessageBoxButton.YesNo, MessageBoxImage.Information);
                        if (result == MessageBoxResult.Yes)
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = saveFileDialog.FileName;
                            process.Start();
                        }
                    }
                }
            }
            else
            {
                MessageNotSelected();
            }
        }
        public ActionResult DocumentSettings(string InsideBrowser)
        {
            //Create a new PDF Document. The pdfDoc object represents the PDF document.
            //This document has one page by default and additional pages have to be added.
            PdfDocument pdfDoc = new PdfDocument();
            PdfPage     page   = pdfDoc.Pages.Add();

            // Get xmp object.
            XmpMetadata xmp = pdfDoc.DocumentInformation.XmpMetadata;

            // XMP Basic Schema.
            BasicSchema basic = xmp.BasicSchema;

            basic.Advisory.Add("advisory");
            basic.BaseURL     = new Uri("http://google.com");
            basic.CreateDate  = DateTime.Now;
            basic.CreatorTool = "creator tool";
            basic.Identifier.Add("identifier");
            basic.Label        = "label";
            basic.MetadataDate = DateTime.Now;
            basic.ModifyDate   = DateTime.Now;
            basic.Nickname     = "nickname";
            basic.Rating.Add(-25);

            //Setting various Document properties.
            pdfDoc.DocumentInformation.Title        = "Document Properties Information";
            pdfDoc.DocumentInformation.Author       = "Syncfusion";
            pdfDoc.DocumentInformation.Keywords     = "PDF";
            pdfDoc.DocumentInformation.Subject      = "PDF demo";
            pdfDoc.DocumentInformation.Producer     = "Syncfusion Software";
            pdfDoc.DocumentInformation.CreationDate = DateTime.Now;

            PdfFont  font     = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            PdfFont  boldFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            PdfBrush brush    = PdfBrushes.Black;

            PdfGraphics     g      = page.Graphics;
            PdfStringFormat format = new PdfStringFormat();

            format.LineSpacing = 10f;

            g.DrawString("Press Ctrl+D to see Document Properties", boldFont, brush, 10, 10);
            g.DrawString("Basic Schema Xml:", boldFont, brush, 10, 50);
            g.DrawString(basic.XmlData.OuterXml, font, brush, new RectangleF(10, 70, 500, 500), format);

            //Defines and set values for Custom metadata and add them to the Pdf document
            CustomSchema custom = new CustomSchema(xmp, "custom", "//www.syncfusion.com/");

            custom["Company"] = "Syncfusion";
            custom["Website"] = "//www.syncfusion.com/";
            custom["Product"] = "Essential PDF";

            //Stream the output to the browser.
            if (InsideBrowser == "Browser")
            {
                return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
示例#27
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);
        }
示例#28
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");
        }
        /// <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);
        }
示例#30
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Stream jpegImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Autumn Leaves.jpg");
            Stream pngImage  = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.syncfusion_logo.png");

#if STORE_SB
            Stream tiffImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.image.tif");
#else
            Stream tiffImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.image.tiff");
#endif
            Stream gifImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Ani.gif");


            // Create a new instance of PdfDocument class.
            PdfDocument document = new PdfDocument();

            // Set font.
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 22, PdfFontStyle.Bold);

            // Create brush.
            PdfBrush textBrush = PdfBrushes.DarkBlue;

            #region Jpeg image
            // Add a new section to the document.
            PdfSection section = document.Sections.Add();
            // Add a new page to the newly created section.
            PdfPage     page = section.Pages.Add();
            PdfGraphics g    = page.Graphics;

            g.DrawString("JPEG Image Drawing", font, textBrush, new PointF(10, 0));

            //Drawing a jpeg image
            PdfImage image = new PdfBitmap(jpegImage);
            g.DrawImage(image, 0, 30);

            #endregion

            #region PNG Image
            page = section.Pages.Add();
            g    = page.Graphics;
            g.DrawString("PNG Image drawing", font, textBrush, new PointF(10, 0));

            image = new PdfBitmap(pngImage);

            g.DrawImage(image, 0, 30);
            #endregion

            #region Multiframe Tiff
            PdfBitmap multiFrameImage = new PdfBitmap(tiffImage);

            int frameCount = multiFrameImage.FrameCount;

            for (int i = 0; i < frameCount; i++)
            {
                // Every frame in a new page.
                page = section.Pages.Add();
                section.PageSettings.Margins.All = 0;
                g = page.Graphics;

                // Set the acive frame.
                multiFrameImage.ActiveFrame = i;

                // Draw active frame.
                g.DrawImage(multiFrameImage, 0, 0, page.Size.Width, page.Size.Height);

                if (i == 0)
                {
#if STORE_SB
                    g.DrawString("Tiff Image", font, textBrush, new PointF(10, 10));
#else
                    g.DrawString("Multiframe Tiff Image", font, textBrush, new PointF(10, 10));
#endif
                }
            }
            #endregion
            #region Gif
            page = section.Pages.Add();
            g    = page.Graphics;

            // Draw gif image.
            image = new PdfBitmap(gifImage);
            g.DrawImage(image, 0, 0, g.ClientSize.Width, image.Height);

            g.DrawString("Gif Image", font, textBrush, new PointF(10, 0));

            #endregion

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

            document.Close(true);
            Save(stream, "Sample.pdf");
        }