private void btnInsertSelectedFiles_Click(object sender, EventArgs e)
        {
            Word.Selection selection = Globals.ThisAddIn.Application.Selection;
            int objectsInWord = Globals.ThisAddIn.Application.ActiveDocument.InlineShapes.Count;
            selection.Collapse(Word.WdCollapseDirection.wdCollapseStart);
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (Convert.ToBoolean(row.Cells[0].Value) == true)
                {

                    string emfPath = @"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\" + jobNumber +"\\" + Convert.ToString(row.Cells[1].Value);
                    using (var src = new Metafile(emfPath))
                    using (var bmp = new Bitmap(@"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\blank.tif"))
                    using (var gr = Graphics.FromImage(bmp))
                    {

                        gr.DrawImage(src, new Rectangle(0, 0, bmp.Width, bmp.Height));
                        bmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        imageOperations.ConvertToBlackAndWhite(bmp);
                        imageOperations.createPDF(bmp, @"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\newPDF_" + jobNumber + ".pdf");
                        bmp.Save(@"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\" + jobNumber + "\\" + Convert.ToString(row.Cells[1].Value).Split('.')[0] + ".tif", ImageFormat.Bmp);
                        msWordOperations.addSection(Word.WdOrientation.wdOrientLandscape);
                        selection.InlineShapes.AddOLEObject("Paint.Picture", @"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\" + jobNumber + "\\" + Convert.ToString(row.Cells[1].Value).Split('.')[0] + ".tif", true);
                        objectsInWord++;

                        Globals.ThisAddIn.Application.ActiveDocument.InlineShapes[objectsInWord].Height = 450.0f;
                        Globals.ThisAddIn.Application.ActiveDocument.InlineShapes[objectsInWord].Width = 684.0f;

                        gr.Dispose();
                        bmp.Dispose();
                        src.Dispose();
                    }
                    System.GC.Collect();

                }

            }
            this.Close();
        }
Beispiel #2
0
        public Size GetInsetName(string p_Path, string p_FileName, string p_FileExt)
        {
            Size ImageSize;
            Font Fnt = new Font("Arial", 8);
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
            Graphics g = Graphics.FromImage(bmp);

            //*** Get maximum width of Title / Subtitle
            ImageSize = g.MeasureString(m_Name, Fnt).ToSize();

            ImageSize.Width = ImageSize.Width + 20;
            ImageSize.Height = ImageSize.Height + 20;

            bmp = new System.Drawing.Bitmap(ImageSize.Width, ImageSize.Height);
            g = Graphics.FromImage(bmp);
            switch (p_FileExt.ToLower())
            {
                case "emf":
                    IntPtr hRefDC = g.GetHdc();
                    Metafile m = new Metafile(p_Path + "\\" + p_FileName + ".emf", hRefDC);
                    g.ReleaseHdc(hRefDC);
                    Graphics gMeta = Graphics.FromImage(m);
                    gMeta.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    m.Dispose();
                    gMeta.Dispose();
                    break;
                case "png":
                    g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
                    break;
                case "jpg":
                    g.Clear(Color.White);
                    g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
                    break;
                case "bmp":
                    g.Clear(Color.White);
                    g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
                    break;
                case "gif":
                    g.Clear(Color.White);
                    g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
                    break;
                case "tiff":
                    g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
                    break;
                case "ico":
                    g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
                    break;
            }

            bmp.Dispose();
            bmp = null;
            g.Dispose();

            Fnt.Dispose();
            return ImageSize;
        }
Beispiel #3
0
        private static string GetRtfImage(Image _image, Control CurControl) 
        {
            StringBuilder _rtf = null;

            // Used to store the enhanced metafile
            MemoryStream _stream = null;

            // Used to create the metafile and draw the image
            Graphics _graphics = null;

            // The enhanced metafile
            Metafile _metaFile = null;

            // Handle to the device context used to create the metafile
            IntPtr _hdc;

            try 
            {
                _rtf = new StringBuilder();
                _stream = new MemoryStream();

                // Get a graphics context from the RichTextBox
                using (_graphics = CurControl.CreateGraphics()) 
                {

                    // Get the device context from the graphics context
                    _hdc = _graphics.GetHdc();

                    // Create a new Enhanced Metafile from the device context
                    _metaFile = new Metafile(_stream, _hdc);

                    // Release the device context
                    _graphics.ReleaseHdc(_hdc);
                }
            
                using(_graphics = Graphics.FromImage(_metaFile)) 
                {

                    // Draw the image on the Enhanced Metafile
                    _graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
                }
                IntPtr _hEmf = _metaFile.GetHenhmetafile();

                // A call to EmfToWmfBits with a null buffer return the size of the
                // buffer need to store the WMF bits.  Use this to get the buffer
                // size.
                uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC,
                EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                // Create an array to hold the bits
                byte[] _buffer = new byte[_bufferSize];

                // A call to EmfToWmfBits with a valid buffer copies the bits into the
                // buffer an returns the number of bits in the WMF.  
                uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC,
                EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                // Append the bits to the RTF string
                for(int i = 0; i < _buffer.Length; ++i) 
                {
                    _rtf.Append(String.Format("{0:X2}", _buffer[i]));
                }

                return _rtf.ToString();
            }
            finally 
            {
                if(_graphics != null)
                _graphics.Dispose();
                if(_metaFile != null)
                _metaFile.Dispose();
                if(_stream != null)
                _stream.Close();
            }
        }
Beispiel #4
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="shapes"></param>
        /// <param name="properties"></param>
        /// <param name="ic"></param>
        /// <returns></returns>
        public MemoryStream MakeMetafileStream(
            Bitmap bitmap,
            IEnumerable<BaseShape> shapes,
            ImmutableArray<ShapeProperty> properties,
            IImageCache ic)
        {
            var g = default(Graphics);
            var mf = default(Metafile);
            var ms = new MemoryStream();

            try
            {
                using (g = Graphics.FromImage(bitmap))
                {
                    var hdc = g.GetHdc();
                    mf = new Metafile(ms, hdc);
                    g.ReleaseHdc(hdc);
                }

                using (g = Graphics.FromImage(mf))
                {
                    var r = new EmfRenderer(72.0 / 96.0);
                    r.State.ImageCache = ic;

                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.PageUnit = GraphicsUnit.Display;

                    if (shapes != null)
                    {
                        foreach (var shape in shapes)
                        {
                            shape.Draw(g, r, 0, 0, properties, null);
                        }
                    }

                    r.ClearCache(isZooming: false);
                }
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }

                if (mf != null)
                {
                    mf.Dispose();
                }
            }
            return ms;
        }
Beispiel #5
0
 /// <summary>
 /// Copies the given <see cref="T:System.Drawing.Imaging.MetaFile" /> to the specified file. If the file does not exist, it will be created.
 /// The given <see cref="T:System.Drawing.Imaging.MetaFile" /> is set to an invalid state inside this function.
 /// </summary>
 public static bool SaveEnhMetaFile(string fileName, Metafile metafile)
 {
     if (metafile == null) throw new ArgumentNullException("metafile");
     bool result = false;
     IntPtr hEmf = metafile.GetHenhmetafile();
     if (hEmf != IntPtr.Zero) {
         IntPtr resHEnh = CopyEnhMetaFile(hEmf, fileName);
         if (resHEnh != IntPtr.Zero) {
             DeleteEnhMetaFile(resHEnh);
             result = true;
         }
         DeleteEnhMetaFile(hEmf);
         metafile.Dispose();
     }
     return result;
 }
