static SizeF PrepareGraphics(PdfPage page, PdfGraphics graphics)
        {
            PdfRectangle cropBox       = page.CropBox;
            float        cropBoxWidth  = (float)cropBox.Width;
            float        cropBoxHeight = (float)cropBox.Height;

            switch (page.Rotate)
            {
            case 90:
                graphics.RotateTransform(-90);
                graphics.TranslateTransform(-cropBoxHeight, 0);
                return(new SizeF(cropBoxHeight, cropBoxWidth));

            case 180:
                graphics.RotateTransform(-180);
                graphics.TranslateTransform(-cropBoxWidth, -cropBoxHeight);
                return(new SizeF(cropBoxWidth, cropBoxHeight));

            case 270:
                graphics.RotateTransform(-270);
                graphics.TranslateTransform(0, -cropBoxWidth);
                return(new SizeF(cropBoxHeight, cropBoxWidth));
            }
            return(new SizeF(cropBoxWidth, cropBoxHeight));
        }
예제 #2
0
            public void DrawBandHead()
            {
                pPen.Width = 1;
                pdfGC.DrawLine(pPen, (float)BandTopLeftLocation.X, (float)BandTopLeftLocation.Y, (float)BandTopLeftLocation.X, (float)(BandTopLeftLocation.Y + BandHight));

                pdfGC.DrawLine(pPen, (float)BandTopLeftLocation.X, (float)(BandTopLeftLocation.Y + BandHight), (float)(BandTopLeftLocation.X - BandHeadWidth), (float)(BandTopLeftLocation.Y + BandHight));
                pdfGC.DrawLine(pPen, (float)(BandTopLeftLocation.X - BandHeadWidth), (float)(BandTopLeftLocation.Y + BandHight), (float)(BandTopLeftLocation.X - BandHeadWidth), (float)BandTopLeftLocation.Y);

                pdfGC.DrawLine(pPen, (float)(BandTopLeftLocation.X - BandHeadWidth), (float)BandTopLeftLocation.Y, (float)BandTopLeftLocation.X, (float)BandTopLeftLocation.Y);

                //  RectangleF rF = new RectangleF((float)(BandTopLeftLocation.X - BandHeadWidth), (float)(BandTopLeftLocation.Y), (float)BandHeadWidth, (float)BandHight);
                RectangleF rF = new RectangleF(0, 0, (float)BandHight, (float)BandHeadWidth);

                PdfStringFormat psf = new PdfStringFormat(PdfStringFormat.GenericDefault);

                psf.Alignment     = PdfStringAlignment.Center;
                psf.LineAlignment = PdfStringAlignment.Center;
                // pdfGC.DrawString(BandName, textfont, Brushes.Black, rF, psf);

                pdfGC.SaveGraphicsState();
                // head box 的左下角
                pdfGC.TranslateTransform((float)(BandTopLeftLocation.X - BandHeadWidth), (float)(BandTopLeftLocation.Y + BandHight));
                pdfGC.RotateTransform(270);
                pdfGC.DrawString(BandName, headFont, new SolidBrush(Color.Black), rF, psf);
                pdfGC.RestoreGraphicsState();
            }
예제 #3
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Stream            docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Product Catalog.pdf");
            PdfLoadedDocument ldoc      = new PdfLoadedDocument(docStream);

            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular);

            foreach (PdfPageBase lPage in ldoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.TranslateTransform(ldoc.Pages[0].Size.Width / 2, ldoc.Pages[0].Size.Height / 2);
                g.SetTransparency(0.25f);
                SizeF waterMarkSize = font.MeasureString("Sample");
                g.RotateTransform(-40);
                g.DrawString("Sample", font, PdfPens.Red, PdfBrushes.Red, new PointF(-waterMarkSize.Width / 2, -waterMarkSize.Height / 2));
                g.Restore(state);
            }
            MemoryStream stream = new MemoryStream();

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

            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save("Stamping.pdf", "application/pdf", stream, m_context);
            }
        }
