示例#1
0
    /// <summary>
    /// Parses image align from string value.
    /// </summary>
    /// <param name="align">Value to parse</param>
    /// <returns>Align of an image</returns>
    private static ImageAlign ParseImageAlign(string align)
    {
        ImageAlign imageAlign = default(ImageAlign);

        if (align != null)
        {
            try
            {
                // Try to get image align
                imageAlign = (ImageAlign)Enum.Parse(typeof(ImageAlign), align);

                // RTL switch
                if (CultureHelper.IsUICultureRTL())
                {
                    if (imageAlign == ImageAlign.Left)
                    {
                        imageAlign = ImageAlign.Right;
                    }
                    else if (imageAlign == ImageAlign.Right)
                    {
                        imageAlign = ImageAlign.Left;
                    }
                }
            }
            catch
            {
                imageAlign = ImageAlign.NotSet;
            }
        }
        else
        {
            imageAlign = ImageAlign.NotSet;
        }
        return(imageAlign);
    }
示例#2
0
        /// <summary>
        /// Control constructor.
        /// </summary>
        /// <param name="parent">Parent control.</param>
        public Button(ControlBase parent)
            : base(parent)
        {
            Alignment = Alignment.Center;
            TextPadding = new Padding(3, 3, 3, 3);
			m_ImageAlign = ImageAlign.LeftSide;
        }
示例#3
0
        /// <include file='doc\Image.uex' path='docs/doc[@for="Image.AddAttributesToRender"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// <para>Adds the attributes of an <see cref='System.Web.UI.WebControls.Image'/> to the output stream for rendering on
        ///    the client.</para>
        /// </devdoc>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);

            string s = ImageUrl;

            if (s.Length > 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveClientUrl(s));
            }
            s = AlternateText;
            if (s.Length > 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Alt, s);
            }

            ImageAlign align = ImageAlign;

            if (align != ImageAlign.NotSet)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Align, Enum.Format(typeof(ImageAlign), align, "G"));
            }

            if (BorderWidth.IsEmpty)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
            }
        }
示例#4
0
        internal static ImageAlign ConvertImageAlignment(string alignment)
        {
            ImageAlign align = ImageAlign.None;

            switch (alignment)
            {
            case "TopCenter":
                return(ImageAlign.Top_Center);

            case "TopLeft":
                return(ImageAlign.Top_Left);

            case "TopRight":
                return(ImageAlign.Top_Right);

            case "CenterLeft":
                return(ImageAlign.Center_Left);

            case "CenterCenter":
                return(ImageAlign.Center_Center);

            case "CenterRight":
                return(ImageAlign.Center_Right);

            case "BottomLeft":
                return(ImageAlign.Bottom_Left);

            case "BottomCenter":
                return(ImageAlign.Bottom_Center);

            case "BottomRight":
                return(ImageAlign.Bottom_Right);
            }
            return(align);
        }
示例#5
0
        public void AddFitImage(Bitmap image, int width, int height, int x, int y, ImageAlign alignment)
        {
            // Resize and crop image to fit in the max bounds
            Bitmap fitImage = GetFitImage(image, width, height, x, y, alignment);

            using (Graphics thumbGraphics = Graphics.FromImage(this.ComicImage))
            {
                thumbGraphics.DrawImage(fitImage, x, y, fitImage.Width, fitImage.Height);
            }
        }
示例#6
0
        // Fill in employee info and working hours with sample data:
        private void FillEmployeeData(GcPdfDocument doc)
        {
            // For the purposes of this sample, we fill the form with random data:
            SetFieldValue(doc, _Names.EmpName, "Jaime Smith");
            SetFieldValue(doc, _Names.EmpNum, "12345");
            SetFieldValue(doc, _Names.EmpDep, "Research & Development");
            SetFieldValue(doc, _Names.EmpTitle, "Senior Developer");
            SetFieldValue(doc, _Names.EmpStatus, "Full Time");
            var      rand    = new Random((int)DateTime.Now.Ticks);
            DateTime workday = DateTime.Now.AddDays(-15);

            while (workday.DayOfWeek != DayOfWeek.Sunday)
            {
                workday = workday.AddDays(1);
            }
            TimeSpan wkTot = TimeSpan.Zero, wkReg = TimeSpan.Zero, wkOvr = TimeSpan.Zero;

            for (int i = 0; i < 7; ++i)
            {
                // Start time:
                var start = new DateTime(workday.Year, workday.Month, workday.Day, rand.Next(6, 12), rand.Next(0, 59), 0);
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][0], start.ToShortDateString());
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][1], start.ToShortTimeString());
                // End time:
                var end = start.AddHours(rand.Next(8, 14)).AddMinutes(rand.Next(0, 59));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][2], end.ToShortTimeString());
                var tot = end - start;
                var reg = TimeSpan.FromHours((start.DayOfWeek != DayOfWeek.Saturday && start.DayOfWeek != DayOfWeek.Sunday) ? 8 : 0);
                var ovr = tot.Subtract(reg);
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][3], reg.ToString(@"hh\:mm"));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][4], ovr.ToString(@"hh\:mm"));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][5], tot.ToString(@"hh\:mm"));
                wkTot += tot;
                wkOvr += ovr;
                wkReg += reg;
                //
                workday = workday.AddDays(1);
            }
            SetFieldValue(doc, _Names.TotalReg, wkReg.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.TotalOvr, wkOvr.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.TotalHours, wkTot.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.EmpSignDate, workday.ToShortDateString());

            // 'Sign' the time sheet on behalf of the employee by drawing an image representing the signature
            // (see TimeSheetIncremental for digitally signing by both employee and supervisor):
            var empSignImage = Image.FromFile(Path.Combine("Resources", "ImagesBis", "signature.png"));

            _disposables.Add(empSignImage);
            var ia = new ImageAlign(ImageAlignHorz.Center, ImageAlignVert.Center, true, true, true, false, false)
            {
                KeepAspectRatio = true
            };

            doc.Pages[0].Graphics.DrawImage(empSignImage, _empSignRect, null, ia);
        }
示例#7
0
        public static Rectangle GetCropImageSize(Size inputSize, Size cropSize, ImageAlign alignment)
        {
            int x = Convert.ToInt32(Convert.ToDouble(inputSize.Width - cropSize.Width) / 2d);
            int y = 0;

            if (alignment == ImageAlign.Center)
            {
                y = Convert.ToInt32(Convert.ToDouble(inputSize.Height - cropSize.Height) / 2d);
            }

            return(new Rectangle(x, y, cropSize.Width, cropSize.Height));
        }
示例#8
0
        // Init variables used to render labels:
        void Init(GcPdfDocument doc)
        {
            _labelWidth  = (doc.PageSize.Width - hmargin * 2) / 2;
            _labelHeight = _labelWidth;
            _pBold       = new Pen(Color.Black, 2);
            _pNorm       = new Pen(Color.Black, 0.5f);
            _logo        = Image.FromFile(Path.Combine("Resources", "ImagesBis", "AcmeLogo-vertical-250px.png"));
            _fontReg     = Font.FromFile(Path.Combine("Resources", "Fonts", "segoeui.ttf"));
            _fontBold    = Font.FromFile(Path.Combine("Resources", "Fonts", "segoeuib.ttf"));
            _tfSmall     = new TextFormat()
            {
                Font = _fontReg, FontSize = 8
            };
            _tfSmallB = new TextFormat()
            {
                Font = _fontBold, FontSize = 8
            };
            _tfLarge = new TextFormat()
            {
                Font = _fontBold, FontSize = 14
            };

            _ia       = new ImageAlign(ImageAlignHorz.Right, ImageAlignVert.Center, true, true, true, false, false);
            _tsHeader = new List <TabStop>()
            {
                new TabStop(24, TabStopAlignment.Leading), new TabStop(108, TabStopAlignment.Leading)
            };
            _tsFrom = new List <TabStop>()
            {
                new TabStop(12, TabStopAlignment.Leading), new TabStop(72, TabStopAlignment.Leading)
            };
            _tsCodes = new List <TabStop>()
            {
                new TabStop(_labelWidth / 8, TabStopAlignment.Center)
            };

            bcTop = new GcBarcode()
            {
                TextFormat          = _tfSmall,
                CodeType            = CodeType.Code_128_B,
                HorizontalAlignment = ImageAlignHorz.Center,
                VerticalAlignment   = ImageAlignVert.Center,
            };
            bcTop.Options.CaptionPosition = BarCodeCaptionPosition.Below;
            bcBottom = new GcBarcode()
            {
                TextFormat          = _tfSmall,
                CodeType            = CodeType.Code_128auto,
                HorizontalAlignment = ImageAlignHorz.Center,
                VerticalAlignment   = ImageAlignVert.Center,
            };
            bcBottom.Options.CaptionPosition = BarCodeCaptionPosition.Below;
        }