Beispiel #6
0
 protected virtual void ExportImage(string filename, string format)
 {
     try
     {
     uint pages;
     Image exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);		// create export draw area
     Graphics drawDestination = Graphics.FromImage(exportImage);
     Graphics grph;
     IntPtr ipHDC;																	//necessary for wmf and emf export
     Metafile mf;
     //EMetafile ef;
     pages = GetPages();		// calculate imageBitmap page count
     if (pages > 0)																	// something to do?
     {
         if (filename.LastIndexOf('.') >= (filename.Length-4)){
             filename = filename.Substring(0,filename.LastIndexOf('.'));
         }
         for (uint i=1; i<=pages; i++){
             switch (format.ToUpper()){				// identify selected format
                 case "BMP":
                     drawDestination.Clear(Color.White);
                     DrawPage(drawDestination,i);
                     exportImage.Save(filename + "_" + i + ".bmp");
                     break;
                 case "GIF":
                     drawDestination.Clear(Color.White);
                     DrawPage(drawDestination,i);
                     exportImage.Save(filename + "_" + i + ".gif",System.Drawing.Imaging.ImageFormat.Gif);
                     break;
                 case "JPG":
                     drawDestination.Clear(Color.White);
                     DrawPage(drawDestination,i);
                     exportImage.Save(filename + "_" + i + ".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
                     break;
                 case "PNG":
                     drawDestination.Clear(Color.White);
                     DrawPage(drawDestination,i);
                     exportImage.Save(filename + "_" + i + ".png",System.Drawing.Imaging.ImageFormat.Png);
                     break;
                 case "WMF":
                     drawDestination.Clear(Color.White);
                     exportImage.Save(filename + "_" + i + ".wmf",System.Drawing.Imaging.ImageFormat.Wmf);		// for save as wmf first empty wmf file shall be created
                     grph = this.CreateGraphics();
                     ipHDC = grph.GetHdc();
                     mf = new Metafile(filename + "_" + i + ".wmf", ipHDC); 										// open created empty wmf file
                     grph = Graphics.FromImage(mf);
                     grph.Clear(Color.White);
                     grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                     grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                     DrawPage(grph,i);														// draw imageBitmap direct to wmf file
                     grph.Dispose();
                     mf.Dispose();
                     break;
                 case "EMF":
                     drawDestination.Clear(Color.White);
                     exportImage.Save(filename + "_" + i + ".emf",System.Drawing.Imaging.ImageFormat.Emf);  		// for save as emf first empty wmf file shall be created
                     grph = this.CreateGraphics();
                     ipHDC = grph.GetHdc();
                     mf = new Metafile(filename + "_" + i + ".emf", ipHDC); 										// open created empty emf file
                     grph = Graphics.FromImage(mf);
                     grph.Clear(Color.White);
                     grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                     grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                     DrawPage(grph,i);														// draw imageBitmap direct to emf file
                     grph.Dispose();
                     mf.Dispose();
                     break;
             }
         }
     }
     Worksheet tmpWorksheet = new Worksheet();						// recalculate back line hights for screen output
     tmpWorksheet.Width = worksheet.GetWorksheetWidth();
     tmpWorksheet.Height = worksheet.GetWorksheetHeight();
     tmpWorksheet.SetMargins(0,0,0,0);
     drawDestination.Dispose();
     exportImage.Dispose();
     }
     catch(Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Beispiel #7
0
 void saveAsImageFile()
 {
     if (File.Exists(m_strTreeFile))
     {
         Graphics grfx = CreateGraphics();
         IntPtr ipHdc = grfx.GetHdc();
         string strMetafile = createFileName("emf");
         mf = new Metafile(strMetafile, ipHdc);
         grfx.ReleaseHdc(ipHdc);
         grfx.Dispose();
         Graphics grfxMF = Graphics.FromImage(mf);
         grfxMF.PageUnit = GraphicsUnit.Millimeter;
         grfxMF.PageScale = .01f;
         SolidBrush brush = new SolidBrush(tree.BackgroundColor);
         PointF pf = new PointF(0f, 0f);
         if (Environment.OSVersion.Platform == PlatformID.Win32Windows)
         {   // adjust because Win98 is extra high (for some reason...)
             pf.Y = grfxMF.DpiY / .254f;
         }
         if (tree.TrySmoothing && tree.TryPixelOffset)
             tree.XSize += 6; // adjust for the pixel offset
         grfxMF.FillRectangle(brush, 0, 0, tree.XSize, tree.YSize + (int)pf.Y);
         tree.Draw(grfxMF, tree.LinesColor);
         brush.Dispose();
         grfxMF.Dispose();
         string strFile;
         if (m_bUseBmp)
         {
             strFile = createFileName("bmp");
             mf.Save(strFile, ImageFormat.Bmp);
         }
         if (m_bUseGif)
         {
             strFile = createFileName("gif");
             mf.Save(strFile, ImageFormat.Gif);
         }
         if (m_bUseJpg)
         {
             strFile = createFileName("jpg");
             mf.Save(strFile, ImageFormat.Jpeg);
         }
         if (m_bUsePng)
         {
             strFile = createFileName("png");
             mf.Save(strFile, ImageFormat.Png);
         }
         if (m_bUseTif)
         {
             strFile = createFileName("tif");
             mf.Save(strFile, ImageFormat.Tiff);
         }
         mf.Dispose();
         if (!m_bUseEmf)
             File.Delete(strMetafile);
     }
 }
Beispiel #8
0
		private static void SaveAsImage(IPrintable document, string path,
			ImageFormat format, bool selectedOnly, bool transparent)
		{
			const int Margin = 20;

			RectangleF areaF = document.GetPrintingArea(selectedOnly);
			areaF.Offset(0.5F, 0.5F);
			Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
				(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));

			if (format == ImageFormat.Emf) // Save to metafile
			{
				Graphics metaG = control.CreateGraphics();
				IntPtr hc = metaG.GetHdc();
				Graphics g = null;

				try
				{
					// Set drawing parameters
					Metafile meta = new Metafile(path, hc);
					g = Graphics.FromImage(meta);
					g.SmoothingMode = SmoothingMode.HighQuality;
					if (DiagramEditor.Settings.Default.UseClearTypeForImages)
						g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
					else
						g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
					g.TranslateTransform(-area.Left, -area.Top);

					// Draw image
					IGraphics graphics = new GdiGraphics(g);
					document.Print(graphics, selectedOnly, Style.CurrentStyle);

					meta.Dispose();
				}
				catch (Exception ex)
				{
					MessageBox.Show(
						string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
							Strings.ErrorsReason, ex.Message),
						Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				finally
				{
					metaG.ReleaseHdc();
					metaG.Dispose();
					if (g != null)
						g.Dispose();
				}
			}
			else // Save to rastered image
			{
				int width = area.Width + Margin * 2;
				int height = area.Height + Margin * 2;
				PixelFormat pixelFormat;

				if (transparent)
					pixelFormat = PixelFormat.Format32bppArgb;
				else
					pixelFormat = PixelFormat.Format24bppRgb;

				using (Bitmap image = new Bitmap(width, height, pixelFormat))
				using (Graphics g = Graphics.FromImage(image))
				{
					// Set drawing parameters
					g.SmoothingMode = SmoothingMode.HighQuality;
					if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent)
						g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
					else
						g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
					g.TranslateTransform(Margin - area.Left, Margin - area.Top);

					// Draw image
					if (!transparent)
						g.Clear(Style.CurrentStyle.BackgroundColor);

					IGraphics graphics = new GdiGraphics(g);
					document.Print(graphics, selectedOnly, Style.CurrentStyle);

					try
					{
						image.Save(path, format);
					}
					catch (Exception ex)
					{
						MessageBox.Show(
							string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
								Strings.ErrorsReason, ex.Message),
							Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
		}
		void AddPictire(Plan plan, surfacesSurfaceLayerElementsElement innerElement, ref int pictureIndex)
		{
			try
			{
				if (innerElement.picture == null)
					return;

				foreach (var innerPicture in innerElement.picture)
				{
					if (string.IsNullOrEmpty(innerPicture.idx))
						innerPicture.idx = pictureIndex++.ToString();

					var picturesDirectory = GetPicturesDirectory();
					if (picturesDirectory == null)
						continue;
					var directoryInfo = new DirectoryInfo(picturesDirectory + "\\Sample" + innerPicture.idx + "." + innerPicture.ext);
					if (File.Exists(directoryInfo.FullName) == false)
						continue;

					if (innerPicture.ext == "emf")
					{
						var metafile = new Metafile(directoryInfo.FullName);
						innerPicture.ext = "bmp";
						directoryInfo = new DirectoryInfo(picturesDirectory + "\\Sample" + innerPicture.idx + "." + innerPicture.ext);
						metafile.Save(directoryInfo.FullName, ImageFormat.Bmp);
						metafile.Dispose();
					}

					var guid = ServiceFactoryBase.ContentService.AddContent(directoryInfo.FullName);
					var elementRectanglePicture = new ElementRectangle()
					{
						Left = Parse(innerElement.rect[0].left),
						Top = Parse(innerElement.rect[0].top),
						Height = Parse(innerElement.rect[0].bottom) - Parse(innerElement.rect[0].top),
						Width = Parse(innerElement.rect[0].right) - Parse(innerElement.rect[0].left),
					};

					if ((elementRectanglePicture.Left == 0) && (elementRectanglePicture.Top == 0) && (elementRectanglePicture.Width == plan.Width) && (elementRectanglePicture.Height == plan.Height))
					{
						plan.BackgroundImageSource = guid;
						plan.BackgroundSourceName = directoryInfo.FullName;
					}
					else
					{
						elementRectanglePicture.BackgroundImageSource = guid;
						elementRectanglePicture.BackgroundSourceName = directoryInfo.FullName;
						plan.ElementRectangles.Add(elementRectanglePicture);
					}
				}
			}
			catch (Exception e)
			{
				Logger.Error(e, "ConfigurationConverter.AddPictire");
			}
		}
Beispiel #10
0
		public void WorldTransforms ()
		{
			Metafile mf;
			using (Bitmap bmp = new Bitmap (100, 100, PixelFormat.Format32bppArgb)) {
				using (Graphics g = Graphics.FromImage (bmp)) {
					IntPtr hdc = g.GetHdc ();
					try {
						mf = new Metafile (hdc, EmfType.EmfPlusOnly);
					}
					finally {
						g.ReleaseHdc (hdc);
					}
				}
				using (Graphics g = Graphics.FromImage (mf)) {
					Assert.IsTrue (g.Transform.IsIdentity, "Initial/IsIdentity");
					g.ScaleTransform (2f, 0.5f);
					Assert.IsFalse (g.Transform.IsIdentity, "Scale/IsIdentity");
					g.RotateTransform (90);
					g.TranslateTransform (-2, 2);
					Matrix m = g.Transform;
					g.MultiplyTransform (m);
					// check
					float[] elements = g.Transform.Elements;
					Assert.AreEqual (-1f, elements[0], 0.00001f, "a0");
					Assert.AreEqual (0f, elements[1], 0.00001f, "a1");
					Assert.AreEqual (0f, elements[2], 0.00001f, "a2");
					Assert.AreEqual (-1f, elements[3], 0.00001f, "a3");
					Assert.AreEqual (-2f, elements[4], 0.00001f, "a4");
					Assert.AreEqual (-3f, elements[5], 0.00001f, "a5");

					g.Transform = m;
					elements = g.Transform.Elements;
					Assert.AreEqual (0f, elements[0], 0.00001f, "b0");
					Assert.AreEqual (0.5f, elements[1], 0.00001f, "b1");
					Assert.AreEqual (-2f, elements[2], 0.00001f, "b2");
					Assert.AreEqual (0f, elements[3], 0.00001f, "b3");
					Assert.AreEqual (-4f, elements[4], 0.00001f, "b4");
					Assert.AreEqual (-1f, elements[5], 0.00001f, "b5");

					g.ResetTransform ();
					Assert.IsTrue (g.Transform.IsIdentity, "Reset/IsIdentity");
				}
				mf.Dispose ();
			}
		}
Beispiel #11
0
		public void Measure ()
		{
			if (test_font == null)
				Assert.Ignore ("No font family could be found.");

			Metafile mf;
			using (Bitmap bmp = new Bitmap (100, 100, PixelFormat.Format32bppArgb)) {
				using (Graphics g = Graphics.FromImage (bmp)) {
					IntPtr hdc = g.GetHdc ();
					try {
						mf = new Metafile (hdc, EmfType.EmfPlusOnly);
					}
					finally {
						g.ReleaseHdc (hdc);
					}
				}
				using (Graphics g = Graphics.FromImage (mf)) {
					string text = "this\nis a test";
					CharacterRange[] ranges = new CharacterRange[2];
					ranges[0] = new CharacterRange (0, 5);
					ranges[1] = new CharacterRange (5, 9);

					SizeF size = g.MeasureString (text, test_font);
					Assert.IsFalse (size.IsEmpty, "MeasureString");

					StringFormat sf = new StringFormat ();
					sf.FormatFlags = StringFormatFlags.NoClip;
					sf.SetMeasurableCharacterRanges (ranges);

					RectangleF rect = new RectangleF (0, 0, size.Width, size.Height);
					Region[] region = g.MeasureCharacterRanges (text, test_font, rect, sf);
					Assert.AreEqual (2, region.Length, "MeasureCharacterRanges");
				}
				mf.Dispose ();
			}
		}
Beispiel #12
0
		private void CreateFilename (EmfType type, bool single)
		{
			string name = String.Format ("{0}-{1}.emf", type, single ? "Single" : "Multiple");
			string filename = Path.Combine (Path.GetTempPath (), name);
			Metafile mf;
			using (Bitmap bmp = new Bitmap (100, 100, PixelFormat.Format32bppArgb)) {
				using (Graphics g = Graphics.FromImage (bmp)) {
					IntPtr hdc = g.GetHdc ();
					try {
						mf = new Metafile (filename, hdc, type);
						Assert.AreEqual (0, new FileInfo (filename).Length, "Empty");
					}
					finally {
						g.ReleaseHdc (hdc);
					}
				}
				long size = 0;
				using (Graphics g = Graphics.FromImage (mf)) {
					g.FillRectangle (Brushes.BlueViolet, 10, 10, 80, 80);
					size = new FileInfo (filename).Length;
					Assert.AreEqual (0, size, "Still-Empty");
				}
// FIXME / doesn't work on mono yet
//				size = new FileInfo (filename).Length;
//				Assert.IsTrue (size > 0, "Non-Empty/GraphicsDisposed");
				if (!single) {
					// can we append stuff ?
					using (Graphics g = Graphics.FromImage (mf)) {
						g.DrawRectangle (Pens.Azure, 10, 10, 80, 80);
						// happily no :)
					}
				}
				mf.Dispose ();
				Assert.AreEqual (size, new FileInfo (filename).Length, "Non-Empty/MetafileDisposed");
			}
		}
		/// <summary>
		/// Renders a document as enhanced metafile. The metafile is rendered into a stream. You can create a metafile object afterwards from that stream.
		/// </summary>
		/// <param name="renderingProc">Procedure for rendering the document.
		/// The argument is a graphics context, which is set to GraphicsUnits equal to Points.
		/// The drawing must be inside of the boundaries of docSize.X and docSize.Y.
		/// </param>
		/// <param name="stream">Destination stream. The metafile is rendered into this stream. The stream has to be writeable and seekable. At return, the position of the stream is set to 0, thus the stream is ready to be used to create a metafile object from it.</param>
		/// <param name="docSize">Size of the document in points (1/72 inch)</param>
		/// <param name="sourceDpiResolution">The resolution in dpi of the source. This parameter is used only if creating the reference graphics context from the current printer fails. In this case, a context from a bitmap with the provided resolution is created.</param>
		/// <param name="outputScalingFactor">Output scaling factor. If less than 1, the image will appear smaller than originally, if greater than 1, the image will appear larger than originally.</param>
		/// <param name="pixelFormat">Optional: Only used if the graphics context can not be created from a printer document. Pixel format of the bitmap that is used in this case to construct the graphics context.</param>
		/// <returns>The rendered enhanced metafile (vector format).</returns>
		/// <remarks>
		/// <para>
		/// I found no other way to realize different dpi resolutions, independently of screen or printer device contexts, as to patch the resulting metafile stream with
		/// informations about an 'artifical' device, which has exactly the resolution that is neccessary. By careful choice of the size of this artifical device one can
		/// avoid rounding errors concerning resolution and size.
		/// It happens that some programs (for instance MS Word 2010 when saving as PDF document) mess up the size of the metafile graphics, if the graphics was created with a PageUnit
		/// (of the graphics context) other than PIXELS.
		/// Thus I now always use PIXEL as PageUnit and scale the graphics context accordingly.
		/// </para>
		/// <para>
		/// Another problem, which is actually without solution, is that e.g. MS Office will not show polylines with more than 8125 points. These polylines are included in the metafile,
		/// but MS Office seems to ignore them. On the other hand, CorelDraw X5 can show these polylines correctly.
		/// This problem might be related to the EmfPlus format, because MS Office will show these polylines if the EmfOnly format is used. But EmfOnly can not handle transparencies, thus
		/// it is not really a choice.
		/// </para>
		/// </remarks>
		public static void RenderAsEnhancedMetafileToStream(Action<Graphics> renderingProc, System.IO.Stream stream, PointD2D docSize, double sourceDpiResolution, double outputScalingFactor, PixelFormat pixelFormat = PixelFormat.Format32bppArgb)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");
			if (!stream.CanWrite)
				throw new ArgumentException("stream is not writeable");
			if (!stream.CanSeek)
				throw new ArgumentException("stream is not seekable");
			stream.SetLength(0);

			var scaledDocSize = docSize * outputScalingFactor;

			// our artifical device has a square size, and the size is an integer multiple of 5 inch (5 inch because this is the smallest size which converts to an integer number of millimeters: 127 mm)
			int deviceSizeInch = (int)(5 * Math.Ceiling(Math.Max(scaledDocSize.X, scaledDocSize.Y) / (72 * 5)));

			// we have to design our artifical device so that it has a resolution of sourceDpiResolution/outputScalingFactor
			// this accounts for the fact, that if
			double deviceResolution = sourceDpiResolution / outputScalingFactor;

			// then the number of pixels of the device is simple the device size in inch times the device resolution
			int devicePixelsX = (int)Math.Round(deviceSizeInch * deviceResolution);
			int devicePixelsY = (int)Math.Round(deviceSizeInch * deviceResolution);

			// device size in millimeter. Because of the choice of the device size (see above) there should be no rounding errors here
			int deviceSizeXMillimeter = (deviceSizeInch * 254) / 10;
			int deviceSizeYMillimeter = (deviceSizeInch * 254) / 10;

			// device size in micrometer
			int deviceSizeXMicrometer = deviceSizeInch * 25400;
			int deviceSizeYMicrometer = deviceSizeInch * 25400;

			// bounds of the graphic in pixels. Because it is in pixels, it is calculated with the unscaled size of the document and the sourceDpiResolution
			int graphicBoundsLeft_Pixels = 0;
			int graphicBoundsTop_Pixels = 0;
			int graphicBoundsWidth_Pixels = (int)Math.Ceiling(sourceDpiResolution * docSize.X / 72);
			int graphicBoundsHeight_Pixels = (int)Math.Ceiling(sourceDpiResolution * docSize.Y / 72);

			// position and size of the bounding box. Please not that the bounds are scaled with the outputScalingFactor
			int boundingBoxLeft_HIMETRIC = 0;
			int boundingBoxTop_HIMETRIC = 0;
			int boundingBoxWidth_HIMETRIC = (int)Math.Ceiling(scaledDocSize.X * 2540.0 / 72);
			int boundingBoxHeight_HIMETRIC = (int)Math.Ceiling(scaledDocSize.Y * 2540.0 / 72);

			Metafile metafile;
			using (var helperbitmap = new System.Drawing.Bitmap(4, 4, PixelFormat.Format32bppArgb))
			{
				using (Graphics grfxReference = Graphics.FromImage(helperbitmap))
				{
					IntPtr deviceContextHandle = grfxReference.GetHdc();

					metafile = new Metafile(
					stream,
					deviceContextHandle,
					new RectangleF(boundingBoxLeft_HIMETRIC, boundingBoxTop_HIMETRIC, boundingBoxWidth_HIMETRIC, boundingBoxHeight_HIMETRIC),
					MetafileFrameUnit.GdiCompatible,
					EmfType.EmfPlusDual); // EmfOnly is working with PolyLines with more than 8125 Points, but can not handle transparencies  // EmfPlusDual and EmfPlusOnly: there is no display of polylines with more than 8125 points, although the polyline seems embedded in the EMF. // EmfPlusOnly can not be converted to WMF

					grfxReference.ReleaseHdc();
				}
			}

			using (Graphics grfxMetafile = Graphics.FromImage(metafile))
			{
				// Set everything to high quality
				grfxMetafile.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
				grfxMetafile.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

				// 2014-10-10 Setting InterpolationMode to HighQualityBicubic and PixelOffsetMode to HighQuality
				// causes problems when rendering small bitmaps (at a large magnification, for instance the density image legend):
				// the resulting image seems a litte soft, the colors somehow distorted, so I decided not to use them here any more

				//grfxMetafile.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
				//grfxMetafile.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

				grfxMetafile.PageUnit = GraphicsUnit.Pixel; // Attention: always use pixels here. Any other choice will cause problems in some programs (see remarks above).
				grfxMetafile.PageScale = (float)(sourceDpiResolution / 72.0); // because our choice of GraphicsUnit is pixels, at the resolution of 72 dpi one point is one pixel. At a higher resolution, one point is more than one pixel.

				grfxMetafile.SetClip(new RectangleF(0, 0, (float)docSize.X, (float)docSize.Y));
				renderingProc(grfxMetafile);
			}
			stream.Flush();

			// we have to patch the resulting metafile stream with the parameters of the graphics and the device

			stream.Position = 0x04;
			var buf4 = new byte[4];
			stream.Read(buf4, 0, 4);
			int headerSize = BitConverter.ToInt32(buf4, 0); // Read the header size to make sure that Metafile header extension 2 is present

			// At position 0x08 there are the bounds of the graphic (not the bounding box, but the box for all the graphical elements)
			stream.Position = 0x08;
			stream.Write(BitConverter.GetBytes(graphicBoundsLeft_Pixels), 0, 4);
			stream.Write(BitConverter.GetBytes(graphicBoundsTop_Pixels), 0, 4);
			stream.Write(BitConverter.GetBytes(graphicBoundsWidth_Pixels), 0, 4);
			stream.Write(BitConverter.GetBytes(graphicBoundsHeight_Pixels), 0, 4);

			// At position 0x48 the device parameters are located: here the number of pixels of the device
			stream.Position = 0x48;
			stream.Write(BitConverter.GetBytes(devicePixelsX), 0, 4); //  the number of pixels of the device X
			stream.Write(BitConverter.GetBytes(devicePixelsY), 0, 4);  // the number of pixels of the device Y
			stream.Write(BitConverter.GetBytes(deviceSizeXMillimeter), 0, 4); // size X of the device in millimeter
			stream.Write(BitConverter.GetBytes(deviceSizeYMillimeter), 0, 4); // size Y of the device in millimeter

			if (headerSize >= (0x64 + 0x08))
			{
				stream.Position = 0x64;
				stream.Write(BitConverter.GetBytes(deviceSizeXMicrometer), 0, 4); // size X of the device in micrometer
				stream.Write(BitConverter.GetBytes(deviceSizeYMicrometer), 0, 4); // size Y of the device in micrometer
			}

			stream.Flush();

			stream.Position = 0;

			metafile.Dispose(); // we can safely dispose this metafile, because stream and metafile are independent of each other, and only the stream is patched
		}
Beispiel #14
0
        private string GenerateImageRtf(Image image)
        {
            MemoryStream metaFileStream = null;
            Graphics graphics = null;
            Metafile metaFile = null;

            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                metaFileStream = new MemoryStream();

                using (graphics = this.CreateGraphics())
                {
                    IntPtr hdc = graphics.GetHdc();
                    metaFile = new Metafile(metaFileStream, hdc);
                    graphics.ReleaseHdc(hdc);
                }

                using (graphics = Graphics.FromImage(metaFile))
                {
                    graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
                }

                IntPtr hMetaFile = metaFile.GetHenhmetafile();

                // get size (buller = null)
                uint bufferSize = GdipEmfToWmfBits(hMetaFile, 0, null, MM_ANISOTROPIC,
                    EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
                byte[] buffer = new byte[bufferSize];

                // do copy (buffer != null, return ignored)
                GdipEmfToWmfBits(hMetaFile, bufferSize, buffer, MM_ANISOTROPIC,
                    EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                stringBuilder.Append(BitConverter.ToString(buffer).Replace("-", ""));

                return stringBuilder.ToString();
            }
            finally
            {
                if (graphics != null)
                    graphics.Dispose();
                if (metaFile != null)
                    metaFile.Dispose();
                if (metaFileStream != null)
                    metaFileStream.Close();
            }
        }
Beispiel #15
0
        private void ExportImage(string filename, string format)
        {
            uint pages;
            Image exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);		// create export draw area
            Bitmap b= new Bitmap(100,100);
            Graphics drawDestination = Graphics.FromImage(exportImage);
            Graphics grph;
            IntPtr ipHDC;																	//necessary for wmf and emf export
            Metafile mf;
            generator.CalcLineHights(drawDestination, worksheet, MSCItem.ItemFont);
            pages = generator.GetPages(worksheet.GetWorksheetHeight());		// calculate imageBitmap page count
            if (pages > 0)																	// something to do?
            {
                if (filename.LastIndexOf('.') >= (filename.Length-4)){
                    filename = filename.Substring(0,filename.LastIndexOf('.'));
                }
                uint i = 1;
                string filenameSuffix = "";
            //				if (singlePage)
            //					i = pages = 0;
                for (; i<=pages; i++){
                    if (i > 0)
                        filenameSuffix = "_" + i.ToString();

                    if (Output.AutosizeOutputHeight){
                        uint index = i;
                        if (index > 0)
                            index--;
                        worksheet.SetWorksheetHeight((int)generator.PageHeights[index]); // correct height for export
                        exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);
                        drawDestination = Graphics.FromImage(exportImage);
                    }
                    if (Output.AutosizeOutputWidth){
                        worksheet.SetWorksheetWidth((int)generator.AutoWidth);
                    }
                    switch (format.ToUpper()){				// identify selected format
                        case "BMP":
                            drawDestination.Clear(Color.White);
                   			generator.CalcOffsets(drawDestination, worksheet);
                   			generator.DrawPage(drawDestination,worksheet, i);
                            exportImage.Save(filename + filenameSuffix + ".bmp");
                            break;
                        case "GIF":
                            drawDestination.Clear(Color.White);
                   			generator.CalcOffsets(drawDestination, worksheet);
                   			generator.DrawPage(drawDestination,worksheet, i);
                            exportImage.Save(filename + filenameSuffix + ".gif",System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                        case "JPG":
                            drawDestination.Clear(Color.White);
                   			generator.CalcOffsets(drawDestination, worksheet);
                   			generator.DrawPage(drawDestination,worksheet, i);
                            exportImage.Save(filename + filenameSuffix + ".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case "PNG":
                            drawDestination.Clear(Color.White);
                   			generator.CalcOffsets(drawDestination, worksheet);
                   			generator.DrawPage(drawDestination,worksheet, i);
                            exportImage.Save(filename + filenameSuffix + ".png",System.Drawing.Imaging.ImageFormat.Png);
                            break;
                        case "WMF":
                            drawDestination.Clear(Color.White);
                            exportImage.Save(filename + filenameSuffix + ".wmf",System.Drawing.Imaging.ImageFormat.Wmf);		// for save as wmf first empty wmf file shall be created
                            grph = Graphics.FromImage(b);
                            ipHDC = grph.GetHdc();
                            mf = new Metafile(filename + filenameSuffix + ".wmf", ipHDC); 										// open created empty wmf file
                            grph = Graphics.FromImage(mf);
                            grph.Clear(Color.White);
                            grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                            grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                   			generator.CalcOffsets(grph, worksheet);
                   			generator.DrawPage(grph,worksheet, i);
                            grph.Dispose();
                            mf.Dispose();
                            break;
                        case "EMF":
                            System.IO.FileStream st= new FileStream(filename + "_" + i + ".emf",FileMode.Create);
                            drawDestination.Clear(Color.White);
                            grph = Graphics.FromImage(b);
                            ipHDC = grph.GetHdc();
                            mf = new Metafile(st,ipHDC);
                            grph = Graphics.FromImage(mf);
                            grph.Clear(Color.White);
                            grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                            grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                   			generator.CalcOffsets(grph, worksheet);
                   			generator.DrawPage(grph,worksheet, i);
                            grph.Dispose();
                            mf.Dispose();
                            break;
                    }
                    if (verbose) {
                        if (singlePage)
                            Console.WriteLine("Diagram created.");
                        else
                            Console.WriteLine("Page " + i.ToString()+ " created.");
                    }
                }
            }
            drawDestination.Dispose();
            b.Dispose();
            exportImage.Dispose();
        }
Beispiel #16
0
        public Size GetTitleImage(string p_Path, string p_FileName, string p_FileExt)
        {
            Size TitleSize;
            Size SubTitleSize;
            Size ImageSize = new Size(0, 0);
            Font font = null;

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
            Graphics g = Graphics.FromImage(bmp);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            //*** Get maximum width of Title / Subtitle
            font = new Font(this._TemplateStyle.TitleSetting.FontTemplate.FontName, this._TemplateStyle.TitleSetting.FontTemplate.FontSize, this._TemplateStyle.TitleSetting.FontTemplate.FontStyle);
            TitleSize = g.MeasureString(m_Title, font).ToSize();      ////m_TitleFont

            font = new Font(this._TemplateStyle.SubTitleSetting.FontTemplate.FontName, this._TemplateStyle.SubTitleSetting.FontTemplate.FontSize, this._TemplateStyle.SubTitleSetting.FontTemplate.FontStyle);
            SubTitleSize = g.MeasureString(m_Subtitle, font).ToSize();    //m_SubtitleFont

            ImageSize.Width = Math.Max(TitleSize.Width, SubTitleSize.Width) + 20;
            ImageSize.Height = TitleSize.Height + SubTitleSize.Height + 20;

            bmp = new System.Drawing.Bitmap(ImageSize.Width, ImageSize.Height);
            g = Graphics.FromImage(bmp);
            switch (p_FileExt.ToLower())
            {
                case "emf":
                    IntPtr hRefDC = g.GetHdc();
                    Metafile m = null;
                    try
                    {
                        m = new Metafile(p_Path + "\\" + p_FileName + ".emf", hRefDC, new Rectangle(0, 0, ImageSize.Width, ImageSize.Height), MetafileFrameUnit.Pixel, EmfType.EmfPlusOnly);

                    }
                    catch (Exception ex)
                    {

                        Console.Write(ex.Message);
                    }
                    g.ReleaseHdc(hRefDC);
                    Graphics gMeta = Graphics.FromImage(m);
                    DrawTitleText(gMeta, TitleSize.Height);

                    m.Dispose();
                    gMeta.Dispose();
                    break;
                case "png":
                    DrawTitleText(g, TitleSize.Height);
                    bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
                    break;
                case "jpg":
                    g.Clear(Color.White);
                    DrawTitleText(g, TitleSize.Height);
                    //bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
                    Map.SaveAsHightQualityJPEG(bmp, p_Path + "\\" + p_FileName + ".jpg");
                    break;
                case "bmp":
                    g.Clear(Color.White);
                    DrawTitleText(g, TitleSize.Height);
                    bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
                    break;
                case "gif":
                    g.Clear(Color.White);
                    DrawTitleText(g, TitleSize.Height);
                    bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
                    break;
                case "tiff":
                    DrawTitleText(g, TitleSize.Height);
                    bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
                    break;
                case "ico":
                    DrawTitleText(g, TitleSize.Height);
                    bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
                    break;
            }

            bmp.Dispose();
            bmp = null;
            g.Dispose();

            return ImageSize;
        }
 private string GetRtfImage(Image _image)
 {
     MemoryStream stream = null;
     Graphics graphics = null;
     Metafile image = null;
     string ret;
     try
     {
         stream = new MemoryStream();
         using (graphics = base.CreateGraphics())
         {
             IntPtr hdc = graphics.GetHdc();
             image = new Metafile(stream, hdc);
             graphics.ReleaseHdc(hdc);
         }
         using (graphics = Graphics.FromImage(image))
         {
             graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
         }
         IntPtr henhmetafile = image.GetHenhmetafile();
         uint num = GdipEmfToWmfBits(henhmetafile, 0, null, 1, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
         byte[] buffer = new byte[num];
         GdipEmfToWmfBits(henhmetafile, num, buffer, 1, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < buffer.Length; i++)
         {
             builder.Append(string.Format("{0:X2}", buffer[i]));
         }
         ret = builder.ToString();
     }
     finally
     {
         if (graphics != null)
         {
             graphics.Dispose();
         }
         if (image != null)
         {
             image.Dispose();
         }
         if (stream != null)
         {
             stream.Close();
         }
     }
     return ret;
 }
Beispiel #18
0
        private string convertCoordinatesToHex()
        {
            string signatureHex = string.Empty;

            if (SignatureCoordinate.Length > 0)
            {
                StringBuilder signatureHexVaule = new StringBuilder();
                MemoryStream memoryStream = new MemoryStream();
                System.Drawing.Image signatureTemplateImg = new System.Drawing.Bitmap(SignatureWidth, SignatureHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics SignatureGraphs = Graphics.FromImage(signatureTemplateImg);
                SignatureGraphs.FillRectangle(Brushes.White, 0, 0, signatureTemplateImg.Width, signatureTemplateImg.Height);

                Metafile signatureMetaFile = null;
                IntPtr hdc;
                try
                {
                    using (SignatureGraphs = Graphics.FromImage(signatureTemplateImg))
                    {
                        hdc = SignatureGraphs.GetHdc();
                        signatureMetaFile = new Metafile(memoryStream, hdc);
                        SignatureGraphs.ReleaseHdc(hdc);
                    }
                    using (SignatureGraphs = Graphics.FromImage(signatureMetaFile))
                    {
                        SignatureGraphs.DrawImage(signatureTemplateImg, new System.Drawing.Rectangle(0, 0, signatureTemplateImg.Width, signatureTemplateImg.Height));
                        SignatureGraphs.DrawRectangle(new Pen(Color.White, 1), 0, 0, SignatureWidth, SignatureHeight);

                        Pen pen = new Pen(Color.Black, 1);
                        string[] points = SignatureCoordinate.Split(':');
                        string[] point = null;

                        for (int i = 0; i < points.Length - 1; i++)
                        {
                            point = points[i].Split('~');
                            if (point.Length == 4)
                            {
                                SignatureGraphs.DrawRectangle(pen, float.Parse(point[0]), float.Parse(point[1]), float.Parse(point[2]), float.Parse(point[3]));
                            }
                        }
                    }

                    IntPtr hEmf = signatureMetaFile.GetHenhmetafile();

                    uint bufferSize = GdipEmfToWmfBits(hEmf, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
                    byte[] buffer = new byte[bufferSize];

                    GdipEmfToWmfBits(hEmf, bufferSize, buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                    for (int i = 0; i < buffer.Length; ++i)
                    {
                        signatureHexVaule.Append(String.Format("{0:X2}", buffer[i]));
                    }

                    signatureHex = signatureHexVaule.ToString();
                }
                finally
                {
                    if (SignatureGraphs != null)
                    {
                        SignatureGraphs.Dispose();
                    }

                    if (signatureMetaFile != null)
                    {
                        signatureMetaFile.Dispose();
                    }

                    if (memoryStream != null)
                    {
                        memoryStream.Close();
                    }
                }
            }

            return signatureHex;
        }
Beispiel #19
0
        public Size GetLegendImage(string p_Path, string p_FileName, string p_FileExt, bool ShowPointLegend, bool showCaption, bool showRange, bool showAreaCount, bool showMissingDataInLegend, LegendsSequenceOrder legendSequenceOrder)
        {
            Size RetVal = new Size(0, 0);

            int ImageWidth;
            int ImageHeight = 0;
            int LegendWidth;
            int LegendHeight;
            int Padding;
            SizeF LegendSize;
            SizeF LegendTitleSize;
            int i = 0;

            this.ShowLegendRange = showRange;
            this.ShowLegendCaption = showCaption;
            this.ShowAreaCount = showAreaCount;

            if (m_MultiLegend == true)
            {
                LegendWidth = 20;
            }
            else
            {
                LegendWidth = 10; //40 di Profiles
            }
            LegendHeight = 5;    //20  di Profiles

            Padding = 10;
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
            Graphics g = Graphics.FromImage(bmp);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            LegendTitleSize = g.MeasureString(m_LegendTitle, m_LegendFont);

            //*** Get maximum width of Legend Items
            ImageWidth = (int)LegendTitleSize.Width + Padding;

            switch (m_ThemeType)
            {
                case ThemeType.Color:
                case ThemeType.Hatch:
                case ThemeType.Symbol:
                    //-- calculate Legend Height (N Legend's Height)

                    LegendHeight = (int)g.MeasureString(m_Legends[0].Title, m_LegendBodyFont).Height;

                    if (legendSequenceOrder == LegendsSequenceOrder.SingleColumn)
                    {
                        //- Show all legends vertically in one column.
                        //- Get image height by summing all legend's height
                        ImageHeight = (m_Legends.Count - Convert.ToInt32(!(showMissingDataInLegend))) * LegendHeight + (m_MultiLegendCol.Count * LegendHeight / 2);

                        //- Add Legend title height
                        ImageHeight += (int)LegendTitleSize.Height + Padding;
                    }
                    else if (legendSequenceOrder == LegendsSequenceOrder.SingleRow)
                    {
                        //- Show all legends horizontally in single row.
                        //- Get image height = Single Legend Height + LegendTitle height
                        ImageHeight = LegendHeight + (int)LegendTitleSize.Height + Padding;

                    }

                    //*** one extra for legend title
                    int ColorBlockWidth;
                    if (m_MultiLegend == true)
                    {
                        ColorBlockWidth = Padding + (LegendWidth * m_MultiLegendCol.Count) + m_MultiLegendCol.Count + Padding;
                    }
                    else
                    {
                        ColorBlockWidth = Padding + LegendWidth + Padding;
                    }

                    //- Calculate Image width
                    foreach (Legend _Legend in m_Legends)
                    {
                        i += 1;

                        //-- Legend Title displayed should be: Legend.Caption + (Legend.Title) "
                        string LegendCaption = string.Empty;
                        if (this.ShowLegendCaption)
                        {
                            LegendCaption = _Legend.Caption + " ";
                        }
                        else if (showMissingDataInLegend && i == m_Legends.Count)
                        {
                            //- Show MissingData for Last Legend if Caption is blank
                            LegendCaption = _Legend.Caption + " ";
                        }

                        if (this.ShowLegendRange && (!(string.IsNullOrEmpty(_Legend.Title))))
                        {
                            LegendCaption += " " + _Legend.Title;
                        }
                        if (this.ShowAreaCount)
                        {
                            LegendCaption += " (" + Convert.ToString(_Legend.ShapeCount) + ")";
                        }

                        LegendSize = g.MeasureString(LegendCaption, m_LegendBodyFont);

                        if (legendSequenceOrder == LegendsSequenceOrder.SingleColumn)
                        {
                            //- if single column, then get maximum legend's width
                            ImageWidth = Math.Max(ImageWidth, ColorBlockWidth + (int)LegendSize.Width);
                        }
                        else if (legendSequenceOrder == LegendsSequenceOrder.SingleRow)
                        {

                            if (i < m_Legends.Count || (showMissingDataInLegend && i == m_Legends.Count))
                            {
                                //- if single row, then get sum of all legend's width
                                ImageWidth += LegendWidth + Padding + (int)LegendSize.Width + Padding;
                            }
                        }
                    }

                    // In case of word wrap when single row legend exceeds map width, increase legend heigt to accomodate wraped text
                    if (legendSequenceOrder == LegendsSequenceOrder.SingleRow && this.m_LegendMaxWidth < ImageWidth)
                    {
                        ImageWidth = Convert.ToInt32(this.m_LegendMaxWidth.ToString());
                        ImageHeight = ImageHeight + ImageHeight;    //
                    }

                    break;

                case ThemeType.Label:

                    int LegendHeightSum = 0;
                    //-- Get sum of all Legends hights
                    // as in label theme, each label is set with its individual font.
                    foreach (Legend _Legend in m_Legends)
                    {
                        LegendHeightSum += (int)g.MeasureString(_Legend.Title, _Legend.MarkerFont).Height;
                    }

                    LegendHeight = LegendHeightSum / m_Legends.Count;

                    ImageHeight = LegendHeightSum + (m_MultiLegendCol.Count * LegendHeight / 2);
                    ImageHeight += (int)LegendTitleSize.Height + Padding;

                    //*** one extra for legend title
                    if (m_MultiLegend == true)
                    {
                        ColorBlockWidth = Padding + (LegendWidth * m_MultiLegendCol.Count) + m_MultiLegendCol.Count + Padding;
                    }
                    else
                    {
                        ColorBlockWidth = Padding + LegendWidth + Padding;
                    }

                    foreach (Legend _Legend in m_Legends)
                    {
                        i += 1;

                        //-- Legend Title displayed should be: Legend.Caption + (Legend.Title) "
                        string LegendCaption = string.Empty;
                        if (this.ShowLegendCaption)
                        {
                            LegendCaption = _Legend.Caption + " ";
                        }
                        else if (showMissingDataInLegend && i == m_Legends.Count)
                        {
                            //- Show MissingData for Last Legend if Caption is blank
                            LegendCaption = _Legend.Caption + " ";
                        }

                        if (this.ShowLegendRange && (!(string.IsNullOrEmpty(_Legend.Title))))
                        {
                            LegendCaption += " " + _Legend.Title;
                        }
                        if (this.ShowAreaCount)
                        {
                            LegendCaption += " (" + Convert.ToString(_Legend.ShapeCount) + ")";
                        }

                        LegendSize = g.MeasureString(LegendCaption, _Legend.MarkerFont);
                        ImageWidth = Math.Max(ImageWidth, ColorBlockWidth + (int)LegendSize.Width);
                    }
                    break;
                case ThemeType.DotDensity:
                    LegendSize = g.MeasureString(m_DotValue + " " + m_UnitName, m_LegendBodyFont);
                    ImageWidth = Math.Max((int)LegendTitleSize.Width + Padding, 20 + (int)LegendSize.Width);
                    ImageHeight = Math.Min(2 * (int)LegendTitleSize.Height, (int)LegendTitleSize.Height + (int)LegendSize.Height);
                    break;
                case ThemeType.Chart:
                    //get height of any one legend item based on legend font
                    LegendHeight = Math.Max(LegendHeight, (int)g.MeasureString(SubgroupName[0].ToString(), m_LegendBodyFont).Height);

                    if (legendSequenceOrder == LegendsSequenceOrder.SingleColumn)
                    {
                        //- Show all legends vertically in one column.
                        //ImageHeight = (SubgroupName.Length + 1) * LegendHeight;

                        // Set Image height of based on number of legend Item
                        ImageHeight = (SubgroupName.Length) * LegendHeight;

                        //- Add Legend title height to image height
                        ImageHeight += (int)(g.MeasureString(IndicatorName[0].ToString(), m_LegendBodyFont).Height)+Padding;
                    }
                    else if (legendSequenceOrder == LegendsSequenceOrder.SingleRow)
                    {
                        //- Show all legends horizontally in single row.
                        ImageHeight = LegendHeight;
                    }

                    //ImageHeight += (int)LegendTitleSize.Height + Padding;
                    //*** one extra for legend title

                    foreach (string _Str in IndicatorName)
                    {
                        LegendSize = g.MeasureString(_Str, m_LegendBodyFont);
                        ImageWidth = Math.Max(ImageWidth, Padding + LegendWidth + Padding + (int)LegendSize.Width);
                    }

                    //- Calculate image width depending upon following cases
                    //- If all legends to be shown in single column.
                    // or all legends in single row.
                    if (legendSequenceOrder == LegendsSequenceOrder.SingleColumn)
                    {
                        //- if single column, then get maximum subgroup's width
                        foreach (string _Str in SubgroupName)
                        {
                            LegendSize = g.MeasureString(_Str, m_LegendBodyFont);

                            ImageWidth = Math.Max(ImageWidth, Padding + LegendWidth + Padding + (int)LegendSize.Width);
                        }
                    }
                    else if (legendSequenceOrder == LegendsSequenceOrder.SingleRow)
                    {
                        int SubgroupCaptionWidth = 0;
                        foreach (string _Str in SubgroupName)
                        {
                            LegendSize = g.MeasureString(_Str, m_LegendBodyFont);
                            SubgroupCaptionWidth += Padding + LegendWidth + Padding + (int)LegendSize.Width;
                        }

                        ImageWidth = Math.Max(ImageWidth, SubgroupCaptionWidth);
                    }

                    //-- Now consider Legend Title width
                    ImageWidth = Math.Max((int)LegendTitleSize.Width + Padding, ImageWidth);

                    break;
            }
            bmp = new System.Drawing.Bitmap(ImageWidth + 2, ImageHeight);
            g = Graphics.FromImage(bmp);
            switch (p_FileExt.ToLower())
            {
                case "emf":
                    IntPtr hRefDC = g.GetHdc();
                    //Metafile m = new Metafile(p_Path + "\\" + p_FileName + ".emf", hRefDC);
                    Metafile m = new Metafile(p_Path + "\\" + p_FileName + ".emf", hRefDC, new Rectangle(0, 0, ImageWidth + 2, ImageHeight), MetafileFrameUnit.Pixel, EmfType.EmfPlusOnly);
                    g.ReleaseHdc(hRefDC);
                    Graphics gMeta = Graphics.FromImage(m);
                    DrawLegend(ref gMeta, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    m.Dispose();
                    gMeta.Dispose();
                    break;
                case "png":
                    g.Clear(Color.White);
                    DrawLegend(ref g, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
                    break;
                case "jpg":
                    g.Clear(Color.White);
                    DrawLegend(ref g, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    //bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
                    Map.SaveAsHightQualityJPEG( bmp, p_Path + "\\" + p_FileName + ".jpg");
                    break;
                case "bmp":
                    g.Clear(Color.White);
                    DrawLegend(ref g, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
                    break;
                case "gif":
                    g.Clear(Color.White);
                    DrawLegend(ref g, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
                    break;
                case "tiff":
                    DrawLegend(ref g, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
                    break;
                case "ico":
                    DrawLegend(ref g, LegendWidth, LegendHeight, ShowPointLegend, showMissingDataInLegend, legendSequenceOrder);
                    bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
                    break;
            }

            RetVal.Height = ImageHeight;
            RetVal.Width = ImageWidth;
            bmp.Dispose();
            bmp = null;
            g.Dispose();
            return RetVal;
        }
Beispiel #20
0
        protected override void ExportImage(string filename, string format)
        {
            uint pages;
            Image exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);		// create export draw area
            Graphics drawDestination = Graphics.FromImage(exportImage);
            //MessageBox.Show(drawDestination.PageScale.ToString());
            Graphics grph;
            IntPtr ipHDC;																	//necessary for wmf and emf export
            Metafile mf;
            Trace.WriteLine(DateTime.Now.TimeOfDay + " height: " + worksheet.Height.ToString());
            Worksheet w = new Worksheet();
            w.WorksheetValues = worksheet.WorksheetValues;
            pages = GetPages();		// calculate imageBitmap page count
            if (pages > 0) {																	// something to do?
                if (Output.AutosizeExport == true) {
                    int x = 0;
                    for (int k = 0; k < generator.PageHeights.Length; k++)
                        x +=	(int)generator.PageHeights[k] - (int)generator.YProcessOffset - (int)Generator.BOTTOM_MARGIN_MSC - (int)generator.YItemOffset;
                    x += (int)generator.YProcessOffset + (int)Generator.BOTTOM_MARGIN_MSC + (int)generator.YItemOffset;
                    worksheet.SetWorksheetHeight(x);
                    if (Output.AutosizeOutputWidth) {
                        worksheet.SetWorksheetWidth((int)generator.AutoWidth);
                    }
                    exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);
                    Trace.WriteLine(DateTime.Now.TimeOfDay + " height: ");
                    drawDestination = Graphics.FromImage(exportImage);
                    switch (format.ToUpper()) {				// identify selected format
                        case "BMP":
                            drawDestination.Clear(Color.White);
                            DrawPage(drawDestination, 0);
                            exportImage.Save(filename + ".bmp");
                            break;
                        case "GIF":
                            drawDestination.Clear(Color.White);
                            DrawPage(drawDestination, 0);
                            exportImage.Save(filename + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                        case "JPG":
                            drawDestination.Clear(Color.White);
                            DrawPage(drawDestination, 0);
                            exportImage.Save(filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case "PNG":
                            drawDestination.Clear(Color.White);
                            DrawPage(drawDestination, 0);
                            exportImage.Save(filename + ".png", System.Drawing.Imaging.ImageFormat.Png);
                            break;
                        case "WMF":
                            drawDestination.Clear(Color.White);
                            exportImage.Save(filename + ".wmf", System.Drawing.Imaging.ImageFormat.Wmf);		// for save as wmf first empty wmf file shall be created
                            grph = this.CreateGraphics();
                            ipHDC = grph.GetHdc();
                            mf = new Metafile(filename + ".wmf", ipHDC); 										// open created empty wmf file
                            grph = Graphics.FromImage(mf);
                            grph.Clear(Color.White);
                            grph.FillRectangle(Brushes.White, 0, 0, exportImage.Width, exportImage.Height);
                            grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                            grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                            DrawPage(grph, 0);														// draw imageBitmap direct to wmf file
                            grph.Dispose();
                            mf.Dispose();
                            break;
                        case "EMF":
                            System.IO.FileStream st = new FileStream(filename + ".emf", FileMode.Create);
                            drawDestination.Clear(Color.White);
                            grph = this.CreateGraphics();
                            ipHDC = grph.GetHdc();
                            mf = new Metafile(st, ipHDC);
                            grph = Graphics.FromImage(mf);
                            grph.Clear(Color.White);
                            grph.FillRectangle(Brushes.White, 0, 0, exportImage.Width, exportImage.Height);
                            grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                            grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                            DrawPage(grph, 0);														// draw imageBitmap direct to emf file
                            grph.Dispose();
                            st.Dispose();
                            mf.Dispose();
                            break;

                    }
                } else {
                    if (filename.LastIndexOf('.') >= (filename.Length - 4)) {
                        filename = filename.Substring(0, filename.LastIndexOf('.'));
                    }
                    for (uint i = 1; i <= pages; i++) {
                        if (Output.AutosizeOutputHeight) {
                            worksheet.SetWorksheetHeight((int)generator.PageHeights[i - 1]); // correct height for export

                        }
                        if (Output.AutosizeOutputWidth) {
                            worksheet.SetWorksheetWidth((int)generator.AutoWidth);
                        }
                        exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);
                        Trace.WriteLine(DateTime.Now.TimeOfDay + " height: ");
                        drawDestination = Graphics.FromImage(exportImage);
                        switch (format.ToUpper()) {				// identify selected format
                            case "BMP":
                                drawDestination.Clear(Color.White);
                                DrawPage(drawDestination, i);
                                exportImage.Save(filename + "_" + i + ".bmp");
                                break;
                            case "GIF":
                                drawDestination.Clear(Color.White);
                                DrawPage(drawDestination, i);
                                exportImage.Save(filename + "_" + i + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                                break;
                            case "JPG":
                                drawDestination.Clear(Color.White);
                                DrawPage(drawDestination, i);
                                exportImage.Save(filename + "_" + i + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                                break;
                            case "PNG":
                                drawDestination.Clear(Color.White);
                                DrawPage(drawDestination, i);
                                exportImage.Save(filename + "_" + i + ".png", System.Drawing.Imaging.ImageFormat.Png);
                                break;
                            case "WMF":
                                drawDestination.Clear(Color.White);
                                exportImage.Save(filename + "_" + i + ".wmf", System.Drawing.Imaging.ImageFormat.Wmf);		// for save as wmf first empty wmf file shall be created
                                grph = this.CreateGraphics();
                                ipHDC = grph.GetHdc();
                                mf = new Metafile(filename + "_" + i + ".wmf", ipHDC); 										// open created empty wmf file
                                grph = Graphics.FromImage(mf);
                                grph.Clear(Color.White);
                                grph.FillRectangle(Brushes.White, 0, 0, exportImage.Width, exportImage.Height);
                                grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                                grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                                DrawPage(grph, i);														// draw imageBitmap direct to wmf file
                                grph.Dispose();
                                mf.Dispose();
                                break;
                            case "EMF":
                                System.IO.FileStream st = new FileStream(filename + "_" + i + ".emf", FileMode.Create);
                                drawDestination.Clear(Color.White);
                                grph = this.CreateGraphics();
                                ipHDC = grph.GetHdc();
                                mf = new Metafile(st, ipHDC);
                                grph = Graphics.FromImage(mf);
                                grph.Clear(Color.White);
                                grph.FillRectangle(Brushes.White, 0, 0, exportImage.Width, exportImage.Height);
                                grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;					// set image quality
                                grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                                DrawPage(grph, i);														// draw imageBitmap direct to emf file
                                grph.Dispose();
                                st.Dispose();
                                mf.Dispose();
                                break;
                        }
                    }
                }
            }
            worksheet.WorksheetValues = w.WorksheetValues;
            tmpWorksheet.Width = worksheet.GetWorksheetWidth();
            tmpWorksheet.Height = worksheet.GetWorksheetHeight();
            tmpWorksheet.SetMargins(0, 0, 0, 0);
            generator.CalcOffsets(drawDestination, tmpWorksheet);
            drawDestination.Dispose();
            exportImage.Dispose();
            GC.Collect();
        }
Beispiel #21
0
		/// <summary>
		/// Wraps the image in an Enhanced Metafile by drawing the image onto the
		/// graphics context, then converts the Enhanced Metafile to a Windows
		/// Metafile, and finally appends the bits of the Windows Metafile in HEX
		/// to a string and returns the string.
		/// </summary>
		/// <param name="image"></param>
		/// <returns>
		/// A string containing the bits of a Windows Metafile in HEX
		/// </returns>
		public static string GetRtfImage(Image image)
		{
			StringBuilder rtf = null;

			// Used to store the enhanced metafile
			MemoryStream stream = null;

			// The enhanced metafile
			Metafile metaFile = null;

			// Handle to the device context used to create the metafile
			IntPtr hdc;

			try
			{
				rtf = new StringBuilder();
				stream = new MemoryStream();

				using (Graphics gr = Graphics.FromImage(image))
				{
					// Get the device context from the graphics context
					hdc = gr.GetHdc();
					// Create a new Enhanced Metafile from the device context
					metaFile = new Metafile(stream, hdc);
					// Release the device context
					gr.ReleaseHdc(hdc);
				}

				// Get a graphics context from the Enhanced Metafile
				using (Graphics gr = Graphics.FromImage(metaFile))
				{
					// Draw the image on the Enhanced Metafile
					gr.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
				}

				// Get the handle of the Enhanced Metafile
				IntPtr hEmf = metaFile.GetHenhmetafile();

				// A call to EmfToWmfBits with a null buffer return the size of the
				// buffer need to store the WMF bits.  Use this to get the buffer
				// size.
				uint bufferSize = GdipEmfToWmfBits(hEmf, 0, null, MM_ANISOTROPIC,
					EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

				// Create an array to hold the bits
				byte[] buffer = new byte[bufferSize];

				// A call to EmfToWmfBits with a valid buffer copies the bits into the
				// buffer an returns the number of bits in the WMF.
				uint convertedSize = GdipEmfToWmfBits(hEmf, bufferSize, buffer, MM_ANISOTROPIC,
					EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

				// Append the bits to the RTF string
				for (int i = 0; i < buffer.Length; ++i)
				{
					rtf.Append(String.Format("{0:X2}", buffer[i]));
				}

				return rtf.ToString();
			}
			finally
			{
				if (metaFile != null)
					metaFile.Dispose();
				if (stream != null)
					stream.Close();
			}
		}
        public void SaveVector(string fileName)
        {
            if (!fileName.EndsWith(".emf"))
            {
                MessageBox.Show("Invalid file extension provided.", "Save Image", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            Graphics g = CreateGraphics();
            IntPtr hdc = g.GetHdc();
            Metafile mf = new Metafile(fileName, hdc, new Rectangle(0, 0, Width, Height), MetafileFrameUnit.Pixel, EmfType.EmfOnly);
            g.ReleaseHdc(hdc);

            Graphics mfg = Graphics.FromImage(mf);
            DrawTimetable(mfg);
            mfg.Dispose();
            mf.Dispose();
        }
		/// <summary>
		///		Convierte la imagen en un Enhanced Metafile desde un Windows Metafile y devuelve los bits
		///		del Windows Metafile en hexadecimal
		/// </summary>
		private string GetRtfImage(Image _image) 
		{	StringBuilder sbRtf = null;
			MemoryStream stmStream = null; // Almacena el enhanced metafile
			Graphics grpGraphics = null; // Utilizado para crear el metafile y dibujar la imagen
			Metafile mfMetafile = null; // El enhanced metafile
			IntPtr hndDC; // Manejador al contexto del dispositivo utilizado para crear el metafile

				try 
					{	// Inicializa las variables
							sbRtf = new StringBuilder();
							stmStream = new MemoryStream();
						// Obtiene el contexto gráfico del RichTextBox
							using (grpGraphics = CreateGraphics()) 
								{	// Obtiene el contexto de dispositivo a partir del contexto gráfico
										hndDC = grpGraphics.GetHdc();
									// Crea un nuevo Enhanced Metafile desde el contexto de dispositivo
										mfMetafile = new Metafile(stmStream, hndDC);
									// Libera el contexto del dispositivo
										grpGraphics.ReleaseHdc(hndDC);
								}
						// Obtiene el contexto gráfico del Enhanced Metafile
							using (grpGraphics = Graphics.FromImage(mfMetafile)) 
								{	// Dibuja la imagen sobre el Enhanced Metafile
										grpGraphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
								}
						// Obtiene el manejador del Enhanced Metafile
							IntPtr _hEmf = mfMetafile.GetHenhmetafile();
						// Llama a EmfToWmfBits con un buffer nulo para obtener el tamaño necesario para almacenar
						// los bits del WMF
							uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC,	
																									EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
						// Crea un array para mantener los bits
							byte[] _buffer = new byte[_bufferSize];
						// Llama a EmfToWmfBits con un buffer correcto para copiar los en el buffer 
						// y devolver el número de bits del WMF
							uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC, 
																										EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
						// Añade los bits a la cadena RTF en hexadecimal
							for (int i = 0; i < _buffer.Length; i++) 
								sbRtf.Append(String.Format("{0:X2}", _buffer[i]));
						// Devuelve la cadena con la imagen
							return sbRtf.ToString();
					}
				finally 
					{	if(mfMetafile != null)
							mfMetafile.Dispose();
						if(stmStream != null)
							stmStream.Close();
					}
		}
Beispiel #24
0
        public Size GetDisclaimerImage(string p_Path, string p_FileName, string p_FileExt, int imageMaxWidthInPixel)
        {
            Size DisclaimerSize;
            string DisclaimerText = this.m_Disclaimer;
            Size ImageSize = new Size(0, 0);
            SolidBrush brDisclaimer = new SolidBrush(Color.Black);
            Font DisclaimerFont = new Font(this._TemplateStyle.DisclaimerFont.FontTemplate.FontName, this._TemplateStyle.DisclaimerFont.FontTemplate.FontSize, this._TemplateStyle.DisclaimerFont.FontTemplate.FontStyle);

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
            Graphics g = Graphics.FromImage(bmp);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            //*** Get maximum width of DisclaimerText
            DisclaimerSize = g.MeasureString(DisclaimerText, DisclaimerFont).ToSize();

            if (imageMaxWidthInPixel > 5)
            {
                if (DisclaimerSize.Width > imageMaxWidthInPixel)
                {
                    //- Wrap Disclaimer text in multiline
                    // so that total width of disclaimer image limits to Maximum Image width specified.
                    string[] DisclaimerTextBlocks = DisclaimerText.Split(' ');
                    int TotalSize = 0;
                    for (int k = 0; k < DisclaimerTextBlocks.Length; k++)
                    {
                        string DisclaimerBlock = DisclaimerTextBlocks[k];

                        TotalSize += g.MeasureString(DisclaimerBlock, DisclaimerFont).ToSize().Width;

                        //- If total disclaimer size exceeds limit,
                        // then add line break to get wrapping.
                        if (TotalSize >= imageMaxWidthInPixel && k > 0)
                        {
                            DisclaimerTextBlocks[k - 1] = DisclaimerTextBlocks[k - 1] + Environment.NewLine + DisclaimerTextBlocks[k];
                            DisclaimerTextBlocks[k] = string.Empty;
                            TotalSize = 0;
                        }
                    }

                    //- get wapped disclaimer Text from new array
                    DisclaimerText = string.Join(" ", DisclaimerTextBlocks);

                    //- Get again maximum width of DisclaimerText image
                    DisclaimerSize = g.MeasureString(DisclaimerText, DisclaimerFont).ToSize();
                }
            }

            ImageSize.Width = DisclaimerSize.Width + 20;
            ImageSize.Height = DisclaimerSize.Height + 20;

            bmp = new System.Drawing.Bitmap(ImageSize.Width, ImageSize.Height);
            g = Graphics.FromImage(bmp);
            switch (p_FileExt.ToLower())
            {
                case "emf":
                    IntPtr hRefDC = g.GetHdc();
                    Metafile m = new Metafile(p_Path + "\\" + p_FileName + ".emf", hRefDC, EmfType.EmfPlusOnly);
                    g.ReleaseHdc(hRefDC);
                    Graphics gMeta = Graphics.FromImage(m);
                    gMeta.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    m.Dispose();
                    gMeta.Dispose();
                    break;
                case "png":
                    g.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
                    break;
                case "jpg":
                    g.Clear(Color.White);
                    g.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    //bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
                    Map.SaveAsHightQualityJPEG(bmp, p_Path + "\\" + p_FileName + ".jpg");
                    break;
                case "bmp":
                    g.Clear(Color.White);
                    g.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
                    break;
                case "gif":
                    g.Clear(Color.White);
                    g.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
                    break;
                case "tiff":
                    g.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
                    break;
                case "ico":
                    g.DrawString(DisclaimerText, DisclaimerFont, brDisclaimer, 10, 10);
                    bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
                    break;
            }

            bmp.Dispose();
            bmp = null;
            g.Dispose();

            brDisclaimer.Dispose();
            return ImageSize;
        }
Beispiel #25
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="container"></param>
        /// <param name="ic"></param>
        /// <returns></returns>
        public MemoryStream MakeMetafileStream(
            Bitmap bitmap,
            Container container,
            IImageCache ic)
        {
            var g = default(Graphics);
            var mf = default(Metafile);
            var ms = new MemoryStream();

            try
            {
                using (g = Graphics.FromImage(bitmap))
                {
                    var hdc = g.GetHdc();
                    mf = new Metafile(ms, hdc);
                    g.ReleaseHdc(hdc);
                }

                using (g = Graphics.FromImage(mf))
                {
                    var r = new EmfRenderer(72.0 / 96.0);
                    r.State.ImageCache = ic;

                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.PageUnit = GraphicsUnit.Display;

                    if (container.Template != null)
                    {
                        r.Draw(g, container.Template, container.Properties, null);
                    }

                    r.Draw(g, container, container.Properties, null);
                    r.ClearCache(isZooming: false);
                }
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }

                if (mf != null)
                {
                    mf.Dispose();
                }
            }
            return ms;
        }
Beispiel #26
0
        public void GetInsetImage(string p_Path, string p_FileExt, int p_Width, int p_Height, int p_Index, string p_FileName)
        {
            int i;
            string ImgFileName = string.Empty;
            //*** Preserve Original Settings
            int SelIndex = Insets.SelIndex;
            int StartIndex = 0;
            int EndIndex = Insets.Count - 1;
            Color CurCanvasColor = this.CanvasColor;
            float CurWidth = m_Width;
            float CurHeight = m_Height;
            RectangleF CurExtent = m_CurrentExtent;
            bool bNorthSymbol = m_NorthSymbol;
            m_NorthSymbol = false;
            //Supress north symbol on Inset Images

            MemoryStream ms = null;

            m_Width = p_Width;
            m_Height = p_Height;
            this.CanvasColor = Color.White;
            if (p_Index > -1)
            {
                StartIndex = p_Index;
                EndIndex = p_Index;
            }
            for (i = StartIndex; i <= EndIndex; i++)
            {
                Insets.SelIndex = i;
                SetFullExtent();
                if (p_FileName == "")
                {
                    p_FileName = "Inset" + i;
                }
                else
                {
                    p_FileName += i;
                }

                ImgFileName = p_Path + "\\" + p_FileName + "." + p_FileExt;

                if (File.Exists(ImgFileName))
                {
                    try
                    {
                        File.Delete(ImgFileName);
                    }
                    catch
                    {
                    }
                }

                Bitmap bmp = new Bitmap(p_Width, p_Height);
                Graphics g = Graphics.FromImage(bmp);
                ms = new MemoryStream(1000);
                switch (p_FileExt.ToLower())
                {
                    case "emf":
                        IntPtr hRefDC = g.GetHdc();
                        Metafile m = new Metafile(p_Path + "\\" + p_FileName + "." + p_FileExt, hRefDC, new Rectangle(0, 0, p_Width, p_Height), MetafileFrameUnit.Pixel, EmfType.EmfPlusOnly);
                        g.ReleaseHdc(hRefDC);
                        Graphics gMeta = Graphics.FromImage(m);
                        DrawMap("", gMeta);
                        m.Dispose();
                        gMeta.Dispose();

                        DrawMap("", g);
                        bmp.Save(ms, ImageFormat.Png);
                        break;
                    case "png":
                        DrawMap("", g);
                        bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
                        bmp.Save(ms, ImageFormat.Png);
                        break;
                    case "jpg":
                        DrawMap("", g);
                        bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
                        bmp.Save(ms, ImageFormat.Jpeg);
                        break;
                    case "bmp":
                        DrawMap("", g);
                        bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
                        bmp.Save(ms, ImageFormat.Bmp);
                        break;
                    case "gif":
                        DrawMap("", g);
                        bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
                        bmp.Save(ms, ImageFormat.Gif);
                        break;
                    case "tiff":
                        DrawMap("", g);
                        bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
                        bmp.Save(ms, ImageFormat.Tiff);
                        break;
                    case "ico":
                        DrawMap("", g);
                        bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
                        bmp.Save(ms, ImageFormat.Icon);
                        break;
                }
                bmp.Dispose();
                bmp = null;
                g.Dispose();

                //-- Get inset Image in Inset.InsetImage property.
                if (File.Exists(ImgFileName))
                {
                    try
                    {
                        this.m_Insets[i].InsetImage = Image.FromStream(ms);
                        //ms.Close();
                    }
                    catch (Exception ex)
                    {

                    }

                }
                ms.Close();
            }

            m_CurrentExtent = CurExtent;
            Insets.SelIndex = SelIndex;
            m_Width = CurWidth;
            m_Height = CurHeight;
            m_NorthSymbol = bNorthSymbol;
            this.CanvasColor = CurCanvasColor;
        }
Beispiel #27
0
        public bool Export(Stream stream, string extension, Graphics referenceGraphics,
            DiagramAlertHandler alerteDelegate, IDictionary<string, object> specificRendererParameters)
        {
            bool result = false;

            if (extension.Equals(".emf", StringComparison.OrdinalIgnoreCase))
            {
                float scaleSave = _diagram.Scale;
                try
                {
                    _diagram.Scale = 1.0f;
                    _diagram.Layout(referenceGraphics);

                    IntPtr hdc = referenceGraphics.GetHdc();
                    Metafile metafile      = new Metafile(stream, hdc);
                    Graphics graphics      = Graphics.FromImage(metafile);
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    _diagram.Layout(graphics);
                    DiagramGdiRenderer.Draw(_diagram, graphics);
                    referenceGraphics.ReleaseHdc(hdc);
                    metafile.Dispose();
                    graphics.Dispose();

                    result = true;
                }
                finally
                {
                    _diagram.Scale = scaleSave;
                    _diagram.Layout(referenceGraphics);
                }
            }
            else if (extension.Equals(".png", StringComparison.OrdinalIgnoreCase) ||
                extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase)      ||
                extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
            {
                Rectangle bbox = _diagram.ScaleRectangle(_diagram.BoundingBox);
                bool bypassAlert = true;
                if (alerteDelegate != null && (bbox.Width > 10000 || bbox.Height > 10000))
                    bypassAlert = alerteDelegate("Huge image generation",
                        String.Format("Do you agree to generate a {0}x{1} image?", bbox.Width, bbox.Height));
                if (bypassAlert)
                {
                    Bitmap bitmap = new Bitmap(bbox.Width, bbox.Height);
                    Graphics graphics = Graphics.FromImage(bitmap);
                    graphics.FillRectangle(Brushes.White, 0, 0, bbox.Width, bbox.Height);
                    DiagramGdiRenderer.Draw(_diagram, graphics);
                    if (extension.CompareTo(".png") == 0)
                        bitmap.Save(stream, ImageFormat.Png);
                    else
                        bitmap.Save(stream, ImageFormat.Jpeg);

                    result = true;
                }
            }
            else if (extension.CompareTo(".txt") == 0 || extension.CompareTo(".csv") == 0)
            {
                float scaleSave = _diagram.Scale;
                try
                {
                    _diagram.Scale = 1.0f;
                    _diagram.Layout(referenceGraphics);
                    using (StreamWriter sw = new StreamWriter(stream))
                    {
                        using (DiagramTxtRenderer renderer = new DiagramTxtRenderer(sw))
                        {
                            renderer.IsCSV = extension.CompareTo(".csv") == 0;
                            IDictionary<string, object> parameters = specificRendererParameters as IDictionary<string, object>;
                            object o;
                            if (parameters != null && parameters.TryGetValue("TextOutputFields", out o))
                                renderer.TextOutputFields = o as IList<string>;
                            renderer.Render(_diagram);
                        }

                        sw.Close();
                    }
                    result = true;
                }
                finally
                {
                    _diagram.Scale = scaleSave;
                    _diagram.Layout(referenceGraphics);
                }
            }
            else //if (extension.CompareTo(".svg") == 0)
            {
                float scaleSave = _diagram.Scale;
                try
                {
                    _diagram.Scale = 1.0f;
                    _diagram.Layout(referenceGraphics);
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        using (DiagramSvgRenderer renderer = new DiagramSvgRenderer(streamWriter, referenceGraphics))
                        {
                            renderer.Render(_diagram);
                        }

                        streamWriter.Close();
                    }
                    result = true;
                }
                finally
                {
                    _diagram.Scale = scaleSave;
                    _diagram.Layout(referenceGraphics);
                }
            }
            return result;
        }
Beispiel #28
0
        public void GetMapImage(string p_Path, string p_FileName, string p_FileExt, bool DefaultView)
        {
            //*** Preserve Original Settings In case some inset is being shown currently
            int SelIndex = Insets.SelIndex;
            RectangleF CurExtent = m_CurrentExtent;

            if (SelIndex > -1 & DefaultView == true)
            {
                Insets.SelIndex = -1;
                SetFullExtent();
            }

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap((int)m_Width, (int)m_Height);

            Graphics g = Graphics.FromImage(bmp);

            switch (p_FileExt.ToLower())
            {
                case "emf":
                    IntPtr hRefDC = g.GetHdc();
                    //Dim m As Imaging.Metafile = New Imaging.Metafile(p_Path & "\" & p_FileName & "." & p_FileExt, hRefDC, New Rectangle(0, 0, m_Width, m_Height), MetafileFrameUnit.Pixel)
                    Metafile m = new Metafile(p_Path + "\\" + p_FileName + "." + p_FileExt, hRefDC, new Rectangle(0, 0, (int)m_Width, (int)m_Height), MetafileFrameUnit.Pixel, EmfType.EmfPlusDual); //MetafileFrameUnit.Point
                    g.ReleaseHdc(hRefDC);
                    Graphics gMeta = Graphics.FromImage(m);
                    DrawMap("", gMeta);
                    m.Dispose();
                    gMeta.Dispose();
                    break;
                case "png":
                    DrawMap("", g);
                    bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
                    break;
                case "jpg":
                    Color TempColor = this.CanvasColor;    //Storing Canvas Color in Tempory variable
                    this.CanvasColor = Color.White;         //Specifying White Canvas Color as Background color of JPEG image
                    DrawMap("", g);
                    this.CanvasColor = TempColor;           //Storing back original Canvas Color.

                    //bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
                    Map.SaveAsHightQualityJPEG(bmp, p_Path + "\\" + p_FileName + ".jpg");
                    break;
                case "bmp":
                    DrawMap("", g);
                    bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
                    break;
                case "gif":
                    DrawMap("", g);
                    bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
                    break;
                case "tiff":
                    DrawMap("", g);
                    bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
                    break;
                case "ico":
                    DrawMap("", g);
                    bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
                    break;
            }
            bmp.Dispose();
            bmp = null;
            g.Dispose();

            if (SelIndex > -1 & DefaultView == true)
            {
                Insets.SelIndex = SelIndex;
                m_CurrentExtent = CurExtent;
            }
        }
Beispiel #29
0
    /// <summary>
    /// Creates a meta file from the current page.
    /// </summary>
    private void miMetaFile_Click(object sender, EventArgs e)
    {
      int page = this.pagePreview.Page;

      // Reuse the renderer from the preview
      DocumentRenderer renderer = this.pagePreview.Renderer;
      PageInfo info = renderer.FormattedDocument.GetPageInfo(page);

      // Create an image
      float dx, dy;
      if (info.Orientation == PdfSharp.PageOrientation.Portrait)
      {
        dx = (float)(info.Width.Inch * 72);
        dy = (float)(info.Height.Inch * 72);
      }
      else
      {
        dx = (float)(info.Height.Inch * 72);
        dy = (float)(info.Width.Inch * 72);
      }

      // Create a graphics object as reference
      Graphics graphicsDisplay = CreateGraphics();
      IntPtr hdc = graphicsDisplay.GetHdc();

      // There is a little difference between the display resolution (i.g. 96 DPI) and the real physical solution of the display.
      // This must be taken into account...
      DeviceInfos devInfo = DeviceInfos.GetInfos(hdc);

      // Create the metafile
      Metafile metafile = new Metafile("test.emf", hdc, 
        new RectangleF(0, 0, devInfo.ScaleX * dx, devInfo.ScaleY * dy), MetafileFrameUnit.Point);
      graphicsDisplay.ReleaseHdc(hdc);
      graphicsDisplay.Dispose();

      // Create a Graphics object for the metafile and scale it for drawing with 72 dpi
      Graphics graphics = Graphics.FromImage(metafile);
      graphics.Clear(System.Drawing.Color.White);
      //graphics.PageUnit = GraphicsUnit.Point; ???
      graphics.ScaleTransform(graphics.DpiX / 72, graphics.DpiY / 72);

      // Check if size is correct
      graphics.DrawLine(Pens.Red, 0, 0, dx, dy);

      // Create an XGraphics object and render the page
      XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point));
      renderer.RenderPage(gfx, page);
      gfx.Dispose();

      metafile.Dispose();

      Process.Start("test.emf");
    }
Beispiel #30
0
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (IsRunning == false && IsCompleted == false && e.KeyCode == Keys.Enter)
            {
                IsRunning = true;
                this.BackColor = Color.Black;

                MSG_SB.Length = 0;
                MSG_SB.AppendLine("RUNNING");
                Invalidate();
                Update();
                bDrawCHT = true;
                MSG_SB.Length = 0;

                Run(bDrawCHT);

                IsRunning = false;
                TS_END = new TimeSpan(DateTime.Now.Ticks);
                TS_END = TS_END.Subtract(TS_START).Duration();
                COMMOD COMMOD9 = COMMOD.Singleton();

                MSG_SB.Length = 0;
                MSG_SB.AppendFormat("BSTPEN = {0}     ELAPSED {1}h:{2}m:{3}s", (int)COMMOD9.BSTPEN, TS_END.Hours, TS_END.Minutes, TS_END.Seconds);
                MSG_SB.AppendLine("\r\nPRESS <Enter> TO VIEW CHARTS OR  PRESS <ESC> TO EXIT.");

                IsCompleted = true;

                M_DRAWINCR = new DRAWINCR();
            }
            else if (IsRunning == false && IsCompleted == false && e.KeyCode == Keys.Space)
            {
                IsRunning = true;
                this.BackColor = Color.Black;

                MSG_SB.Length = 0;
                MSG_SB.AppendLine("RUNNING");
                Invalidate();
                Update();
                MSG_SB.Length = 0;
                bDrawCHT = false;
                Run(bDrawCHT);

                IsRunning = false;

                TS_END = new TimeSpan(DateTime.Now.Ticks);
                TS_END = TS_END.Subtract(TS_START).Duration();
                COMMOD COMMOD9 = COMMOD.Singleton();
                MSG_SB.Length = 0;
                MSG_SB.AppendFormat("BSTPEN = {0}     ELAPSED {1}h:{2}m:{3}s", (int)COMMOD9.BSTPEN, TS_END.Hours, TS_END.Minutes, TS_END.Seconds);
                MSG_SB.AppendLine("\r\nPRESS <Enter> TO VIEW CHARTS OR  PRESS <ESC> TO EXIT.");

                this.BackColor = Color.White;

                Invalidate();
                Update();

                IsCompleted = true;

                M_DRAWINCR = new DRAWINCR();
            }
            else if (IsRunning == false && IsCompleted == false && e.KeyCode == Keys.Escape)
            {
                this.Close();
                this.Dispose();
            }
            else if (IsCompleted == true && Step < 2 && e.KeyCode == Keys.Enter)
            {
                if (Step == -1)
                {
                    if (bDrawCHT)
                    {
                        this.BackColor = Color.White;
                        Invalidate();
                        Update();
                        Step = 0;
                        bDrawCHT = false;
                    }
                    else
                    {
                        Step = 0;
                        this.BackColor = Color.White;
                        Invalidate();
                        Update();
                    }

                }
                else
                {
                    Invalidate();
                    Update();
                }
            }
            else if (Step == 2)
            {
                if (e.KeyCode == Keys.Escape)
                {

                    M_DRAWINCR.BeforeDO3();
                    Step = 3;
                    JDelta = 0;
                    EvtDelta = 0;
                    Invalidate();
                    Update();
                }
                else
                {

                    if (e.KeyValue == 37)
                    {
                        int temp = EvtDelta;

                        EvtDelta--;
                        EvtDelta = Math.Max(0, EvtDelta);

                        if (temp != EvtDelta)
                        {
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 39)
                    {
                        int temp = EvtDelta;

                        EvtDelta++;
                        EvtDelta = Math.Min(COMMOD.Singleton().NEVNT - 1, EvtDelta);

                        if (temp != EvtDelta)
                        {
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 38)
                    {
                        int temp = JDelta;

                        JDelta++;
                        JDelta = Math.Min(9, JDelta);

                        if (temp != JDelta)
                        {
                            EvtDelta = 0;
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 40)
                    {
                        int temp = JDelta;

                        JDelta--;
                        JDelta = Math.Max(0, JDelta);

                        if (temp != JDelta)
                        {
                            EvtDelta = 0;
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyCode == Keys.S)
                    {
                        try
                        {
                            Bitmap bmp = new Bitmap(COMMOD.Singleton().maxx, COMMOD.Singleton().maxy);
                            Graphics gs = Graphics.FromImage(bmp);
                            Metafile mf = new Metafile("export.emf", gs.GetHdc());

                            Graphics g = Graphics.FromImage(mf);

                            M_DRAWINCR.DO2(this, g, ref JDelta, ref EvtDelta);

                            g.Save();
                            g.Dispose();
                            mf.Dispose();

                            MessageBox.Show("Diagram has been exported!");

                        }
                        catch
                        {
                        }
                    }

                }

            }
            else if (Step == 3)
            {
                if (e.KeyCode == Keys.Escape)
                {
                    Step = 4;
                    JDelta = 0;
                    LDelta = 0;
                    Invalidate();
                    Update();
                }
                else
                {
                    if (e.KeyValue == 37)
                    {
                        int temp = LDelta;

                        LDelta--;
                        LDelta = Math.Max(0, LDelta);

                        if (temp != LDelta)
                        {
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 39)
                    {
                        int temp = LDelta;

                        LDelta++;
                        LDelta = Math.Min(4, LDelta);

                        if (temp != LDelta)
                        {
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 38)
                    {
                        int temp = JDelta;

                        JDelta++;
                        JDelta = Math.Min(9, JDelta);

                        if (temp != JDelta)
                        {
                            EvtDelta = 0;
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 40)
                    {
                        int temp = JDelta;

                        JDelta--;
                        JDelta = Math.Max(0, JDelta);

                        if (temp != JDelta)
                        {
                            EvtDelta = 0;
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyCode == Keys.S)
                    {
                        try
                        {
                            Bitmap bmp = new Bitmap(COMMOD.Singleton().maxx, COMMOD.Singleton().maxy);
                            Graphics gs = Graphics.FromImage(bmp);
                            Metafile mf = new Metafile("export.emf", gs.GetHdc());

                            Graphics g = Graphics.FromImage(mf);

                            M_DRAWINCR.DO3(this, g, ref JDelta, ref LDelta);

                            g.Save();
                            g.Dispose();
                            mf.Dispose();

                            MessageBox.Show("Diagram has been exported!");

                        }
                        catch
                        {
                        }
                    }
                }
            }
            else if (Step == 4)
            {
                if (e.KeyCode == Keys.Escape)
                {
                    Step = 5;
                    EvtDelta = 0;
                    JDelta = 0;
                    Invalidate();
                    Update();
                }
                else
                {
                    if (e.KeyValue == 37)
                    {
                        int temp = LDelta;

                        LDelta--;
                        LDelta = Math.Max(0, LDelta);

                        if (temp != LDelta)
                        {
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyValue == 39)
                    {
                        int temp = LDelta;

                        LDelta++;
                        LDelta = Math.Min(1, LDelta);

                        if (temp != LDelta)
                        {
                            Invalidate();
                            Update();
                        }
                    }
                    else if (e.KeyCode == Keys.S)
                    {
                        try
                        {
                            Bitmap bmp = new Bitmap(COMMOD.Singleton().maxx, COMMOD.Singleton().maxy);
                            Graphics gs = Graphics.FromImage(bmp);
                            Metafile mf = new Metafile("export.emf", gs.GetHdc());

                            Graphics g = Graphics.FromImage(mf);

                            M_DRAWINCR.DO4(this, g, ref LDelta);

                            g.Save();
                            g.Dispose();
                            mf.Dispose();

                            MessageBox.Show("Diagram has been exported!");

                        }
                        catch
                        {
                        }
                    }
                }
            }
            else if (Step == 5)
            {
                if (e.KeyCode == Keys.Escape)
                {
                    this.Close();
                    this.Dispose();
                }
                else if (e.KeyValue == 37)
                {
                    int temp = EvtDelta;

                    EvtDelta--;
                    EvtDelta = Math.Max(0, EvtDelta);

                    if (temp != EvtDelta)
                    {
                        Invalidate();
                        Update();
                    }
                }
                else if (e.KeyValue == 39)
                {
                    int temp = EvtDelta;

                    EvtDelta++;
                    EvtDelta = Math.Min(COMMOD.Singleton().NEVNT - 1, EvtDelta);

                    if (temp != EvtDelta)
                    {
                        Invalidate();
                        Update();
                    }
                }
                else if (e.KeyValue == 38)
                {
                    int temp = JDelta;

                    JDelta++;
                    JDelta = Math.Min(9, JDelta);

                    if (temp != JDelta)
                    {
                        EvtDelta = 0;
                        Invalidate();
                        Update();
                    }
                }
                else if (e.KeyValue == 40)
                {
                    int temp = JDelta;

                    JDelta--;
                    JDelta = Math.Max(0, JDelta);

                    if (temp != JDelta)
                    {
                        EvtDelta = 0;
                        Invalidate();
                        Update();
                    }
                }
                else if (e.KeyCode == Keys.S)
                {
                    try
                    {
                        Bitmap bmp = new Bitmap(COMMOD.Singleton().maxx, COMMOD.Singleton().maxy);
                        Graphics gs = Graphics.FromImage(bmp);
                        Metafile mf = new Metafile("export.emf", gs.GetHdc());

                        Graphics g = Graphics.FromImage(mf);

                        M_DRAWINCR.DO5(this, g, ref JDelta, ref EvtDelta);

                        g.Save();
                        g.Dispose();
                        mf.Dispose();

                        MessageBox.Show("Diagram has been exported!");

                    }
                    catch
                    {
                    }
                }
            }
            else if (IsCompleted == true && e.KeyCode == Keys.Escape)
            {
                this.Close();
                this.Dispose();
            }

            base.OnKeyDown(e);
        }