예제 #4
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Stream            docStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Syncfusion_Windows8_whitepaper.pdf");
            PdfLoadedDocument ldoc      = new PdfLoadedDocument(docStream);

            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular);

            foreach (PdfPageBase lPage in ldoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.SetTransparency(0.25f);
                g.TranslateTransform(50, lPage.Size.Height / 2);
                g.RotateTransform(-40);
                g.DrawString("Syncfusion", font, PdfPens.Red, PdfBrushes.Red, new PointF(0, 0));
                g.Restore(state);
            }
            MemoryStream stream = new MemoryStream();

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

            if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("Stamping.pdf", "application/pdf", stream);
            }
        }
        private async void StampingSample()
        {
            //Load PDF document to stream.
            Stream docStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Syncfusion_Windows8_whitepaper.pdf");

            MemoryStream stream = new MemoryStream();

            //Load the PDF document into the loaded document object.
            using (PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream))
            {
                //Create font object.
                PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular);

                //Stamp or watermark on all the pages.
                foreach (PdfPageBase lPage in ldoc.Pages)
                {
                    PdfGraphics      g     = lPage.Graphics;
                    PdfGraphicsState state = g.Save();
                    g.SetTransparency(0.25f);
                    g.TranslateTransform(50, lPage.Size.Height / 2);
                    g.RotateTransform(-40);
                    g.DrawString("Syncfusion", font, PdfPens.Red, PdfBrushes.Red, new PointF(0, 0));
                    g.Restore(state);
                }

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

            stream.Position = 0;

            if (IsToggled)
            {
                //Open in Essential PDF viewer.
                PdfViewerUI pdfViewer = new SampleBrowser.PdfViewerUI();
                pdfViewer.PdfDocumentStream = stream;
                if (Device.Idiom != TargetIdiom.Phone && Device.OS == TargetPlatform.Windows)
                {
                    await PDFViewModel.Navigation.PushModalAsync(new NavigationPage(pdfViewer));
                }
                else
                {
                    await PDFViewModel.Navigation.PushAsync(pdfViewer);
                }
            }
            else
            {
                //Open in default system viewer.
                if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                {
                    Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream);
                }
                else
                {
                    Xamarin.Forms.DependencyService.Get <ISave>().Save("Stamping.pdf", "application/pdf", stream);
                }
            }
        }
예제 #6
0
        public void AddWatermark(string text, string fileName, string resultFileName)
        {
            using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor())
            {
                string          fontName     = "Arial Black";
                int             fontSize     = 12;
                PdfStringFormat stringFormat = PdfStringFormat.GenericTypographic;
                stringFormat.Alignment     = PdfStringAlignment.Center;
                stringFormat.LineAlignment = PdfStringAlignment.Center;
                documentProcessor.LoadDocument(fileName);
                using (SolidBrush brush = new SolidBrush(Color.FromArgb(63, Color.Black)))
                {
                    using (Font font = new Font(fontName, fontSize))
                    {
                        foreach (var page in documentProcessor.Document.Pages)
                        {
                            var watermarkSize = page.CropBox.Width * 0.75;
                            using (PdfGraphics graphics = documentProcessor.CreateGraphics())
                            {
                                SizeF  stringSize = graphics.MeasureString(text, font);
                                Single scale      = Convert.ToSingle(watermarkSize / stringSize.Width);
                                graphics.TranslateTransform(Convert.ToSingle(page.CropBox.Width * 0.5), Convert.ToSingle(page.CropBox.Height * 0.5));
                                graphics.RotateTransform(-45);
                                graphics.TranslateTransform(Convert.ToSingle(-stringSize.Width * scale * 0.5), Convert.ToSingle(-stringSize.Height * scale * 0.5));
                                using (Font actualFont = new Font(fontName, fontSize * scale))
                                {
                                    RectangleF rect = new RectangleF(0, 0, stringSize.Width * scale, stringSize.Height * scale);
                                    graphics.DrawString(text, actualFont, brush, rect, stringFormat);
                                }

                                graphics.AddToPageForeground(page, 72, 72);
                            }
                        }
                    }
                }

                documentProcessor.SaveDocument(resultFileName);
            }
        }