示例#9
0
        private void DrawImage(Rectangle box, Graphics g)
        {
            Image     image    = CheckState == CheckState.Checked ? Image : ((CheckState == CheckState.Indeterminate && ImageIndeterminate != null) ? ImageIndeterminate : (ImageUnchecked != null ?ImageUnchecked: Image));
            Size      isize    = (imagelayout == ImageLayout.Stretch) ? box.Size : image.Size;
            Rectangle drawarea = ImageAlign.ImagePositionFromContentAlignment(box, isize);

            //System.Diagnostics.Debug.WriteLine("Image for " + Name + " " + Enabled + " " + DrawnImageAttributesEnabled);

            if (DrawnImageAttributesEnabled != null)
            {
                g.DrawImage(image, drawarea, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, (Enabled) ? DrawnImageAttributesEnabled : DrawnImageAttributesDisabled);
            }
            else
            {
                g.DrawImage(image, drawarea, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            }
        }
示例#10
0
        private protected System.Drawing.Imaging.ImageAttributes drawnImageAttributesDisabled = null;        // Image override (colour etc) for background when using Image while !Enabled.

        private protected void DrawImage(Image image, Rectangle box, Graphics g, System.Drawing.Imaging.ImageAttributes imgattr)
        {
            if (image != null)
            {
                Size      isize    = ImageStretch ? box.Size : image.Size;
                Rectangle drawarea = ImageAlign.ImagePositionFromContentAlignment(box, isize, true, true);

                if (imgattr != null)
                {
                    g.DrawImage(image, drawarea, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imgattr);
                }
                else
                {
                    g.DrawImage(image, drawarea, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
                }
            }
        }
示例#11
0
    /// <summary>
    /// Corrects image align for RTL cultures.
    /// </summary>
    /// <param name="align">Value to parse</param>
    /// <returns>Align of an image</returns>
    private static ImageAlign GetImageAlign(ImageAlign align)
    {
        // RTL switch
        if (CultureHelper.IsUICultureRTL())
        {
            if (align == ImageAlign.Left)
            {
                align = ImageAlign.Right;
            }
            else if (align == ImageAlign.Right)
            {
                align = ImageAlign.Left;
            }
        }

        return(align);
    }
示例#12
0
 /// <summary>
 /// 获取水印图片的位置
 /// </summary>
 /// <param name="WaterMarkAlign">图片位置</param>
 /// <param name="x">生成水印图片的x值</param>
 /// <param name="y">生成水印图片的y值</param>
 /// <param name="s_imagewidth">原图片的宽度</param>
 /// <param name="s_imageheight">原图片的高度</param>
 /// <param name="wm_imagewidth">水印图片的宽度</param>
 /// <param name="wm_imageheight">水印图片的宽度</param>
 public static void GetWaterMarkPosition(ImageAlign WaterMarkAlign, out int x, out int y, int s_imagewidth, int s_imageheight, int wm_imagewidth, int wm_imageheight)
 {
     if (WaterMarkAlign == ImageAlign.LeftTop)
     {
         x = 10;
         y = 10;
     }
     else if (WaterMarkAlign == ImageAlign.LeftBottom)
     {
         x = 10;
         y = ((s_imageheight - wm_imageheight) - 10);
     }
     else if (WaterMarkAlign == ImageAlign.RightTop)
     {
         x = ((s_imagewidth - wm_imagewidth) - 10);
         y = 10;
     }
     else if (WaterMarkAlign == ImageAlign.RightBottom)
     {
         x = ((s_imagewidth - wm_imagewidth) - 10);
         y = ((s_imageheight - wm_imageheight) - 10);
     }
     else if (WaterMarkAlign == ImageAlign.Center)
     {
         x = ((s_imagewidth - wm_imagewidth) / 2);
         y = ((s_imageheight - wm_imageheight) / 2);
     }
     else if (WaterMarkAlign == ImageAlign.CenterBottom)
     {
         x = ((s_imagewidth - wm_imagewidth) / 2);
         y = ((s_imageheight - wm_imageheight) - 10);
     }
     else if (WaterMarkAlign == ImageAlign.CenterTop)
     {
         x = ((s_imagewidth - wm_imagewidth) / 2);
         y = 10;
     }
     else
     {
         x = ((s_imagewidth - wm_imagewidth) - 10);
         y = ((s_imageheight - wm_imageheight) - 10);
     }
 }
示例#13
0
		/// <summary>
		/// Sets the button's image.
		/// </summary>
		/// <param name="textureName">Texture name. Null to remove.</param>
		/// <param name="imageAlign">Determines how the image should be aligned.</param>
		public virtual void SetImage(string textureName, ImageAlign imageAlign = ImageAlign.LeftSide)
        {
            if (String.IsNullOrEmpty(textureName))
            {
                if (m_Image != null)
                    m_Image.Dispose();
                m_Image = null;
                return;
            }

            if (m_Image == null)
            {
                m_Image = new ImagePanel(this);
            }

            m_Image.ImageName = textureName;
			m_Image.MouseInputEnabled = false;
			m_ImageAlign = imageAlign;
			m_Image.SendToBack();

			Invalidate();
		}
示例#14
0
        public async override Task RenderAsync(TextWriter writer)
        {
            var tagBuilder = new TagBuilder("img")
            {
                TagRenderMode = TagRenderMode.Normal
            };

            tagBuilder.Attributes.Add("alt", AlternateText);
            tagBuilder.Attributes.Add("src", ImageUrl);
            if (!String.IsNullOrEmpty(DescriptionUrl))
            {
                tagBuilder.Attributes.Add("longdesc", DescriptionUrl);
            }

            if (ImageAlign != ImageAlign.NotSet)
            {
                tagBuilder.Attributes.Add("align", ImageAlign.ToString().ToLower());
            }

            tagBuilder.WriteTo(writer, HtmlEncoder.Default);

            await Task.CompletedTask;
        }
示例#15
0
 protected virtual void SetAlign(ImageAlign align)
 {
     this.Call("setAlign", align.ToString().ToLowerInvariant());
 }
示例#16
0
		internal override void restoreProperties(ItemProperties props)
		{
			TableProperties tprops = (TableProperties)props;

			caption = tprops.caption;
			captionColor = tprops.captionColor;
			captionFormat = tprops.captionFormat;
			captionHeight = tprops.captionHeight;
			cellBorders = tprops.cellBorders;
			columnWidth = tprops.columnWidth;
			currScrollRow = tprops.currScrollRow;
			linkStyle = tprops.linkStyle;
			picture = tprops.picture;
			picturePos = tprops.picturePos;
			rowHeight = tprops.rowHeight;
			scrollable = tprops.scrollable;
			selStyle = tprops.selStyle;
			style = tprops.style;
			textColor = tprops.textColor;
			EnableStyledText = tprops.enableStyledText;
			customDraw = tprops.customDraw;
			cellCustomDraw = tprops.cellCustomDraw;

			if (captionBackBrush != tprops.captionBackBrush)
			{
				if (captionBackBrush != null)
					captionBackBrush.Release();
				captionBackBrush = tprops.captionBackBrush;
				if (captionBackBrush != null)
					captionBackBrush.AddRef();
			}

			base.restoreProperties(props);
		}
示例#17
0
文件: Box.cs 项目: ChrisMoreton/Test3
		internal override void restoreProperties(ItemProperties props)
		{
			BoxProperties bprops = (BoxProperties)props;

			customDraw = bprops.customDraw;
			image = bprops.image;
			picturePos = bprops.picturePos;
			selStyle = bprops.selStyle;
			text = bprops.text;
			textColor = bprops.textColor;
			textFormat = bprops.textFormat;
			transparent = bprops.transparent;

			Style = bprops.style;
			ShapeOrientation = bprops.shapeRotation;
			Shape = bprops.shapeTemplate;
			PolyTextLayout = bprops.usePolyTextLt;
			EnableStyledText = bprops.useStyledText;

			base.restoreProperties(props);
		}
示例#18
0
        //Open Pre-RC2  client files
        public void OpenObsoleteClientFile(string fileName)
        {
            FileStream fs = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }

                throw new ArgumentException("The client data file (client.wyc) failed to open.\n\nFull details:\n\n" + ex.Message);
            }


            // Read back the file identification data, if any
            if (!ReadFiles.IsHeaderValid(fs, "IUCDFV2"))
            {
                //free up the file so it can be deleted
                fs.Close();

                throw new ArgumentException("The client file does not have the correct identifier - this is usually caused by file corruption. \n\nA possible solution is to replace the following file by reinstalling:\n\n" + fileName);
            }

            byte bType = (byte)fs.ReadByte();

            while (!ReadFiles.ReachedEndByte(fs, bType, 0xFF))
            {
                switch (bType)
                {
                case 0x01:     // Read Company Name
                    CompanyName = ReadFiles.ReadDeprecatedString(fs);
                    break;

                case 0x02:     // Product Name
                    ProductName = ReadFiles.ReadDeprecatedString(fs);
                    break;

                case 0x03:     // Read Installed Version
                    InstalledVersion = ReadFiles.ReadDeprecatedString(fs);
                    break;

                case 0x04:     // Add server file site
                    AddUniqueString(ReadFiles.ReadDeprecatedString(fs), ServerFileSites);
                    break;

                case 0x09:     // Add client server file site
                    AddUniqueString(ReadFiles.ReadDeprecatedString(fs), ClientServerSites);
                    break;

                case 0x11:     // Header image alignment
                    try
                    {
                        HeaderImageAlign = (ImageAlign)Enum.Parse(typeof(ImageAlign), ReadFiles.ReadDeprecatedString(fs));
                    }
                    catch { }
                    break;

                case 0x12:     // Header text indent
                    HeaderTextIndent = ReadFiles.ReadInt(fs);
                    break;

                case 0x13:     // Header text color
                    HeaderTextColorName = ReadFiles.ReadDeprecatedString(fs);
                    break;

                case 0x06:     // top Image
                    TopImage = ReadFiles.ReadImage(fs);
                    break;

                case 0x07:     // side Image
                    SideImage = ReadFiles.ReadImage(fs);
                    break;

                default:
                    ReadFiles.SkipField(fs, bType);
                    break;
                }

                bType = (byte)fs.ReadByte();
            }

            fs.Close();
        }
示例#19
0
 /// <summary>
 /// 获取水印图片的位置
 /// </summary>
 /// <param name="WaterMarkAlign">图片位置</param>
 /// <param name="x">生成水印图片的x值</param>
 /// <param name="y">生成水印图片的y值</param>
 /// <param name="s_imagewidth">原图片的宽度</param>
 /// <param name="s_imageheight">原图片的高度</param>
 /// <param name="wm_imagewidth">水印图片的宽度</param>
 /// <param name="wm_imageheight">水印图片的宽度</param>
 public static void GetWaterMarkPosition(ImageAlign WaterMarkAlign, out int x, out int y, int s_imagewidth, int s_imageheight, int wm_imagewidth, int wm_imageheight)
 {
     if (WaterMarkAlign == ImageAlign.LeftTop)
     {
         x = 10;
         y = 10;
     }
     else if (WaterMarkAlign == ImageAlign.LeftBottom)
     {
         x = 10;
         y = ((s_imageheight - wm_imageheight) - 10);
     }
     else if (WaterMarkAlign == ImageAlign.RightTop)
     {
         x = ((s_imagewidth - wm_imagewidth) - 10);
         y = 10;
     }
     else if (WaterMarkAlign == ImageAlign.RightBottom)
     {
         x = ((s_imagewidth - wm_imagewidth) - 10);
         y = ((s_imageheight - wm_imageheight) - 10);
     }
     else if (WaterMarkAlign == ImageAlign.Center)
     {
         x = ((s_imagewidth - wm_imagewidth) / 2);
         y = ((s_imageheight - wm_imageheight) / 2);
     }
     else if (WaterMarkAlign == ImageAlign.CenterBottom)
     {
         x = ((s_imagewidth - wm_imagewidth) / 2);
         y = ((s_imageheight - wm_imageheight) - 10);
     }
     else if (WaterMarkAlign == ImageAlign.CenterTop)
     {
         x = ((s_imagewidth - wm_imagewidth) / 2);
         y = 10;
     }
     else
     {
         x = ((s_imagewidth - wm_imagewidth) - 10);
         y = ((s_imageheight - wm_imageheight) - 10);
     }
 }
示例#20
0
 /// <summary>
 ///
 /// </summary>
 public virtual TBuilder Align(ImageAlign align)
 {
     this.ToComponent().Align = align;
     return(this as TBuilder);
 }
示例#21
0
			public virtual void loadFrom(BinaryReader reader, PersistContext ctx)
			{
				backColor = ctx.loadColor();
				behavior = (BehaviorType)reader.ReadInt32();
				arrowHead = (ArrowHead)reader.ReadInt32();
				arrowBase = (ArrowHead)reader.ReadInt32();
				arrowInterm = (ArrowHead)reader.ReadInt32();
				arrowHeadSize = (float)reader.ReadDouble();
				arrowBaseSize = (float)reader.ReadDouble();
				arrowIntermSize = (float)reader.ReadDouble();
				shadowsStyle = (ShadowsStyle)reader.ReadInt32();
				boxFillColor = ctx.loadColor();
				arrowFillColor = ctx.loadColor();
				boxFrameColor = ctx.loadColor();
				arrowColor = ctx.loadColor();
				alignToGrid = reader.ReadBoolean();
				showGrid = reader.ReadBoolean();
				gridColor = ctx.loadColor();
				gridSize = (float)reader.ReadDouble();
				boxStyle = (BoxStyle)reader.ReadInt32();
				shadowColor = ctx.loadColor();
				imagePos = (ImageAlign)reader.ReadInt32();
				textColor = ctx.loadColor();
				activeMnpColor = ctx.loadColor();
				selMnpColor = ctx.loadColor();
				disabledMnpColor = ctx.loadColor();
				arrowStyle = (ArrowStyle)reader.ReadInt32();
				arrowSegments = reader.ReadInt16();
				scrollX = (float)reader.ReadDouble();
				scrollY = (float)reader.ReadDouble();

				// zoomFactor was a short, now it is a float
				if (ctx.FileVersion < 19)
					zoomFactor = reader.ReadInt16();
				else
					zoomFactor = reader.ReadSingle();

				penDashStyle = (DashStyle)reader.ReadInt32();
				penWidth = (float)reader.ReadDouble();
				int c = reader.ReadInt32();
				defPolyShape = reader.ReadBytes(c);
				docExtents = ctx.loadRectF();
				shadowOffsetX = (float)reader.ReadDouble();
				shadowOffsetY = (float)reader.ReadDouble();
				tableFillColor = ctx.loadColor();
				tableFrameColor = ctx.loadColor();
				tableRowsCount = reader.ReadInt32();
				tableColumnsCount = reader.ReadInt32();
				tableColWidth = (float)reader.ReadDouble();
				tableRowHeight = (float)reader.ReadDouble();
				tableCaptionHeight = (float)reader.ReadDouble();
				tableCaption = reader.ReadString();
				arrowCascadeOrientation = (Orientation)reader.ReadInt32();
				tableCellBorders = (CellFrameStyle)reader.ReadInt32();
				boxIncmAnchor = (ArrowAnchor)reader.ReadInt32();
				boxOutgAnchor = (ArrowAnchor)reader.ReadInt32();
				boxesExpandable = reader.ReadBoolean();
				tablesScrollable = reader.ReadBoolean();
			}
示例#22
0
		private void drawImage(Graphics g, ImageAlign imgPos, bool transforms)
		{
			if (imagePos < ImageAlign.Document)
			{
				RectangleF rcs = new RectangleF(
					ClientRectangle.X, ClientRectangle.Y,
					ClientRectangle.Width, ClientRectangle.Height);
				Utilities.drawImage(g, BackgroundImage, rcs, imgPos);
			}
			else
			{
				if (transforms)
					setTransforms(g);
				else
				{
					g.PageUnit = measureUnit;
					g.PageScale = zoomFactor / 100F;
				}

				Utilities.drawImage(g, BackgroundImage, DocExtents,
					(ImageAlign)(imgPos - ImageAlign.Document));
				unsetTransforms(g);
			}
		}
示例#23
0
		private void DrawPicture(Graphics g, Image pict, RectangleF rect, ImageAlign pos)
		{
			float xoff = 0, yoff = 0;
			int xc = 0, yc = 0;

			// get image logical size in document coordinates
			float docZoom = document.ZoomFactor / 100.0f;
			float picw = (float)pict.Width / pict.HorizontalResolution * g.DpiX * docZoom;
			float pich = (float)pict.Height / pict.VerticalResolution * g.DpiY * docZoom;
			PointF ptLT = document.ClientToDoc(new Point(0, 0));
			PointF ptRB = document.ClientToDoc(new Point((int)picw, (int)pich));
			picw = ptRB.X - ptLT.X;
			pich = ptRB.Y - ptLT.Y;

			switch (pos)
			{
				case ImageAlign.TopLeft:
					xoff = rect.Left;
					yoff = rect.Top;
					xc = yc = 1;
					break;
				case ImageAlign.BottomLeft:
					xoff = rect.Left;
					yoff = rect.Bottom - pich;
					xc = yc = 1;
					break;
				case ImageAlign.TopRight:
					xoff = rect.Right - picw;
					yoff = rect.Top;
					xc = yc = 1;
					break;
				case ImageAlign.BottomRight:
					xoff = rect.Right - picw;
					yoff = rect.Bottom - pich;
					xc = yc = 1;
					break;
				case ImageAlign.Center:
					xoff = (rect.Right + rect.Left - picw) / 2;
					yoff = (rect.Bottom + rect.Top - pich) / 2;
					xc = yc = 1;
					break;
				case ImageAlign.Fit:
				{
					xc = yc = 1;
					float h = rect.Bottom - rect.Top;
					float w = rect.Right - rect.Left;
					if (h == 0) break;

					float ratioCtrl = w / h;
					float ratioPic = picw / pich;

					if (ratioCtrl > ratioPic)
					{
						//stretch vertically
						pich = (int)h;
						picw = (int)(ratioPic * pich);
						yoff = rect.Top;
						xoff = (rect.Right + rect.Left - picw) / 2;
					}
					else
					{
						//stretch horizontally
						picw = (int)w;
						if (ratioPic == 0) break;
						pich = (int)(picw / ratioPic);
						xoff = rect.Left;
						yoff = (rect.Bottom + rect.Top - pich) / 2;
					}
				}
					break;
				case ImageAlign.Stretch:
				{
					picw = rect.Right - rect.Left;
					pich = rect.Bottom - rect.Top;
					xoff = rect.Left; yoff = rect.Top;
					xc = yc = 1;
				}
					break;
				case ImageAlign.Tile:
				{
					xoff = rect.Left; yoff = rect.Top;
					xc = (int)((rect.Right - rect.Left) / picw) + 1;
					yc = (int)((rect.Bottom - rect.Top) / pich) + 1;
				}
					break;
			}

			if (pos != ImageAlign.Tile)
			{
				for (int x = 0; x < xc; x++)
					for (int y = 0; y < yc; y++)
						g.DrawImage(pict, xoff+x*picw, yoff+y*pich, picw, pich);
			}
			else
			{
				PointF ptLT2 = document.ClientToDoc(new Point(0, 0));
				PointF ptRB2 = document.ClientToDoc(new Point(
					(int)(1 + (float)Math.Ceiling((double)pict.Size.Width /
					pict.HorizontalResolution * g.DpiX * docZoom)), 
					(int)(1 + (float)Math.Ceiling((double)pict.Size.Height /
					pict.VerticalResolution * g.DpiY * docZoom))));
				float picw2 = ptRB2.X - ptLT.X;
				float pich2 = ptRB2.Y - ptLT.Y;

				for (int x = 0; x < xc; x++)
					for (int y = 0; y < yc; y++)
						g.DrawImage(pict, xoff+x*picw, yoff+y*pich, picw2, pich2);
			}
		}
示例#24
0
		internal static void drawImage(Graphics g, Image pict,
			RectangleF rect, ImageAlign ppos, float rotationAngle, PointF pivot)
		{
			float xoff = 0, yoff = 0;
			int xc = 0, yc = 0;

			// get image logical size in document coordinates
			RectangleF sizeDev = RectangleF.FromLTRB(0, 0,
				(float)pict.Size.Width / pict.HorizontalResolution * g.DpiX * g.PageScale,
				(float)pict.Size.Height / pict.VerticalResolution * g.DpiY * g.PageScale);
			RectangleF sizeDoc = deviceToDoc(g, sizeDev);
			float picw = sizeDoc.Width;
			float pich = sizeDoc.Height;

			switch (ppos)
			{
			case ImageAlign.TopLeft:
				xoff = rect.Left;
				yoff = rect.Top;
				break;
			case ImageAlign.BottomLeft:
				xoff = rect.Left;
				yoff = rect.Bottom - pich;
				break;
			case ImageAlign.TopRight:
				xoff = rect.Right - picw;
				yoff = rect.Top;
				break;
			case ImageAlign.BottomRight:
				xoff = rect.Right - picw;
				yoff = rect.Bottom - pich;
				break;
			case ImageAlign.Center:
				xoff = (rect.Right + rect.Left - picw) / 2;
				yoff = (rect.Bottom + rect.Top - pich) / 2;
				break;
			case ImageAlign.TopCenter:
				xoff = rect.X + rect.Width / 2 - picw / 2;
				yoff = rect.Y;
				break;
			case ImageAlign.BottomCenter:
				xoff = rect.X + rect.Width / 2 - picw / 2;
				yoff = rect.Bottom - pich;
				break;
			case ImageAlign.MiddleLeft:
				xoff = rect.X;
				yoff = rect.Y + rect.Height / 2 - pich / 2;
				break;
			case ImageAlign.MiddleRight:
				xoff = rect.Right - picw;
				yoff = rect.Y + rect.Height / 2 - pich / 2;
				break;
			case ImageAlign.Fit:
				{
					float h = rect.Bottom - rect.Top;
					float w = rect.Right - rect.Left;
					if (h == 0) break;

					float ratioCtrl = w / h;
					float ratioPic = picw / pich;

					if (ratioCtrl > ratioPic)
					{
						//stretch vertically
						pich = (int)h;
						picw = (int)(ratioPic * pich);
						yoff = rect.Top;
						xoff = (rect.Right + rect.Left - picw) / 2;
					}
					else
					{
						//stretch horizontally
						picw = (int)w;
						if (ratioPic == 0) break;
						pich = (int)(picw / ratioPic);
						xoff = rect.Left;
						yoff = (rect.Bottom + rect.Top - pich) / 2;
					}
				}
				break;
			case ImageAlign.Stretch:
				{
					picw = rect.Right - rect.Left;
					pich = rect.Bottom - rect.Top;
					xoff = rect.Left; yoff = rect.Top;
				}
				break;
			case ImageAlign.Tile:
				{
					xoff = rect.Left; yoff = rect.Top;
					xc = (int)((rect.Right - rect.Left) / picw) + 1;
					yc = (int)((rect.Bottom - rect.Top) / pich) + 1;
				}
				break;
			}

			if (ppos != ImageAlign.Tile)
			{
				Point alignedDevPos = docToDevice(g, new PointF(xoff, yoff));
				PointF alignedDocPos = deviceToDoc(g, alignedDevPos);

				if (rotationAngle != 0)
				{
					// Apply rotation transformation
					g.TranslateTransform(pivot.X, pivot.Y);
					g.RotateTransform(rotationAngle);
					g.TranslateTransform(-pivot.X, -pivot.Y);
				}

				g.DrawImage(pict, alignedDocPos.X, alignedDocPos.Y, picw, pich);

				if (rotationAngle != 0)
				{
					// Remove rotation
					g.TranslateTransform(pivot.X, pivot.Y);
					g.RotateTransform(-rotationAngle);
					g.TranslateTransform(-pivot.X, -pivot.Y);
				}
			}
			else
			{
				RectangleF sizeDev2 = RectangleF.FromLTRB(0, 0,
					1+(float)Math.Ceiling((double)pict.Size.Width / pict.HorizontalResolution * g.DpiX * g.PageScale),
					1+(float)Math.Ceiling((double)pict.Size.Height / pict.VerticalResolution * g.DpiY * g.PageScale));
				RectangleF sizeDoc2 = deviceToDoc(g, sizeDev2);
				float picw2 = sizeDoc2.Width;
				float pich2 = sizeDoc2.Height;

				if (rotationAngle != 0)
				{
					// Apply rotation transformation
					g.TranslateTransform(pivot.X, pivot.Y);
					g.RotateTransform(rotationAngle);
					g.TranslateTransform(-pivot.X, -pivot.Y);
				}

				for (int x = 0; x < xc; x++)
					for (int y = 0; y < yc; y++)
						g.DrawImage(pict, xoff+x*picw, yoff+y*pich, picw2, pich2);

				if (rotationAngle != 0)
				{
					// Remove rotation
					g.TranslateTransform(pivot.X, pivot.Y);
					g.RotateTransform(-rotationAngle);
					g.TranslateTransform(-pivot.X, -pivot.Y);
				}
			}
		}
示例#25
0
		internal static void drawImage(Graphics g, Image pict,
			RectangleF rect, ImageAlign ppos)
		{
			drawImage(g, pict, rect, ppos, 0, PointF.Empty);
		}
示例#26
0
        /// <summary>
        /// Raises the <see cref="ExtButton.Paint"/> event.
        /// </summary>
        /// <param name="pe">A <see cref="PaintEventArgs"/> that contains the event data.</param>
        protected override void OnPaint(PaintEventArgs pe)
        {
            if (FlatStyle != FlatStyle.Popup)      // popup style uses custom painting.
            {
                base.OnPaint(pe);
            }
            else
            {
                Rectangle border = ClientRectangle;
                border.Width--; border.Height--;

                Rectangle buttonarea = ClientRectangle;
                buttonarea.Inflate(-1, -1);                     // inside it.

                //System.Diagnostics.Debug.WriteLine("ButPaint " + this.Name + " " + ClientRectangle +" " + border + " " + buttonarea + " c " + BackColor + " " + FlatAppearance.BorderColor + " E:" + Enabled + " D:" + ButtonDisabledScaling);

                Color colBack   = Color.Empty;
                Color colBorder = Color.Empty;
                switch (drawState)
                {
                case DrawState.Disabled:
                    colBack   = BackColor.Multiply(buttonDisabledScaling);
                    colBorder = FlatAppearance.BorderColor.Multiply(buttonDisabledScaling);
                    break;

                case DrawState.Normal:
                default:
                    colBack   = BackColor;
                    colBorder = FlatAppearance.BorderColor;
                    break;

                case DrawState.Hover:
                    colBack   = FlatAppearance.MouseOverBackColor;
                    colBorder = FlatAppearance.BorderColor.Multiply(borderColorScaling);
                    break;

                case DrawState.Click:
                    colBack   = FlatAppearance.MouseDownBackColor;
                    colBorder = FlatAppearance.BorderColor.Multiply(borderColorScaling);
                    break;
                }

                if (buttonarea.Width >= 1 && buttonarea.Height >= 1)  // ensure size
                {
                    using (var b = new LinearGradientBrush(buttonarea, colBack, colBack.Multiply(buttonColorScaling), 90))
                        pe.Graphics.FillRectangle(b, buttonarea);       // linear grad brushes do not respect smoothing mode, btw
                }

                pe.Graphics.SmoothingMode = SmoothingMode.None;

                if (border.Width >= 1 && border.Height >= 1)        // ensure it does not except
                {
                    using (var p = new Pen(colBorder))
                        pe.Graphics.DrawRectangle(p, border);
                }

                if (buttonarea.Width < 1 || buttonarea.Height < 1)  // and no point drawing any more in the button area if its too small, it will except
                {
                    return;
                }

                if (Image != null)
                {
                    Size isize = (imagelayout == ImageLayout.Stretch) ? new Size(buttonarea.Height, buttonarea.Height) : Image.Size;

                    if ((Enabled && drawnImageAttributesEnabled != null) || (!Enabled && drawnImageAttributesDisabled != null))
                    {
                        //System.Diagnostics.Debug.WriteLine("ButtonExt " + this.Name + " Draw image with IA");
                        pe.Graphics.DrawImage(Image, ImageAlign.ImagePositionFromContentAlignment(buttonarea, isize),
                                              0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, (Enabled) ? drawnImageAttributesEnabled : drawnImageAttributesDisabled);
                    }
                    else
                    {
                        pe.Graphics.DrawImage(Image, ImageAlign.ImagePositionFromContentAlignment(buttonarea, isize),
                                              0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel);
                    }
                }

                pe.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

                if (!string.IsNullOrEmpty(Text))
                {
                    var txalign = Environment.OSVersion.Platform == PlatformID.Win32NT ? RtlTranslateAlignment(TextAlign) : TextAlign;      // MONO Bug cover over

                    using (var fmt = ControlHelpersStaticFunc.StringFormatFromContentAlignment(txalign))
                    {
                        using (Brush textb = new SolidBrush((Enabled) ? this.ForeColor : this.ForeColor.Multiply(ButtonDisabledScaling)))
                        {
                            if (this.UseMnemonic)
                            {
                                fmt.HotkeyPrefix = this.ShowKeyboardCues ? HotkeyPrefix.Show : HotkeyPrefix.Hide;
                            }
                            if (this.AutoEllipsis)
                            {
                                fmt.Trimming = StringTrimming.EllipsisCharacter;
                            }
                            pe.Graphics.DrawString(this.Text, this.Font, textb, buttonarea, fmt);
                        }
                    }
                }

                pe.Graphics.SmoothingMode = SmoothingMode.None;

                if (Focused && ShowFocusCues)
                {
                    using (var p = new Pen(colBorder))
                    {
                        Rectangle rcFocus = border;

                        // Thicken the standard border by 1px.
                        rcFocus.Inflate(-1, -1);
                        pe.Graphics.DrawRectangle(p, rcFocus);

                        // Thicken that by an additional 1px, using something similar to ControlPaint.DrawFocusRectangle, but capable of honouring forecolour.
                        rcFocus.Inflate(-1, -1);
                        p.DashStyle   = DashStyle.Dash;
                        p.DashPattern = new[] { 1f, 1f };
                        pe.Graphics.DrawRectangle(p, rcFocus);
                    }
                }

                pe.Graphics.SmoothingMode = SmoothingMode.Default;

                this.OnCustomPaint(pe);
            }
        }