예제 #7
0
        public MemoryStream CreatePdfDocument(CbTransH trans)
        {
            string Title   = "BUKTI KAS/BANK";
            string Tanggal = "Tanggal";
            string NoDoc   = "No.";


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

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

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

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

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

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

            document.Save(ms);
            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;
            return(ms);
        }
예제 #8
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Load PDF document to stream.
#if COMMONSB
            Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Product Catalog.pdf");
#else
            Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Product Catalog.pdf");
#endif

            //Load the PDF document into the loaded document object.
            PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream);

            //Create font object.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular);

            //Stamp or watermark on all the pages.
            foreach (PdfPageBase lPage in ldoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.TranslateTransform(ldoc.Pages[0].Size.Width / 2, ldoc.Pages[0].Size.Height / 2);
                g.SetTransparency(0.25f);
                SizeF waterMarkSize = font.MeasureString("Sample");
                g.RotateTransform(-40);
                g.DrawString("Sample", font, PdfPens.Red, PdfBrushes.Red, new PointF(-waterMarkSize.Width / 2, -waterMarkSize.Height / 2));
                g.Restore(state);
            }
            MemoryStream stream = new MemoryStream();

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

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

            //Open in default system viewer.
            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("Stamping.pdf", "application/pdf", stream);
            }
        }
예제 #9
0
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream LayersPDF()
        {
            //Create a new PDF document
            PdfDocument doc = new PdfDocument();

            doc.PageSettings = new PdfPageSettings(new SizeF(350, 300));

            PdfPage page = doc.Pages.Add();

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

            page.Graphics.DrawString("Layers", font, PdfBrushes.DarkBlue, new PointF(150, 10));

            //Add the first layer
            PdfPageLayer layer = page.Layers.Add("Layer1");

            PdfGraphics graphics = layer.Graphics;

            graphics.TranslateTransform(100, 60);

            //Draw Arc
            PdfPen     pen  = new PdfPen(Color.Red, 50);
            RectangleF rect = new RectangleF(0, 0, 50, 50);

            graphics.DrawArc(pen, rect, 360, 360);

            pen = new PdfPen(Color.Blue, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            pen = new PdfPen(Color.Yellow, 20);
            graphics.DrawArc(pen, rect, 360, 360);

            pen = new PdfPen(Color.Green, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            //Add another layer on the page
            layer = page.Layers.Add("Layer2");

            graphics = layer.Graphics;
            graphics.TranslateTransform(100, 180);
            graphics.SkewTransform(0, 50);

            //Draw another set of elements
            pen = new PdfPen(Color.Red, 50);
            graphics.DrawArc(pen, rect, 360, 360);
            pen = new PdfPen(Color.Blue, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);
            pen = new PdfPen(Color.Yellow, 20);
            graphics.DrawArc(pen, rect, 360, 360);
            pen = new PdfPen(Color.Green, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            //Add another layer
            layer    = page.Layers.Add("Layer3");
            graphics = layer.Graphics;
            graphics.TranslateTransform(160, 120);

            //Draw another set of elements.
            pen = new PdfPen(Color.Red, 50);
            graphics.DrawArc(pen, rect, -60, 60);
            pen = new PdfPen(Color.Blue, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60);
            pen = new PdfPen(Color.Yellow, 20);
            graphics.DrawArc(pen, rect, -60, 60);
            pen = new PdfPen(Color.Green, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60);

            MemoryStream stream = new MemoryStream();

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

            stream.Position = 0;

            //Close the PDF document
            doc.Close(true);
            return(stream);
        }
예제 #10
0
        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);
            }
        }