示例#27
0
		/// <summary>
		/// Adds embedded image to DXF output
		/// </summary>
		/// <param name="rect1">Image bounding rect</param>
		/// <param name="oImage">Image itself</param>
		/// <param name="ImageID">Uniques ID of the image</param>
		/// <param name="ia">Image alignment</param>
		/// <param name="Color2Repl">Color that to be replace transparent one in the image</param>
		/// <returns>true if succesfull otherwsie false</returns>
		public bool AddImage(RectangleF rect1, Image oImage, long ImageID, ImageAlign ia, Color Color2Repl)
		{
			string FileName = "", sText = "";
			try
			{

				if (!m_ExportExternalImages)
					return true;

				float fW = 0, fH = 0, fDX = 0, fDY = 0;
				RectangleF rect = RectangleF.Empty;

				// Validating input parameters
				if ( oImage == null )
					return true;


				if ( FileName == null )
					return true;


				// Correcting bounding rectangle according to image alignment
				rect = new RectangleF(rect1.X, rect1.Y,rect1.Width, rect1.Height);
				if ( GetImageDim(oImage, rect, ia , ref fW, ref fH , ref fDX, ref fDY))
				{
					rect.Width = fW;
					rect.Height = fH;
					rect.X = fDX;
					rect.Y = fDY;

				}
				
				// Replicating color if it's necessary
				if ( Color2Repl != Color.Empty )
				{
					Color pixColor;
					Bitmap bmp = oImage as Bitmap;
					for (int Xcount = 0; Xcount < oImage.Width; Xcount++)
					{
						for (int Ycount = 0; Ycount < bmp.Height; Ycount++)
						{
							pixColor = bmp.GetPixel(Xcount, Ycount);
							if ( pixColor == Color.FromArgb(0,0,0,0))
							{
								bmp.SetPixel(Xcount, Ycount, Color2Repl);
							}

					
						}
					}
				}

				// Preparing & inserting IMAGEDEF
				FileName = String.Format("{2}\\{0}_{1}.jpg", FileNamePattern, ImageID, BasedPath);
				oImage.Save(FileName, System.Drawing.Imaging.ImageFormat.Jpeg);

				sText = String.Format(provider , "  0\nIMAGEDEF\n  5\n{0:ID}\n  100\nAcDbRasterImageDef\n  90\n0\n  1\n{1}\n   10\n{2:U}\n  20\n{3:U}\n  11\n0.01\n  21\n0.01\n  280\n1\n  281\n0\n",
					ImageID, 
					FileName,
					rect.Width,
					rect.Height);

				// Preparing & inserting IMAGE
                if (AddObject(String.Format("OBJ{0:X3}", ImageID), sText))
				{

					sText = String.Format(provider, "  0\nIMAGE\n100\nAcDbEntity\n{0:HAN}  8\n{3}\n100\nAcDbRasterImage\n  10\n{0:U}\n  20\n{1:U}\n  11\n1\n  21\n0\n  31\n0\n  12\n0\n  22\n1\n  32\n0\n  13\n{4:U}\n  23\n{5:U}\n  340\n{2:ID}\n  70\n9\n",
						rect.X,
						m_FlowChart.DocExtents.Height - rect.Bottom,
						ImageID,
						IMAGE_LAYER,
						rect.Width,
						rect.Height);

					AddEntity(String.Format("IMG{0:X3}", ImageID), sText);
				}


			}
			catch ( Exception ex)
			{

				Trace.WriteLine(String.Format("{0} error {1}\n","AddImage",ex.Message));
				return false;

			}

			return true;
		}
示例#28
0
    /// <summary>
    /// Method for adding button to controls.
    /// </summary>
    /// <param name="outerPanel">Panel to be added to</param>
    /// <param name="identifier">Index of button</param>
    private void AddButtonTo(CMSPanel outerPanel, int identifier)
    {
        MenuItem   button      = Buttons[identifier];
        string     caption     = button.Text;
        string     tooltip     = button.Tooltip;
        string     cssClass    = button.CssClass;
        string     onClick     = button.OnClientClick;
        string     redirectUrl = button.RedirectUrl;
        string     imagePath   = button.ImagePath;
        string     alt         = button.ImageAltText;
        int        minWidth    = button.MinimalWidth;
        ImageAlign imageAlign  = GetImageAlign(button.ImageAlign);

        // Generate button image
        Image buttonImage = new Image();

        buttonImage.ID              = "img" + identifier;
        buttonImage.CssClass        = "MenuButtonImage";
        buttonImage.EnableViewState = false;
        buttonImage.AlternateText   = alt ?? caption;
        if (!string.IsNullOrEmpty(imagePath))
        {
            buttonImage.ImageUrl = ResolveUrl(imagePath);
        }
        buttonImage.ImageAlign = imageAlign;

        // Generate button text
        Literal captionLiteral = new Literal();

        captionLiteral.ID = "ltlCaption" + identifier;
        captionLiteral.EnableViewState = false;
        string separator = (imageAlign == ImageAlign.Top) ? "<br />" : "\n";

        captionLiteral.Text = String.Format("{0}<span class=\"MenuButtonText\">{1}</span>", separator, caption);

        CMSPanel pnlSubItems = null;

        if (button.SubItems.Count > 0)
        {
            // Ensure jQuery tool is loaded
            ScriptHelper.RegisterJQueryTools(Page);

            // Append submenu toogle script
            onClick = "CMSUniMenu.ToogleSubMenu(this);" + onClick;

            // Append arrow down image for idication sub menu
            captionLiteral.Text += "&nbsp;<img style=\"width:8px; height:8px;\" src=\"" + GetImageUrl("Design/Controls/UniMenu/ArrowDown.png") + "\" alt=\"Sub menu items\" class=\"SubItemsArrow\" />";

            // Create submenu
            CreateSubMenu(button, ref pnlSubItems, cssClass, identifier);
        }

        // Generate button link
        HyperLink buttonLink = new HyperLink();

        buttonLink.ID = "btn" + identifier;
        buttonLink.EnableViewState = false;

        buttonLink.Controls.Add(buttonImage);
        buttonLink.Controls.Add(captionLiteral);

        if (!string.IsNullOrEmpty(redirectUrl))
        {
            buttonLink.NavigateUrl = ResolveUrl(redirectUrl);
        }

        // Generate left border
        CMSPanel pnlLeft = new CMSPanel();

        pnlLeft.ID      = "pnlLeft" + identifier;
        pnlLeft.ShortID = "pl" + identifier;

        pnlLeft.EnableViewState = false;
        pnlLeft.CssClass        = "Left" + cssClass;

        // Generate middle part of button
        CMSPanel pnlMiddle = new CMSPanel();

        pnlMiddle.ID      = "pnlMiddle" + identifier;
        pnlMiddle.ShortID = "pm" + identifier;

        pnlMiddle.EnableViewState = false;
        pnlMiddle.CssClass        = "Middle" + cssClass;
        pnlMiddle.Controls.Add(buttonLink);
        if (minWidth > 0)
        {
            pnlMiddle.Style.Add("min-width", minWidth + "px");

            // IE7 issue with min-width
            CMSPanel pnlMiddleTmp = new CMSPanel();
            pnlMiddleTmp.EnableViewState = false;
            pnlMiddleTmp.Style.Add("width", minWidth + "px");
            pnlMiddle.Controls.Add(pnlMiddleTmp);
        }

        // Add sub items if exists
        if (pnlSubItems != null)
        {
            pnlMiddle.Controls.Add(pnlSubItems);
        }

        // Generate right border
        CMSPanel pnlRight = new CMSPanel();

        pnlRight.ID      = "pnlRight" + identifier;
        pnlRight.ShortID = "pr" + identifier;

        pnlRight.EnableViewState = false;
        pnlRight.CssClass        = "Right" + cssClass;

        // Generate whole button
        CMSPanel pnlButton = new CMSPanel();

        pnlButton.ID      = "pnlButton" + identifier;
        pnlButton.ShortID = BUTTON_PANEL_SHORTID + identifier;

        pnlButton.EnableViewState = false;
        if ((AllowSelection && identifier == SelectedIndex) || (button.AllowToggle && button.IsToggled))
        {
            cssClass += SelectedSuffix;
        }

        pnlButton.CssClass = cssClass;

        if (button.AllowToggle)
        {
            pnlButton.CssClass += " Toggle";
            EnsureAllowToggleScript();
        }

        //Generate button table (IE7 issue)
        Table     tabButton     = new Table();
        TableRow  tabRow        = new TableRow();
        TableCell tabCellLeft   = new TableCell();
        TableCell tabCellMiddle = new TableCell();
        TableCell tabCellRight  = new TableCell();

        tabButton.CellPadding = 0;
        tabButton.CellSpacing = 0;

        tabButton.Rows.Add(tabRow);
        tabRow.Cells.Add(tabCellLeft);
        tabRow.Cells.Add(tabCellMiddle);
        tabRow.Cells.Add(tabCellRight);

        // Add inner controls
        tabCellLeft.Controls.Add(pnlLeft);
        tabCellMiddle.Controls.Add(pnlMiddle);
        tabCellRight.Controls.Add(pnlRight);

        pnlButton.Controls.Add(tabButton);

        pnlButton.ToolTip = tooltip ?? caption;

        outerPanel.Controls.Add(pnlButton);

        if (AllowDraggable)
        {
            mStartupScript.Append(String.Format("$j( '#{0}' ).draggable({{ helper:{1}, scope:'{2}' }});", pnlButton.ClientID, GetDraggableHandler(button.DraggableTemplateHandler), button.DraggableScope));
        }
        if (AllowSelection)
        {
            onClick = "SelectButton(this);" + onClick;
        }
        else if (button.AllowToggle)
        {
            onClick = "ToggleButton(this);" + onClick;
        }

        pnlButton.Attributes["onclick"] = CheckChanges ? "if (CheckChanges()) {" + onClick + "}" : onClick;

        // In case of horizontal layout
        if (HorizontalLayout)
        {
            // Stack buttons underneath
            pnlButton.Style.Add("clear", "both");
        }
        else
        {
            // Stack buttons side-by-side
            pnlButton.Style.Add("float", "left");
        }
    }
示例#29
0
    /// <summary>
    /// Method for adding button to controls.
    /// </summary>
    /// <param name="outerPanel">Panel to be added to</param>
    /// <param name="identifier">Index of button</param>
    private void AddButtonTo(CMSPanel outerPanel, int identifier)
    {
        MenuItem   button      = Buttons[identifier];
        string     caption     = button.Text;
        string     tooltip     = button.Tooltip;
        string     cssClass    = button.CssClass;
        string     onClick     = button.OnClientClick;
        string     redirectUrl = button.RedirectUrl;
        string     imagePath   = button.ImagePath;
        string     iconClass   = button.IconClass;
        string     alt         = button.ImageAltText;
        int        minWidth    = button.MinimalWidth;
        ImageAlign imageAlign  = GetImageAlign(button.ImageAlign);

        // Generate button image
        WebControl image = null;

        if (!string.IsNullOrEmpty(imagePath))
        {
            var buttonImage = new Image
            {
                ID              = "img" + identifier,
                CssClass        = "MenuButtonImage",
                EnableViewState = false,
                AlternateText   = alt ?? caption,
                ImageAlign      = imageAlign,
                ImageUrl        = ResolveUrl(imagePath)
            };
            image = buttonImage;
        }
        else if (!string.IsNullOrEmpty(iconClass))
        {
            var icon = new CMSIcon
            {
                ID = "ico" + identifier,
                EnableViewState = false,
                ToolTip         = tooltip,
                CssClass        = "cms-icon-80 " + iconClass
            };
            image = icon;
        }

        // Generate button text
        Literal captionLiteral = new Literal();

        captionLiteral.ID = "ltlCaption" + identifier;
        captionLiteral.EnableViewState = false;
        string separator = (imageAlign == ImageAlign.Top) ? "<br />" : "\n";

        captionLiteral.Text = String.Format("{0}<span class=\"MenuButtonText\">{1}</span>", separator, caption);

        CMSPanel pnlSubItems = null;

        if (button.SubItems.Count > 0)
        {
            // Ensure jQuery tool is loaded
            ScriptHelper.RegisterJQueryTools(Page);

            // Register support script
            ScriptHelper.RegisterScriptFile(Page, "~/CMSAdminControls/UI/UniMenu/UniMenu.js");

            // Append sub-menu toggle script
            onClick = "CMSUniMenu.ToogleSubMenu(this);" + onClick;

            // Append arrow down image for indication sub menu
            captionLiteral.Text += @"<i aria-hidden=""true"" class=""icon-caret-right-down cms-icon-30""></i>";

            // Create submenu
            pnlSubItems = CreateSubMenu(button, cssClass, identifier);
        }

        // Generate button link
        HyperLink buttonLink = new HyperLink();

        buttonLink.ID = "btn" + identifier;
        buttonLink.EnableViewState = false;

        if (image != null)
        {
            buttonLink.Controls.Add(image);
        }
        buttonLink.Controls.Add(captionLiteral);

        if (!string.IsNullOrEmpty(redirectUrl))
        {
            buttonLink.NavigateUrl = ResolveUrl(redirectUrl);
        }

        // Generate left border
        CMSPanel pnlLeft = new CMSPanel();

        pnlLeft.ID      = "pnlLeft" + identifier;
        pnlLeft.ShortID = "pl" + identifier;

        pnlLeft.EnableViewState = false;
        pnlLeft.CssClass        = "Left" + cssClass;

        // Generate middle part of button
        CMSPanel pnlMiddle = new CMSPanel();

        pnlMiddle.ID      = "pnlMiddle" + identifier;
        pnlMiddle.ShortID = "pm" + identifier;

        pnlMiddle.EnableViewState = false;
        pnlMiddle.CssClass        = "Middle" + cssClass;
        pnlMiddle.Controls.Add(buttonLink);
        if (minWidth > 0)
        {
            pnlMiddle.Style.Add("min-width", minWidth + "px");

            // IE7 issue with min-width
            CMSPanel pnlMiddleTmp = new CMSPanel();
            pnlMiddleTmp.EnableViewState = false;
            pnlMiddleTmp.Style.Add("width", minWidth + "px");
            pnlMiddle.Controls.Add(pnlMiddleTmp);
        }

        // Add sub items if exists
        if (pnlSubItems != null)
        {
            pnlMiddle.Controls.Add(pnlSubItems);
        }

        // Generate right border
        CMSPanel pnlRight = new CMSPanel();

        pnlRight.ID      = "pnlRight" + identifier;
        pnlRight.ShortID = "pr" + identifier;

        pnlRight.EnableViewState = false;
        pnlRight.CssClass        = "Right" + cssClass;

        // Generate whole button
        CMSPanel pnlButton = new CMSPanel();

        pnlButton.ID      = "pnlButton" + identifier;
        pnlButton.ShortID = BUTTON_PANEL_SHORTID + identifier;

        // Propagate attributes to panel for JavaScript use
        foreach (var entry in button.Attributes)
        {
            pnlButton.Attributes.Add(entry.Key, entry.Value);
        }

        pnlButton.EnableViewState = false;

        if (button.AllowToggle && button.IsToggled)
        {
            cssClass += SelectedSuffix;
        }

        pnlButton.CssClass = cssClass;

        if (button.AllowToggle)
        {
            pnlButton.CssClass += " Toggle";
            EnsureAllowToggleScript();
        }

        //Generate button table (IE7 issue)
        Table     tabButton     = new Table();
        TableRow  tabRow        = new TableRow();
        TableCell tabCellLeft   = new TableCell();
        TableCell tabCellMiddle = new TableCell();
        TableCell tabCellRight  = new TableCell();

        tabButton.CellPadding = 0;
        tabButton.CellSpacing = 0;

        tabButton.Rows.Add(tabRow);
        tabRow.Cells.Add(tabCellLeft);
        tabRow.Cells.Add(tabCellMiddle);
        tabRow.Cells.Add(tabCellRight);

        // Add inner controls
        tabCellLeft.Controls.Add(pnlLeft);
        tabCellMiddle.Controls.Add(pnlMiddle);
        tabCellRight.Controls.Add(pnlRight);

        pnlButton.Controls.Add(tabButton);

        pnlButton.ToolTip = tooltip ?? caption;

        outerPanel.Controls.Add(pnlButton);

        if (AllowDraggable)
        {
            mStartupScript.Append(String.Format("$cmsj( '#{0}' ).draggable({{ helper:{1}, scope:'{2}' }});", pnlButton.ClientID, GetDraggableHandler(button.DraggableTemplateHandler), button.DraggableScope));
        }

        if (!AllowSelection && button.AllowToggle)
        {
            onClick = "ToggleButton(this);" + onClick;
        }

        pnlButton.Attributes["onclick"] = CheckChanges ? "if (CheckChanges()) {" + onClick + "}" : onClick;

        // In case of horizontal layout
        if (HorizontalLayout)
        {
            // Stack buttons underneath
            pnlButton.Style.Add("clear", "both");
        }
        else
        {
            // Stack buttons side-by-side
            pnlButton.Style.Add("float", "left");
        }

        if (button.IsSelectable)
        {
            // Collect panel client IDs for JavaScript
            mElemsIds += "#" + pnlButton.ClientID + ",";
            if (AllowSelection && (identifier == SelectedIndex))
            {
                // Button should be selected by default, remember its ClientID for JavaScript
                defaultSelectedClientID = "#" + pnlButton.ClientID;
            }
        }
    }
示例#30
0
        /// <summary>
        /// 生成图片的Html代码
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="path">路径</param>
        /// <param name="width">宽</param>
        /// <param name="widthUnit">宽单位</param>
        /// <param name="height">高</param>
        /// <param name="heightUnit">高单位</param>
        /// <param name="align">图片显示方式</param>
        /// <param name="border">边框</param>
        /// <param name="vspace"></param>
        /// <param name="hspace"></param>
        /// <param name="alt">说明文字</param>
        /// <param name="linkUrl">链接的URL</param>
        /// <param name="pic2Path">替换图片的路径</param>
        /// <param name="linkTarget">目标</param>
        /// <param name="linkTitle">标题</param>
        /// <param name="linkAccesskey">访问键</param>
        /// <returns></returns>
        public string ImageHtml(
            string name,
            string path,
            string width,
            string widthUnit,
            string height,
            string heightUnit,
            ImageAlign align,
            string border,
            string vspace,
            string hspace,
            string alt,
            string linkUrl,
            string pic2Path,
            string linkTarget,
            string linkTitle,
            string linkAccesskey,
            string mediaID
            )
        {
            string picMouseOut  = "";
            string picMouseOver = "";
            string picCode      = "";

            if (path == "")
            {
                return("");
            }

            //图片设置*/
            string imgHtml = "<img src=\"${srs_" + mediaID + "}\" ";

            imgHtml += "style = \"WIDTH:" + width + widthUnit + "; HEIGHT:" + height + heightUnit + "\" ";
            imgHtml += "border=\"" + border + "\" vspace=\"" + vspace + "\" ";
            imgHtml += "hspace=\"" + hspace + "\" alt=\"" + alt + "\" ";
            imgHtml += "name=\"" + name + "\" align=\"" + align.ToString().ToLower() + "\" />";

            //链接设置*/
            string linkHtml = "";

            if (linkUrl != "" || pic2Path != "")
            {
                if (linkUrl != "")
                {
                    linkHtml  = "<a href=\"" + linkUrl + "\" ";
                    linkHtml += "target=\"" + linkTarget + "\" ";
                    linkHtml += "title=\"" + linkTitle + "\" ";
                    linkHtml += "accesskey=\"" + linkAccesskey + "\"";
                }
                else
                {
                    linkHtml = "<a href=\"#\"";
                }
                //图片替换
                if (pic2Path != "")
                {
                    picMouseOut  = " na_restore_img_src('" + name + "', 'document')";
                    linkHtml    += "OnMouseOut=\"" + picMouseOut + "\"";
                    picMouseOver = "na_change_img_src('" + name + "', 'document'," + pic2Path + ",true)";
                    linkHtml    += "OnMouseOver=\"" + picMouseOver + "\"";
                }

                linkHtml += ">";
                picCode   = linkHtml + imgHtml + @"</a>";
                return(picCode);
            }
            else
            {
                picCode = picCode = imgHtml;
                return(picCode);
            }
        }
示例#31
0
		/// <summary>
		/// Adds new "rect" node to SVG
		/// </summary>
		/// <param name="sX">X - coord of the node</param>
		/// <param name="sY">Y - coord of the node</param>
		/// <param name="sWidth">Node width</param>
		/// <param name="sHeight">Node heaignt</param>
		/// <param name="sStrokeWidth">Frame width</param>
		/// <param name="colFill">Fill color</param>
		/// <param name="colStroke">Frame color</param>
		/// <param name="sRX">Bounds Z-size ( for bounding rects )</param>
		/// <param name="sRY">Bounds Y-size ( for bounding rects )</param>
		/// <param name="newImg">Node image(if any exists NULL otherwise)</param>
		/// <param name="Color2Repl">Color to replace transparent one in the image</param>
		/// <returns>Returns recently added to SVG XML "rect" node</returns>
		public XmlNode AddRect(string sX, 
			string sY, 
			string sWidth, 
			string sHeight, 
			string sStrokeWidth,
			Color colFill, 
			Color colStroke,
			string sRX,
			string sRY,
			System.Drawing.Image newImg,
			Color Color2Repl,
			ImageAlign ia,
			RectangleF rect)
		{

			bool IsImage = ( newImg != null );
			if (!IsValid())
				return null;
			
			m_InnerNode = m_InnerRoot.InsertAfter(m_InnerDoc.CreateNode(XmlNodeType.Element, IsImage ? "image":"rect" , sNsDefault), m_InnerRoot.LastChild);
			if ( m_InnerNode!=null )
			{
				m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("x"));
				m_InnerNode.Attributes["x"].Value = sX;

				m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("y"));
				m_InnerNode.Attributes["y"].Value = sY;

				if ( sRX!=null )
				{
					m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("rx"));
					m_InnerNode.Attributes["rx"].Value = sRX;
				}
				
				if (sRY!=null)
				{
					m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("ry"));
					m_InnerNode.Attributes["ry"].Value = sRY;
				}

				m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("width"));
				m_InnerNode.Attributes["width"].Value = sWidth;

				m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("height"));
				m_InnerNode.Attributes["height"].Value = sHeight;

				if (!IsImage)
				{
					m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("stroke"));
					m_InnerNode.Attributes["stroke"].Value = SvgManager.Color2Str(colStroke);
				
			
					m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("fill"));
					m_InnerNode.Attributes["fill"].Value = SvgManager.Color2Str(colFill);
				
					m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("stroke-width"));
					m_InnerNode.Attributes["stroke-width"].Value = sStrokeWidth;
				}
				else
				{
					Image cloneImg = newImg.Clone() as System.Drawing.Image;
					m_InnerNode.Attributes.Append(m_InnerDoc.CreateAttribute("href", "http://www.w3.org/1999/xlink"));
					string sImg = String.Format("data:image/jpg;base64,{0}", SvgManager.Image2String(cloneImg, Color2Repl));
					m_InnerNode.Attributes["href"].Value = sImg;

					float fW = 0, fH = 0, fDX = 0, fDY = 0;

					if ( GetImageDim(cloneImg, rect, ia , ref fW, ref fH , ref fDX, ref fDY))
					{
						m_InnerNode.Attributes["width"].Value = Unit2PixStr(fW);
						m_InnerNode.Attributes["height"].Value = Unit2PixStr(fH);

						if (fDX!=0)
						{						
							m_InnerNode.Attributes["x"].Value = Unit2PixStr(fDX);
						}

						if (fDY!=0)
						{
							m_InnerNode.Attributes["y"].Value = Unit2PixStr(fDY);
						}
					}

				}
			
			}
			return m_InnerNode;
		}