예제 #11
0
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            //Create a new instance of PdfDocument class.
            doc = new PdfDocument();

            // Set page size.
            doc.PageSettings = new PdfPageSettings(new SizeF(350, 300));

            // Add a new page to the document.
            page = doc.Pages.Add();

            page.Graphics.DrawString("Layers", new PdfStandardFont(PdfFontFamily.Helvetica, 16), PdfBrushes.DarkBlue, new PointF(150, 10));

            //Add first layer
            PdfPageLayer layer = page.Layers.Add("Layer1");

            PdfGraphics graphics = layer.Graphics;

            graphics.TranslateTransform(100, 60);

            //Draw Arc
            PdfPen     pen  = new PdfPen(redColor, 50);
            RectangleF rect = new RectangleF(0, 0, 50, 50);

            graphics.DrawArc(pen, rect, 360, 360);

            pen = new PdfPen(blueColor, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            pen = new PdfPen(yellowColor, 20);
            graphics.DrawArc(pen, rect, 360, 360);

            pen = new PdfPen(greenColor, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            //Add another layer on the page
            layer = page.Layers.Add("Layer2");

            graphics = layer.Graphics;
            graphics.TranslateTransform(100, 180);

            //Draw another set of elements
            pen = new PdfPen(redColor, 50);
            graphics.DrawArc(pen, rect, 360, 360);
            pen = new PdfPen(blueColor, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);
            pen = new PdfPen(yellowColor, 20);
            graphics.DrawArc(pen, rect, 360, 360);
            pen = new PdfPen(greenColor, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            //Add third layer.
            layer    = page.Layers.Add("Layer3");
            graphics = layer.Graphics;
            graphics.TranslateTransform(160, 120);

            //Draw another set of elements.
            pen = new PdfPen(redColor, 50);
            graphics.DrawArc(pen, rect, -60, 60);
            pen = new PdfPen(blueColor, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60);
            pen = new PdfPen(yellowColor, 20);
            graphics.DrawArc(pen, rect, -60, 60);
            pen = new PdfPen(greenColor, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60);

            // Save and close the document.
            MemoryStream stream = new MemoryStream();
            await doc.SaveAsync(stream);

            doc.Close(true);
            Save(stream, "Layers.pdf");
        }
        public ActionResult Layers(string InsideBrowser)
        {
            //Create a new PDF document
            PdfDocument doc = new PdfDocument();

            doc.PageSettings = new PdfPageSettings(new SizeF(350, 300));

            PdfPage page = doc.Pages.Add();

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

            page.Graphics.DrawString("Layers", font, PdfBrushes.DarkBlue, new PointF(150, 10));

            //Add the first layer
            PdfPageLayer layer = page.Layers.Add("Layer1");

            PdfGraphics graphics = layer.Graphics;

            graphics.TranslateTransform(100, 60);

            //Draw Arc
            PdfPen     pen  = new PdfPen(Color.Red, 50);
            RectangleF rect = new RectangleF(0, 0, 50, 50);

            graphics.DrawArc(pen, rect, 360, 360);

            pen = new PdfPen(Color.Blue, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            pen = new PdfPen(Color.Yellow, 20);
            graphics.DrawArc(pen, rect, 360, 360);

            pen = new PdfPen(Color.Green, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            //Add another layer on the page
            layer = page.Layers.Add("Layer2");

            graphics = layer.Graphics;
            graphics.TranslateTransform(100, 180);
            graphics.SkewTransform(0, 50);

            //Draw another set of elements
            pen = new PdfPen(Color.Red, 50);
            graphics.DrawArc(pen, rect, 360, 360);
            pen = new PdfPen(Color.Blue, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);
            pen = new PdfPen(Color.Yellow, 20);
            graphics.DrawArc(pen, rect, 360, 360);
            pen = new PdfPen(Color.Green, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360);

            //Add another layer
            layer    = page.Layers.Add("Layer3");
            graphics = layer.Graphics;
            graphics.TranslateTransform(160, 120);

            //Draw another set of elements.
            pen = new PdfPen(Color.Red, 50);
            graphics.DrawArc(pen, rect, -60, 60);
            pen = new PdfPen(Color.Blue, 30);
            graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60);
            pen = new PdfPen(Color.Yellow, 20);
            graphics.DrawArc(pen, rect, -60, 60);
            pen = new PdfPen(Color.Green, 10);
            graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60);

            //Stream the output to the browser.
            if (InsideBrowser == "Browser")
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
예제 #13
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
        }