示例#32
0
        public int CreatePDF(Stream stream)
        {
            using (var clouds = Image.FromFile(Path.Combine("Resources", "Images", "clouds.jpg")))
                using (var firth = Image.FromFile(Path.Combine("Resources", "Images", "firth.jpg")))
                    using (var lavender = Image.FromFile(Path.Combine("Resources", "Images", "lavender.jpg")))
                    {
                        var yumin = Font.FromFile(Path.Combine("Resources", "Fonts", "yumin.ttf"));
                        var ia    = new ImageAlign(ImageAlignHorz.Left, ImageAlignVert.Top, true, true, true, false, false);

                        var doc = new GcPdfDocument();

                        // The TextLayout that will hold and render the text:
                        var tl = new TextLayout(72);
                        tl.FirstLineIndent       = 18;
                        tl.ParagraphSpacing      = 6;
                        tl.FlowDirection         = FlowDirection.VerticalRightToLeft;
                        tl.TextAlignment         = TextAlignment.Justified;
                        tl.AlignmentDelayToSplit = true;
                        var tf = new TextFormat()
                        {
                            Font = yumin, FontSize = 12
                        };
                        // Repeat test text to fill a few pages:
                        for (int i = 0; i < 25; ++i)
                        {
                            tl.Append(text, tf);
                            tl.AppendLine();
                        }

                        // Layout text in 4 horizontal columns:
                        // (The logic/code in this sample is identical to ArabicColumns):
                        const int NCOLS  = 4;
                        var       margin = 36f;
                        var       gap    = 18f;
                        var       page   = doc.NewPage();
                        page.Landscape = true;
                        var colHeight = (page.Size.Height - margin * 2 - gap * (NCOLS - 1)) / NCOLS;
                        tl.MaxWidth     = page.Size.Width;
                        tl.MaxHeight    = page.Size.Height;
                        tl.MarginLeft   = tl.MarginRight = margin;
                        tl.MarginTop    = margin;
                        tl.MarginBottom = margin + (colHeight + gap) * (NCOLS - 1);
                        // We can specify arbitrary rectangles for the text to flow around.
                        // In this case, we add 3 areas to draw some images:
                        tl.ObjectRects = new List <ObjectRect>()
                        {
                            new ObjectRect(page.Size.Width - margin - 267, margin, 267, 200),
                            new ObjectRect(margin + 100, margin + 60, 133, 100),
                            new ObjectRect(margin, page.Size.Height - margin - 301, 200, 301),
                        };
                        // Convert object rects to image areas, adjust to provide nice looking padding:
                        var rClouds = tl.ObjectRects[0].ToRectangleF();
                        rClouds.Inflate(-4, -3);
                        var rFirth = tl.ObjectRects[1].ToRectangleF();
                        rFirth.Inflate(-4, -3);
                        var rLavender = tl.ObjectRects[2].ToRectangleF();
                        rLavender.Inflate(-4, -3);
                        page.Graphics.DrawImage(clouds, rClouds, null, ia);
                        page.Graphics.DrawImage(firth, rFirth, null, ia);
                        page.Graphics.DrawImage(lavender, rLavender, null, ia);

                        // THE call: it calculates the glyphs needed to draw the text, and lays it out:
                        tl.PerformLayout(true);

                        // Loop while there is still text to render:
                        bool done = false;
                        while (!done)
                        {
                            for (int col = 0; col < NCOLS; ++col)
                            {
                                int nextcol = (col < NCOLS - 1) ? col + 1 : 0;
                                // TextSplitOptions tell TextLayout.Split() how to layout the remaining text.
                                // In this case we advance from column to column by updating top and bottom margins:
                                var tso = new TextSplitOptions(tl)
                                {
                                    RestMarginTop    = margin + (colHeight + gap) * nextcol,
                                    RestMarginBottom = margin + (colHeight + gap) * (NCOLS - 1 - nextcol)
                                };
                                var split = tl.Split(tso, out TextLayout rest);
                                page.Graphics.DrawTextLayout(tl, PointF.Empty);
                                if (split != SplitResult.Split)
                                {
                                    done = true;
                                    break;
                                }
                                tl = rest;
                            }
                            if (!done)
                            {
                                page           = doc.NewPage();
                                page.Landscape = true;
                                // We only want to render images on the first page, so clear ObjectRect:
                                if (tl.ObjectRects != null)
                                {
                                    tl.ObjectRects = null;
                                    // We need to redo the layout, but no need to recalculate the glyphs:
                                    tl.PerformLayout(false);
                                }
                            }
                        }
                        // Done:
                        doc.Save(stream);
                        return(doc.Pages.Count);
                    }
        }
    /// <summary>
    /// Corrects image align for RTL cultures.
    /// </summary>
    /// <param name="align">Value to parse</param>
    /// <returns>Align of an image</returns>
    private static ImageAlign GetImageAlign(ImageAlign align)
    {
        // RTL switch
        if (CultureHelper.IsUICultureRTL())
        {
            if (align == ImageAlign.Left)
            {
                align = ImageAlign.Right;
            }
            else if (align == ImageAlign.Right)
            {
                align = ImageAlign.Left;
            }
        }

        return align;
    }
示例#34
0
 protected virtual void SetAlign(ImageAlign align)
 {
     this.Call("setAlign", align.ToString().ToLowerInvariant());
 }
示例#35
0
 public int CreatePDF(Stream stream)
 {
     // Get the images to use as inline objects:
     using (var imgPuffins = Image.FromFile("Resources/ImagesBis/puffins-small.jpg"))
         using (var imgFerns = Image.FromFile("Resources/ImagesBis/ferns-small.jpg"))
         {
             // The image alignment to use:
             var ia = new ImageAlign(ImageAlignHorz.Center, ImageAlignVert.Bottom, true, true, true, false, false);
             // Create and set up the document:
             var doc  = new GcPdfDocument();
             var page = doc.NewPage();
             var g    = page.Graphics;
             // Create and set up a TextLayout object to print the text:
             var tl = g.CreateTextLayout();
             tl.MaxWidth                = page.Size.Width;
             tl.MaxHeight               = page.Size.Height;
             tl.MarginLeft              = tl.MarginRight = tl.MarginTop = tl.MarginBottom = 36;
             tl.DefaultFormat.Font      = StandardFonts.Times;
             tl.DefaultFormat.FontSize  = 12;
             tl.DefaultFormat.BackColor = Color.LightGoldenrodYellow;
             tl.TextAlignment           = TextAlignment.Justified;
             // Create inline objects using the images and arbitrary sizes:
             var ioPuffins = new InlineObject(imgPuffins, 36, 24);
             var ioFerns   = new InlineObject(imgFerns, 36, 24);
             // Build up the text:
             tl.Append(
                 "The 'Inline objects' feature of the TextLayout class allows to insert arbitrary objects " +
                 "into a block of text. Those objects are then treated exactly like other text runs, " +
                 "and keep their positions relative to the surrounding text. " +
                 "In this sample, we insert some images into the text as inline objects, " +
                 "use the TextLayout class to position them along with text, and draw them " +
                 "using the GcGraphics.DrawImage method. "
                 );
             tl.Append("Here are some puffins: ");
             tl.Append(ioPuffins);
             tl.Append(" and here are some ferns: ");
             tl.Append(ioFerns);
             tl.Append(" The end.");
             //
             System.Diagnostics.Debug.Assert(tl.InlineObjects.Count == 0, "InlineObjects is filled by RecalculateGlyphs");
             // This method fetches and measures the glyphs needed to render the text,
             // because we draw the same text a few times with different layout,
             // we call this once before the loop below:
             tl.RecalculateGlyphs();
             //
             System.Diagnostics.Debug.Assert(tl.InlineObjects.Count == 2, "InlineObjects is filled by RecalculateGlyphs");
             // In a loop, draw the text and inline images in 3 different locations
             // and bounds on the page:
             for (int i = 0; i < 3; ++i)
             {
                 tl.MarginTop   = tl.ContentRectangle.Bottom + 36;
                 tl.MarginLeft  = 36 + 72 * i;
                 tl.MarginRight = 36 + 72 * i;
                 // Note passing 'false' here, we do not need to recalc the glyphs because
                 // the text has not changed:
                 tl.PerformLayout(false);
                 // Draw the text and images:
                 g.DrawTextLayout(tl, PointF.Empty);
                 foreach (var io in tl.InlineObjects)
                 {
                     g.DrawImage((Image)io.Object, io.ObjectRect.ToRectangleF(), null, ia);
                 }
             }
             // Done:
             doc.Save(stream);
             return(doc.Pages.Count);
         }
 }
示例#36
0
        void LoadClientData(Stream ms, string updatePathVar, string customUrlArgs)
        {
            ms.Position = 0;

            // Read back the file identification data, if any
            if (!ReadFiles.IsHeaderValid(ms, "IUCDFV2"))
            {
                //free up the file so it can be deleted
                ms.Close();

                throw new Exception("The client file does not have the correct identifier - this is usually caused by file corruption.");
            }

#if !CLIENT_READER
            LanguageCulture lastLanguage = null;
#endif
            string serverSite;
            byte   bType = (byte)ms.ReadByte();
            while (!ReadFiles.ReachedEndByte(ms, bType, 0xFF))
            {
                switch (bType)
                {
                case 0x01:    //Read Company Name
                    CompanyName = ReadFiles.ReadDeprecatedString(ms);
                    break;

                case 0x02:    //Product Name
                    ProductName = ReadFiles.ReadDeprecatedString(ms);
                    break;

                case 0x0A:     // GUID
                    m_GUID = ReadFiles.ReadString(ms);
                    break;

                case 0x03:    //Read Installed Version
                    InstalledVersion = ReadFiles.ReadDeprecatedString(ms);
                    break;

                case 0x04:    //Add server file site

                    serverSite = ReadFiles.ReadDeprecatedString(ms);

                    if (updatePathVar != null)
                    {
                        serverSite = serverSite.Replace("%updatepath%", updatePathVar);
                    }

                    if (customUrlArgs != null)
                    {
                        serverSite = serverSite.Replace("%urlargs%", customUrlArgs);
                    }

                    AddUniqueString(serverSite, ServerFileSites);


                    break;

                case 0x09:    //Add client server file site

                    serverSite = ReadFiles.ReadDeprecatedString(ms);

                    if (updatePathVar != null)
                    {
                        serverSite = serverSite.Replace("%updatepath%", updatePathVar);
                    }

                    if (customUrlArgs != null)
                    {
                        serverSite = serverSite.Replace("%urlargs%", customUrlArgs);
                    }

                    AddUniqueString(serverSite, ClientServerSites);
                    break;

                case 0x11:    //Header image alignment
                    try
                    {
                        HeaderImageAlign = (ImageAlign)Enum.Parse(typeof(ImageAlign), ReadFiles.ReadDeprecatedString(ms));
                    }
                    catch { }
                    break;

                case 0x12:    //Header text indent
                    HeaderTextIndent = ReadFiles.ReadInt(ms);
                    break;

                case 0x13:    //Header text color
                    HeaderTextColorName = ReadFiles.ReadDeprecatedString(ms);
                    break;

                case 0x14:     //header image filename
                    TopImageFilename = ReadFiles.ReadDeprecatedString(ms);
                    break;

                case 0x15:     //side image filename
                    SideImageFilename = ReadFiles.ReadDeprecatedString(ms);
                    break;

#if CLIENT_READER
                case 0x18:     // language culture
                    Languages.Add(ReadFiles.ReadDeprecatedString(ms));
                    break;
#else
                case 0x18:     // language culture

                    lastLanguage = new LanguageCulture(ReadFiles.ReadDeprecatedString(ms));

                    Languages.Add(lastLanguage.Culture, lastLanguage);
                    break;

                case 0x16:     //language filename

                    if (lastLanguage != null)
                    {
                        lastLanguage.Filename = ReadFiles.ReadDeprecatedString(ms);
                    }
                    else
                    {
                        Languages.Add(string.Empty, new LanguageCulture(null)
                        {
                            Filename = ReadFiles.ReadDeprecatedString(ms)
                        });
                    }

                    break;
#endif
                case 0x17:     //hide the header divider
                    HideHeaderDivider = ReadFiles.ReadBool(ms);
                    break;

                case 0x19:
                    CloseOnSuccess = ReadFiles.ReadBool(ms);
                    break;

                case 0x1A:
                    CustomWyUpdateTitle = ReadFiles.ReadString(ms);
                    break;

                case 0x1B:
                    PublicSignKey = ReadFiles.ReadString(ms);
                    break;

                case 0x1C:
                    UpdatePassword = ReadFiles.ReadString(ms);
                    break;

                default:
                    ReadFiles.SkipField(ms, bType);
                    break;
                }

                bType = (byte)ms.ReadByte();
            }

            ms.Close();
        }
示例#37
0
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;

            //
            // We want to draw 3 images in certain arbitrary locations on the first page,
            // and then print a text that would take 2-3 pages, and have it flow around
            // the images on the first page.
            //
            // Get the images and their rectangles. Note that we specify a square
            // area for all images - but they will be aligned within that area
            // preserving their original aspect ratios, so we will later retrieve
            // the actual rectangles where the images were drawn:
            using (var imgPuffins = Image.FromFile("Resources/Images/puffins.jpg"))
                using (var imgReds = Image.FromFile("Resources/Images/reds.jpg"))
                    using (var imgLavender = Image.FromFile("Resources/Images/lavender.jpg"))
                    {
                        var rectPuffins  = new RectangleF(100, 70, 180, 180);
                        var rectReds     = new RectangleF(300, 280, 180, 180);
                        var rectLavender = new RectangleF(190, 510, 180, 180);
                        // Set up ImageAlign that would fit and center an image within a specified area,
                        // preserving the image's original aspect ratio:
                        ImageAlign ia = new ImageAlign(ImageAlignHorz.Center, ImageAlignVert.Center, true, true, true, false, false);
                        // Draw each image, providing an array of rectangles as an output parameter for each DrawImage call,
                        // so that we get the actual rectangle taken by the image (an array is needed to handle tiled images):
                        g.DrawImage(imgPuffins, rectPuffins, null, ia, out RectangleF[] rectsPuffins);
                        g.DrawImage(imgReds, rectReds, null, ia, out RectangleF[] rectsReds);
                        g.DrawImage(imgLavender, rectLavender, null, ia, out RectangleF[] rectsLavender);
                        // Create and set up a TextLayout object to print the text:
                        var tl = g.CreateTextLayout();
                        tl.DefaultFormat.Font     = StandardFonts.Times;
                        tl.DefaultFormat.FontSize = 9;
                        tl.TextAlignment          = TextAlignment.Justified;
                        tl.ParagraphSpacing       = 72 / 8;
                        tl.MaxWidth  = doc.PageSize.Width;
                        tl.MaxHeight = doc.PageSize.Height;
                        // 1/2" margins all around
                        tl.MarginAll = 72 / 2;
                        // ObjectRect is the type used to specify the areas to flow around to TextLayout.
                        // We set up a local function to create an ObjecRect based on an image rectangle,
                        // adding some padding so that the result looks nicer:
                        Func <RectangleF, ObjectRect> makeObjectRect = rect_ =>
                                                                       new ObjectRect(rect_.X - 6, rect_.Y - 2, rect_.Width + 12, rect_.Height + 4);
                        // Specify the array of ObjectRects on the TextLayout:
                        tl.ObjectRects = new List <ObjectRect>()
                        {
                            makeObjectRect(rectsPuffins[0]),
                            makeObjectRect(rectsReds[0]),
                            makeObjectRect(rectsLavender[0]),
                        };
                        // Add several paragraphs of text:
                        tl.Append(Common.Util.LoremIpsum(7, 5, 6, 28, 32));
                        // Calculate glyphs and lay out the text:
                        tl.PerformLayout(true);
                        // Split options to control splitting of text between pages.
                        // We can either use the default ctor and set up values like MaxWidth etc,
                        // or create a TextSplitOptions based on the TextLayout, and clear RestObjectRects:
                        TextSplitOptions to = new TextSplitOptions(tl)
                        {
                            RestObjectRects          = null,
                            MinLinesInFirstParagraph = 2,
                            MinLinesInLastParagraph  = 2
                        };
                        // In a loop, split and render the text:
                        while (true)
                        {
                            // 'rest' will accept the text that did not fit:
                            var splitResult = tl.Split(to, out TextLayout rest);
                            doc.Pages.Last.Graphics.DrawTextLayout(tl, PointF.Empty);
                            if (splitResult != SplitResult.Split)
                            {
                                break;
                            }
                            tl = rest;
                            // We only draw images on the first page:
                            tl.ObjectRects = null;
                            doc.Pages.Add();
                        }
                        // Done:
                        doc.Save(stream);
                        return(doc.Pages.Count);
                    }
        }
示例#38
0
		public override void loadFrom(BinaryReader reader, PersistContext ctx)
		{
			base.loadFrom(reader, ctx);
			hasHeaderRows = false;

			hasSpanningCells = false;
			ctx.loadReference(this);	// load cells
			ctx.loadReference(this);	// load rows
			ctx.loadReference(this);	// load columns
			currScrollRow = reader.ReadInt32();
			scrollable = reader.ReadBoolean();
			setScrollable(scrollable);
			fillColor = ctx.loadColor();
			frameColor = ctx.loadColor();
			caption = reader.ReadString();
			captionColor = ctx.loadColor();
			captionFormat = ctx.loadStringFormat();

			captionHeight = (float)reader.ReadDouble();
			cellBorders = (CellFrameStyle)reader.ReadInt32();
			rowsCount = reader.ReadInt32();
			rowHeight = (float)reader.ReadDouble();
			columnsCount = reader.ReadInt32();
			columnWidth = (float)reader.ReadDouble();
			textColor = ctx.loadColor();
			picturePos = (ImageAlign)reader.ReadInt32();

			picture = ctx.loadImage();

			pen.Width = PenWidth;
			pen.Color = frameColor;
			pen.DashStyle = PenDashStyle;
			brush.Release();
			brush = new SolidBrush(fillColor);
			brush.AddRef();

			if (ctx.FileVersion > 3)
			{
				pen = (Pen)ctx.loadObject();
				ctx.loadReference(this);

				selStyle = (HandlesStyle)reader.ReadInt32();

				if (ctx.FileVersion > 5)
				{
					// new in save format 6
					rowAnchorPattern = ctx.loadAnchorPattern();
					enabledHandles = (Handles)reader.ReadInt64();
					style = (TableStyle)reader.ReadInt32();

					if (ctx.FileVersion > 7)
					{
						// new in file format 8
						linkStyle = (TableLinkStyle)reader.ReadInt32();

						if (ctx.FileVersion > 8)
						{
							// new in save format 9
							anchorPattern = ctx.loadAnchorPattern();

							// Load table arrows
							ctx.loadReference(this);
							ctx.loadReference(this);

							if (ctx.FileVersion > 13)
							{
								// new in save format 14
								setExpanded(reader.ReadBoolean());
								setExpandable(reader.ReadBoolean());
								useStyledText = reader.ReadBoolean();

								if (ctx.FileVersion > 18)
								{
									// new in save format 19
									customDraw = (CustomDraw)reader.ReadInt32();
									cellCustomDraw = (CustomDraw)reader.ReadInt32();

									if (ctx.FileVersion > 21)
									{
										// new in save format 22
										offsetHeaderRows = reader.ReadBoolean();

										if (ctx.FileVersion > 24)
										{
											// new in save format 25
											ctx.loadReference(this);	// captionBackBrush
										}
									}
								}
							}
						}
					}
				}
			}

			resetCoveredCells();
			updateText();
			layoutText();
		}
示例#39
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Rectangle rect = new Rectangle(ClientRectangle.X + 1, ClientRectangle.Y + 1, ClientRectangle.Width - 2, ClientRectangle.Height - 2);

            if (isMouseClick)
            {
                SolidBrush brush = new SolidBrush(Color.FromArgb(230, 230, 255));
                e.Graphics.FillRectangle(brush, rect);
            }
            else if (isActive)
            {
                LinearGradientBrush brush = new LinearGradientBrush(rect,
                                                                    Color.FromArgb(66, 116, 144),
                                                                    Color.FromArgb(167, 200, 255),
                                                                    45F);
                e.Graphics.FillRectangle(brush, rect);
            }
            else if (isMouseOver)
            {
                using (LinearGradientBrush br = new LinearGradientBrush(
                           rect, Color.Blue, Color.White, 45f))
                {
                    // Create a ColorBlend object. Note that you
                    // must initialize it before you save it in the
                    // brush's InterpolationColors property.
                    ColorBlend colorBlend = new ColorBlend();
                    colorBlend.Colors = new Color[]
                    {
                        Color.FromArgb(120, 120, 120),
                        Color.FromArgb(250, 250, 255),
                        Color.FromArgb(120, 120, 120)
                    };
                    colorBlend.Positions = new float[]
                    {
                        0f, 1 / 2f, 1f
                    };
                    br.InterpolationColors = colorBlend;

                    e.Graphics.FillRectangle(br, rect);
                }
            }
            else if (!Enabled)
            {
                LinearGradientBrush brush = new LinearGradientBrush(rect,
                                                                    Color.FromArgb(30, 30, 30),
                                                                    Color.FromArgb(150, 150, 150),
                                                                    45F);
                e.Graphics.FillRectangle(brush, rect);
            }
            else
            {
                float angle = 45f;
                if (horizontalGradient)
                {
                    angle = 90f;
                }
                using (LinearGradientBrush br = new LinearGradientBrush(
                           rect, Color.Blue, Color.White, angle))
                {
                    // Create a ColorBlend object. Note that you
                    // must initialize it before you save it in the
                    // brush's InterpolationColors property.
                    ColorBlend colorBlend = new ColorBlend();
                    colorBlend.Colors = new Color[]
                    {
                        Color.FromArgb(50, 50, 50),
                        Color.FromArgb(220, 220, 230),
                        Color.FromArgb(50, 50, 50)
                    };
                    colorBlend.Positions = new float[]
                    {
                        0f, 1 / 2f, 1f
                    };
                    br.InterpolationColors = colorBlend;

                    e.Graphics.FillRectangle(br, rect);
                }
            }

            // Draw text
            Brush foreBrush = new SolidBrush(ForeColor);

            if (isMouseClick || isMouseOver)
            {
                foreBrush = new SolidBrush(Color.SaddleBrown);
            }
            SizeF  size = e.Graphics.MeasureString(Text, Font);
            PointF pt   = new PointF((Width - size.Width) / 2 + (isMouseClick ? 1 : 0), (Height - size.Height) / 2 + (isMouseClick ? 1 : 0));

            if (!Enabled)
            {
                foreBrush = new SolidBrush(Color.Gray);
            }
            e.Graphics.DrawString(Text, Font, foreBrush, pt);
            foreBrush.Dispose();

            if (Image != null)
            {
                if (ImageAlign.Equals(ContentAlignment.BottomCenter) || ImageAlign.Equals(ContentAlignment.MiddleCenter) || ImageAlign.Equals(ContentAlignment.TopCenter))
                {
                    if (!Enabled)
                    {
                        e.Graphics.DrawImage(GrayscaleImage(Image), (Width - Image.Width) / 2, 1, Image.Width, Image.Height);
                    }
                    else
                    {
                        e.Graphics.DrawImage(Image, (Width - Image.Width) / 2, 1, Image.Width, Image.Height);
                    }
                }
                else
                {
                    if (!Enabled)
                    {
                        e.Graphics.DrawImage(GrayscaleImage(Image), 3, 1, Image.Width, Image.Height);
                    }
                    else
                    {
                        e.Graphics.DrawImage(Image, 3, 1, Image.Width, Image.Height);
                    }
                }
            }
        }
示例#40
0
			public virtual void loadFrom(BinaryReader reader, PersistContext ctx)
			{
				toolTip = "";
				hyperLink = "";

				text = reader.ReadString();
				textFormat = ctx.loadStringFormat();
				ctx.loadReference(this);

				if (ctx.FileVersion > 5)
				{
					// new in save format 6
					picturePos = (ImageAlign)reader.ReadInt32();
					picture = ctx.loadImage();

					if (ctx.FileVersion > 13)
					{
						// new in save format 14
						textColor = ctx.loadColor();
						ctx.loadReference(this);	// brush

						if (ctx.FileVersion > 17)
						{
							// new in save format 18
							toolTip = reader.ReadString();

							if (ctx.FileVersion > 18)
							{
								// new in save format 19
								hyperLink = reader.ReadString();

								if (ctx.FileVersion > 21)
								{
									// new in save format 22
									columnSpan = reader.ReadInt32();
									rowSpan = reader.ReadInt32();

									tag = null;
									bool tagAvailable = reader.ReadBoolean();
									if (tagAvailable)
										tag = ctx.loadTag();
								}
							}
						}
					}
				}

				txOptions = new Text.LayoutOptions();
				txLayout = new Text.Layout();
			}
示例#41
0
        public int CreatePDF(Stream stream)
        {
            var doc  = new GcPdfDocument();
            var font = Font.FromFile(Path.Combine("Resources", "Fonts", "segoeui.ttf"));
            // 1/2" page margins all around:
            const float margin = 36;

            // Load all images from the Resources/Images folder:
            List <ImageInfo> imageInfos = new List <ImageInfo>();

            foreach (var fname in Directory.GetFiles(Path.Combine("Resources", "Images"), "*", SearchOption.AllDirectories))
            {
                imageInfos.Add(new ImageInfo()
                {
                    Name = Path.GetFileName(fname), Image = Util.ImageFromFile(fname)
                });
            }
            imageInfos.Shuffle();
            // Set up image alignment that would center images horizontally and align to top vertically:
            ImageAlign ia = new ImageAlign(ImageAlignHorz.Center, ImageAlignVert.Top, true, true, true, false, false);
            // Image rectangle for full-sized images - whole page:
            RectangleF rBig = new RectangleF(margin, margin, doc.PageSize.Width - margin * 2, doc.PageSize.Height - margin * 2);

            // Render all images full-size, one image per page:
            for (int i = 0; i < imageInfos.Count; ++i)
            {
                var g  = doc.NewPage().Graphics;
                var ii = imageInfos[i];
                g.DrawImage(ii.Image, rBig, null, ia);
                ii.PageIdx = i;
            }
            // Insert page(s) with thumbnails into the beginning of the document as a 4x5 grid (see SlidePages):
            const int rows = 5;
            const int cols = 4;
            float     gapx = 72f / 4, gapy = gapx;
            float     sWidth  = (doc.PageSize.Width - margin * 2 + gapx) / cols;
            float     sHeight = (doc.PageSize.Height - margin * 2 + gapy) / rows;

            if (sWidth > sHeight)
            {
                gapx  += sWidth - sHeight;
                sWidth = sHeight;
            }
            else
            {
                gapy   += sHeight - sWidth;
                sHeight = sWidth;
            }
            const float sMargin = 72f / 6;

            // Center thumbnails vertically too:
            ia.AlignVert = ImageAlignVert.Center;
            // Text format for image captions:
            TextFormat tf = new TextFormat()
            {
                Font = font, FontSize = sMargin * 0.65f
            };
            // Insertion point:
            PointF ip   = new PointF(margin, margin);
            var    page = doc.Pages.Insert(0);

            for (int i = 0; i < imageInfos.Count(); ++i)
            {
                var ii   = imageInfos[i];
                var rect = new RectangleF(ip, new SizeF(sWidth - gapx, sHeight - gapy));
                // Add a link to the page where the full-sized image is (the page index
                // will be updated when we know how many pages are in TOC, see below):
                page.Annotations.Add(new LinkAnnotation(rect, new DestinationFit(ii.PageIdx)));
                // Draw thumbnail:
                var g = page.Graphics;
                g.FillRectangle(rect, Color.LightGray);
                g.DrawRectangle(rect, Color.Black, 0.5f);
                rect.Inflate(-sMargin, -sMargin);
                g.DrawImage(ii.Image, rect, null, ia, out RectangleF[] imageRect);
                g.DrawRectangle(imageRect[0], Color.DarkGray, 1);
                // Print image file name as caption in the bottom slide margin:
                g.DrawString(ii.Name, tf,
                             new RectangleF(rect.X, rect.Bottom, rect.Width, sMargin),
                             TextAlignment.Center, ParagraphAlignment.Near, false);
                ip.X += sWidth;
                if (ip.X + sWidth > doc.PageSize.Width)
                {
                    ip.X  = margin;
                    ip.Y += sHeight;
                    if (ip.Y + sHeight > doc.PageSize.Height)
                    {
                        page = doc.Pages.Insert(doc.Pages.IndexOf(page) + 1);
                        ip.Y = margin;
                    }
                }
            }
            // We now go through all TOC pages, updating page indices in links' destinations
            // to account for the TOC pages inserted in the beginning of the document:
            int tocPages = doc.Pages.IndexOf(page) + 1;

            for (int i = 0; i < tocPages; ++i)
            {
                foreach (var ann in doc.Pages[i].Annotations)
                {
                    if (ann is LinkAnnotation link && link.Dest is DestinationFit dest)
                    {
                        link.Dest = new DestinationFit(dest.PageIndex.Value + tocPages);
                    }
                }
            }
            // Done:
            doc.Save(stream);
            imageInfos.ForEach((ii_) => ii_.Image.Dispose());
            return(doc.Pages.Count);
        }
示例#42
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Rectangle rect = new Rectangle(ClientRectangle.X + 1, ClientRectangle.Y + 1, ClientRectangle.Width - 2, ClientRectangle.Height - 2);

            if (isMouseClick)
            {
                SolidBrush brush = new SolidBrush(Color.FromArgb(230, 230, 255));
                e.Graphics.FillRectangle(brush, rect);
            }
            else if (isActive)
            {
                LinearGradientBrush brush = new LinearGradientBrush(rect,
                                                                    Color.FromArgb(66, 116, 144),
                                                                    Color.FromArgb(167, 200, 255),
                                                                    45F);
                e.Graphics.FillRectangle(brush, rect);
            }

            else if (isMouseOver)
            {
                LinearGradientBrush brush = new LinearGradientBrush(rect,
                                                                    Color.FromArgb(120, 120, 120),
                                                                    Color.FromArgb(250, 250, 255),
                                                                    45F);
                e.Graphics.FillRectangle(brush, rect);
            }
            else
            {
                LinearGradientBrush brush = new LinearGradientBrush(rect,
                                                                    Color.FromArgb(90, 90, 90),
                                                                    Color.FromArgb(220, 220, 230),
                                                                    45F);
                e.Graphics.FillRectangle(brush, rect);
            }

            // Draw text
            Brush foreBrush = new SolidBrush(ForeColor);

            if (isMouseClick || isMouseOver)
            {
//                foreBrush = new SolidBrush(Color.Yellow);
            }
            SizeF  size = e.Graphics.MeasureString(Text, Font);
            PointF pt   = new PointF((Width - size.Width) / 2 + (isMouseClick ? 1 : 0), (Height - size.Height) / 2 + (isMouseClick ? 1 : 0));

            e.Graphics.DrawString(Text, Font, foreBrush, pt);
            foreBrush.Dispose();

            if (Image != null)
            {
                if (ImageAlign.Equals(ContentAlignment.BottomCenter) || ImageAlign.Equals(ContentAlignment.MiddleCenter) || ImageAlign.Equals(ContentAlignment.TopCenter))
                {
                    e.Graphics.DrawImage(Image, (Width - Image.Width) / 2, 1, Image.Width, Image.Height);
                }
                else
                {
                    e.Graphics.DrawImage(Image, 3, 1, Image.Width, Image.Height);
                }
            }
        }
示例#43
0
 protected virtual void SetAlign(ImageAlign align)
 {
     this.AddScript("{0}.setAlign({1});", this.ClientID, JSON.Serialize(align.ToString().ToLower()));
 }
示例#44
0
		/// <summary>
		/// Returns new dimensions of the image's bounding rect according to its parameters
		/// </summary>
		/// <param name="pict">Image reference</param>
		/// <param name="rect">Image bounding rect</param>
		/// <param name="ppos">Image alignment</param>
		/// <param name="picw">New image's width value</param>
		/// <param name="pich">New image's height value</param>
		/// <param name="xoff">Image's X offset</param>
		/// <param name="yoff">Image's Y offset</param>
		/// <returns>true if successfull otherwise false</returns>
		public bool GetImageDim(Image pict, RectangleF rect, ImageAlign ppos, ref float  picw, ref float pich , ref float xoff , ref float yoff)
		{
			bool bOk = false;
			int xc = 0, yc = 0;

			try
			{
			
				if ( rect.Equals(RectangleF.Empty))
					return false;

				picw = 0;
				pich = 0;
				xoff =0;
				yoff =0;

				Graphics g = System.Drawing.Graphics.FromHwnd(GetActiveWindow());
				setTransforms(g);

				// get image logical size in document coordinates
				RectangleF sizeDev = RectangleF.FromLTRB(0, 0,
					(float)pict.Size.Width / pict.HorizontalResolution * g.DpiX * g.PageScale,
					(float)pict.Size.Height / pict.VerticalResolution * g.DpiY * g.PageScale);
				RectangleF sizeDoc = deviceToDoc(g, sizeDev);
				picw = sizeDoc.Width;
				pich = sizeDoc.Height;

				
				switch (ppos)
				{
					case ImageAlign.TopLeft:
						xoff = rect.Left;
						yoff = rect.Top;
						break;
					case ImageAlign.BottomLeft:
						xoff = rect.Left;
						yoff = rect.Bottom - pich;
						break;
					case ImageAlign.TopRight:
						xoff = rect.Right - picw;
						yoff = rect.Top;
						break;
					case ImageAlign.BottomRight:
						xoff = rect.Right - picw;
						yoff = rect.Bottom - pich;
						break;
					case ImageAlign.Center:
						xoff = (rect.Right + rect.Left - picw) / 2;
						yoff = (rect.Bottom + rect.Top - pich) / 2;
						break;
					case ImageAlign.TopCenter:
						xoff = rect.X + rect.Width / 2 - picw / 2;
						yoff = rect.Y;
						break;
					case ImageAlign.BottomCenter:
						xoff = rect.X + rect.Width / 2 - picw / 2;
						yoff = rect.Bottom - pich;
						break;
					case ImageAlign.MiddleLeft:
						xoff = rect.X;
						yoff = rect.Y + rect.Height / 2 - pich / 2;
						break;
					case ImageAlign.MiddleRight:
						xoff = rect.Right - picw;
						yoff = rect.Y + rect.Height / 2 - pich / 2;
						break;
					case ImageAlign.Fit:
					{
						float h = rect.Bottom - rect.Top;
						float w = rect.Right - rect.Left;
						if (h == 0) break;

						float ratioCtrl = w / h;
						float ratioPic = picw / pich;

						if (ratioCtrl > ratioPic)
						{
							//stretch vertically
							pich = (int)h;
							picw = (int)(ratioPic * pich);
							yoff = rect.Top;
							xoff = (rect.Right + rect.Left - picw) / 2;
						}
						else
						{
							//stretch horizontally
							picw = (int)w;
							if (ratioPic == 0) break;
							pich = (int)(picw / ratioPic);
							xoff = rect.Left;
							yoff = (rect.Bottom + rect.Top - pich) / 2;
						}
					}
						break;
					case ImageAlign.Stretch:
					{
						picw = rect.Right - rect.Left;
						pich = rect.Bottom - rect.Top;
						xoff = rect.Left; yoff = rect.Top;
					}
						break;
					case ImageAlign.Tile:
					{
						xoff = rect.Left; yoff = rect.Top;
						xc = (int)((rect.Right - rect.Left) / picw) + 1;
						yc = (int)((rect.Bottom - rect.Top) / pich) + 1;
					}
						break;

					default:
						return false;
				}

				PointF center = new PointF(
					rect.X + rect.Width / 2,
					rect.Y + rect.Height / 2);
				bOk = true;
			}
		
			catch ( Exception ex )
			{
				Trace.WriteLine(String.Format("{0} error {1}\n","SvgManager.GetImageDim",ex.Message));
				bOk = false;
			}
			
			return bOk;
		}
示例#45
0
        // The main sample driver.
        public int CreatePDF(Stream stream)
        {
            GcPdfDocument doc = new GcPdfDocument();
            // This will hold the llst of images so we can dispose them after saving the document:
            List <IDisposable> disposables = new List <IDisposable>();

            // Page footer:
            var ftrImg = Image.FromFile(Path.Combine("Resources", "ImagesBis", "logo-GC-devsol.png"));

            disposables.Add(ftrImg);
            var fx    = ftrImg.HorizontalResolution / 72f;
            var fy    = ftrImg.VerticalResolution / 72f;
            var ftrRc = new RectangleF(
                doc.PageSize.Width / 2 - ftrImg.Width / fx / 2,
                doc.PageSize.Height - 40,
                ftrImg.Width / fx,
                ftrImg.Height / fy);

            // Color for the title:
            var colorBlue = Color.FromArgb(0x3B, 0x5C, 0xAA);
            // Color for the highlights:
            var colorRed = Color.Red;
            // The text layout used to render text:
            TextLayout tl = new TextLayout(72)
            {
                MaxWidth     = doc.PageSize.Width,
                MaxHeight    = doc.PageSize.Height,
                MarginLeft   = 72,
                MarginRight  = 72,
                MarginTop    = 72,
                MarginBottom = 72,
            };

            tl.DefaultFormat.Font     = Font.FromFile(Path.Combine("Resources", "Fonts", "segoeui.ttf"));
            tl.DefaultFormat.FontSize = 11;

            var page = doc.NewPage();

            addFtr();
            var g = page.Graphics;

            // Caption:
            tl.TextAlignment = TextAlignment.Center;
            tl.Append("Introduction\n", new TextFormat()
            {
                FontSize = 16, ForeColor = colorBlue
            });
            tl.Append("The Importance of Wetlands", new TextFormat()
            {
                FontSize = 13, ForeColor = colorBlue
            });
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);

            // Move below the caption for the first para:
            tl.MarginTop = tl.ContentHeight + 72 * 2;
            tl.Clear();
            tl.TextAlignment    = TextAlignment.Leading;
            tl.ParagraphSpacing = 12;

            // For the first para we want a bigger initial letter, but no first line indent,
            // so we render it separately from the rest of the text:
            tl.Append(_paras[0].Substring(0, 1), new TextFormat(tl.DefaultFormat)
            {
                FontSize = 22
            });
            addPara(_paras[0].Substring(1));
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);

            // Account for the first para, and set up the text layout
            // for the rest of the text (a TextLayout allows to render multiple paragraphs,
            // but they all must have the same paragraph format):
            tl.MarginTop = tl.ContentRectangle.Bottom;
            tl.Clear();
            tl.FirstLineIndent = 36;

            // Add remaining paragraphs:
            foreach (var para in _paras.Skip(1))
            {
                // Paragraphs starting with '::' indicate images to be rendered across the page width:
                if (para.StartsWith("::"))
                {
                    var img = Image.FromFile(Path.Combine("Resources", "ImagesBis", para.Substring(2)));
                    disposables.Add(img);
                    var w = tl.MaxWidth.Value - tl.MarginLeft - tl.MarginRight;
                    var h = (float)img.Height / (float)img.Width * w;
                    tl.AppendInlineObject(img, w, h);
                    tl.AppendLine();
                }
                else
                {
                    addPara(para);
                }
            }
            // Layout the paragraphs:
            tl.PerformLayout(true);
            // Text split options allow to implement widow and orphan control:
            var tso = new TextSplitOptions(tl)
            {
                RestMarginTop            = 72,
                MinLinesInFirstParagraph = 2,
                MinLinesInLastParagraph  = 2,
            };
            // Image alignment used to render the pictures:
            var ia = new ImageAlign(ImageAlignHorz.Left, ImageAlignVert.Top, true, true, true, false, false)
            {
                BestFit = true
            };

            // In a loop, split and render the text:
            while (true)
            {
                var splitResult = tl.Split(tso, out TextLayout rest);
                g = doc.Pages.Last.Graphics;
                doc.Pages.Last.Graphics.DrawTextLayout(tl, PointF.Empty);
                // Render all images that occurred on this page:
                foreach (var io in tl.InlineObjects)
                {
                    doc.Pages.Last.Graphics.DrawImage((Image)io.Object, io.ObjectRect.ToRectangleF(), null, ia);
                }
                // Break unless there is more to render:
                if (splitResult != SplitResult.Split)
                {
                    break;
                }
                // Assign the remaining text to the 'main' TextLayout, add a new page and continue:
                tl = rest;
                doc.Pages.Add();
                addFtr();
            }

            // Save the PDF:
            doc.Save(stream);
            // Dispose images (can be done only after saving the document):
            disposables.ForEach(d_ => d_.Dispose());
            // Done:
            return(doc.Pages.Count);

            void addPara(string para)
            {
                // We implement a primitive markup to highlight some fragments in red:
                var txt = para.Split(new string[] { "<red>", "</red>" }, StringSplitOptions.None);

                for (int i = 0; i < txt.Length; ++i)
                {
                    if (i % 2 == 0)
                    {
                        tl.Append(txt[i]);
                    }
                    else
                    {
                        tl.Append(txt[i], new TextFormat(tl.DefaultFormat)
                        {
                            ForeColor = colorRed
                        });
                    }
                }
                tl.AppendLine();
            }

            void addFtr()
            {
                doc.Pages.Last.Graphics.DrawImage(ftrImg, ftrRc, null, ImageAlign.StretchImage);
            }
        }