public void ExportImage(string filename) { switch (Path.GetExtension(filename).ToLower()) { case ".png": Bitmap bmp = new Bitmap(ClientRectangle.Width, ClientRectangle.Height); using (Graphics g = Graphics.FromImage(bmp)) { _chart.Draw(g); bmp.Save(filename); } break; case ".emf": using (Graphics g = this.CreateGraphics()) { IntPtr hdc = g.GetHdc(); Metafile mf = new Metafile(filename, hdc); using (Graphics mg = Graphics.FromImage(mf)) { using (mf) { _chart.Draw(mg); } } g.ReleaseHdc(hdc); } break; } }
protected override void OnPrintPage(PrintPageEventArgs e) { base.OnPrintPage(e); Stream pageToPrint = m_pages[m_currentPage]; pageToPrint.Position = 0; // Load each page into a Metafile to draw it. using (Metafile pageMetaFile = new Metafile(pageToPrint)) { Rectangle adjustedRect = new Rectangle( e.PageBounds.Left - (int)e.PageSettings.HardMarginX, e.PageBounds.Top - (int)e.PageSettings.HardMarginY, e.PageBounds.Width, e.PageBounds.Height); // Draw a white background for the report e.Graphics.FillRectangle(Brushes.White, adjustedRect); // Draw the report content e.Graphics.DrawImage(pageMetaFile, adjustedRect); // Prepare for next page. Make sure we haven't hit the end. m_currentPage++; e.HasMorePages = m_currentPage < m_pages.Count; } }
public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) { Bitmap bmp = new Bitmap(1, 1); Graphics bmpg = Graphics.FromImage(bmp); IntPtr hdc = bmpg.GetHdc(); ms = new MemoryStream(); Metafile meta = new Metafile(ms, hdc, EmfType.EmfPlusDual); bmpg.ReleaseHdc(hdc); this.pic.Image = meta; Graphics g = Graphics.FromImage(meta); PaperSize size = e.PageSettings.PaperSize; int height = size.Height * dpi / 100; int width = size.Width * dpi / 100; if (e.PageSettings.Landscape) { g.FillRectangle(Brushes.White, 0, 0, height, width); g.SetClip(new Rectangle(0, 0, height - 16, width - 16)); } else { g.FillRectangle(Brushes.White, 0, 0, width, height); g.SetClip(new Rectangle(0, 0, width - 16, height - 16)); } return g; }
/// <summary> /// Saves the specified <see cref="Metafile"/> at the specified path. /// </summary> /// /// <exception cref="ArgumentNullException"> /// <para> /// <paramref name="path"/> is <see langword="null"/>. /// </para> /// -or- /// <para> /// <paramref name="path"/> is an empty string. /// </para> /// -or- /// <para> /// <paramref name="metafileToSave"/> is <see langword="null"/>. /// </para> /// </exception> public static void Save(string path, Metafile metafileToSave) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } if (metafileToSave == null) { throw new ArgumentNullException("metafileToSave"); } FileStream stream = null; try { stream = new FileStream(path, FileMode.Create); Save(stream, metafileToSave); } catch { throw; } finally { if (stream != null) { stream.Flush(); stream.Close(); } } }
private static void DrawTree(TreeNode treeNode, string file) { using (Metafile mf = new Metafile(file, Graphics.FromHwnd(IntPtr.Zero).GetHdc(), EmfType.EmfOnly)) { using (Graphics graphics = Graphics.FromImage(mf)) { graphics.PageUnit = GraphicsUnit.Point; Font labelFont = new Font("SimSun", 9.0f, FontStyle.Regular, GraphicsUnit.Point); DrawTreeContext context = new DrawTreeContext() { Graphics = graphics, BorderPen = new Pen(Color.Black, 0.75f), ConnectorPen = new Pen(Color.Black, 0.5f), LabelBrush = Brushes.Black, LabelFont = labelFont, LabelHeight = labelFont.Size, NodeHorizontalSep = 9.0, NodeVerticalSep = 24.0, NodeHorizontalPadding = 3.75, NodeVerticalPadding = 3.75, PreferCjk = true }; treeNode.DrawTree(context, new PointD(treeNode.Layout(context).Pivot, 0.0)); } } }
/// <summary> /// Create image metafile constructor /// </summary> /// <param name="Width">Image width in pixels.</param> /// <param name="Height">Image height in pixels.</param> public CreateMetafile( Int32 Width, Int32 Height ) { using (MemoryStream Stream = new MemoryStream()) { using (Graphics MemoryGraphics = Graphics.FromHwndInternal(IntPtr.Zero)) { IntPtr deviceContextHandle = MemoryGraphics.GetHdc(); Metafile = new Metafile(Stream, deviceContextHandle, new RectangleF(0, 0, Width, Height), MetafileFrameUnit.Pixel, EmfType.EmfPlusOnly); MemoryGraphics.ReleaseHdc(); } } Graphics = Graphics.FromImage(Metafile); // Set everything to high quality Graphics.SmoothingMode = SmoothingMode.HighQuality; Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; Graphics.CompositingQuality = CompositingQuality.HighQuality; Graphics.PageUnit = GraphicsUnit.Pixel; return; }
protected override Image DrawSvg(SvgDocument svgDoc) { // GDI+ Metafile metafile; using (var stream = new MemoryStream()) using (var img = new Bitmap((int)svgDoc.Width.Value, (int)svgDoc.Height.Value)) // Not necessary if you use Control.CreateGraphics(). using (Graphics ctrlGraphics = Graphics.FromImage(img)) // Control.CreateGraphics() { IntPtr handle = ctrlGraphics.GetHdc(); var rect = new RectangleF(0, 0, svgDoc.Width, svgDoc.Height); metafile = new Metafile(stream, handle, rect, MetafileFrameUnit.Pixel, EmfType.EmfPlusOnly); using (Graphics ig = Graphics.FromImage(metafile)) { svgDoc.Draw(ig); } ctrlGraphics.ReleaseHdc(handle); } return metafile; }
private static Image GetImageFromParams(object pict, IntPtr handle, int pictype, IntPtr paletteHandle, int width, int height) { switch (pictype) { case -1: return null; case 0: return null; case 1: return Image.FromHbitmap(handle, paletteHandle); case 2: { var wmfHeader = new WmfPlaceableFileHeader(); wmfHeader.BboxRight = (short) width; wmfHeader.BboxBottom = (short) height; var metafile = new Metafile(handle, wmfHeader, false); return (Image) RuntimeHelpers.GetObjectValue(metafile.Clone()); } case 4: { var metafile2 = new Metafile(handle, false); return (Image) RuntimeHelpers.GetObjectValue(metafile2.Clone()); } } throw new Exception("AXUnknownImage"); }
public void ProcessEMF(byte[] emf) { try { _ms = new MemoryStream(emf); _mf = new Metafile(_ms); _bm = new Bitmap(1, 1); g = Graphics.FromImage(_bm); //XScale = Width / _mf.Width; //YScale = Height/ _mf.Height; m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback); g.EnumerateMetafile(_mf, new Point(0, 0), m_delegate); } finally { if (g != null) g.Dispose(); if (_bm != null) _bm.Dispose(); if (_ms != null) { _ms.Close(); _ms.Dispose(); } } }
protected override void OnPrintPage(PrintPageEventArgs ev) { base.OnPrintPage(ev); if (this.m_EMFStreams == null || this.m_EMFStreams.Count == 0) { this.Export(this.m_LocalReport); this.m_CurrentPageIndex = 0; if (this.m_EMFStreams.Count == 0 || this.m_EMFStreams == null) { return; } } this.m_PageImage = new Metafile(this.m_EMFStreams[this.m_CurrentPageIndex]); ev.Graphics.DrawImageUnscaledAndClipped(this.m_PageImage, ev.PageBounds); this.m_CurrentPageIndex++; ev.HasMorePages = (this.m_CurrentPageIndex < this.m_EMFStreams.Count); if (this.m_CurrentPageIndex == this.m_EMFStreams.Count) { this.m_CurrentPageIndex = 0; this.m_EMFStreams.Clear(); this.m_EMFStreams = null; this.m_PageImage.Dispose(); base.Dispose(); } }
private static void SaveClipboardEmf(Stream stream, ImageFormat format) { OpenClipboard(); try { if (!IsClipboardFormatAvailable(CF_ENHMETAFILE)) { Failed("No enhanced metafile data available."); } IntPtr ptr = GetClipboardData(CF_ENHMETAFILE); if (ptr == IntPtr.Zero) { Failed("Unable to retrieve data from clipboard even through Clipboard previously indicated data exists."); } var metafile = new Metafile(ptr, true); metafile.Save(stream, format); } finally { // "An application should call the CloseClipboard function after every successful call to OpenClipboard." // -- http://msdn.microsoft.com/en-us/library/windows/desktop/ms649048(v=vs.85).aspx CloseClipboard(); } }
public static Metafile Convert( string htmlSnippet, float leftBorder = 0, float topBorder = 0, float rightBorder = 0, float bottomBorder = 0) { Metafile image; IntPtr dib; IntPtr memoryHdc = Win32Utils.CreateMemoryHdc(IntPtr.Zero, 1, 1, out dib); try { image = new Metafile(memoryHdc, EmfType.EmfPlusDual, ".."); using (Graphics g = Graphics.FromImage(image)) { SizeF size = HtmlRender.Measure(g, htmlSnippet); g.FillRectangle( Brushes.White, leftBorder * -1, topBorder * -1, size.Width + leftBorder + rightBorder, size.Height + topBorder + bottomBorder); SizeF sizeF = HtmlRender.Render(g, htmlSnippet); } } finally { Win32Utils.ReleaseMemoryHdc(memoryHdc, dib); } return image; }
protected override void PrintPage(System.Drawing.Imaging.Metafile file, PrintPageEventArgs e, int width, int height) { // 纸张大小 float paperWidth = CustomBaseDoc.PaperWidth / 2.54f * 100.0f; float paperHeight = CustomBaseDoc.PaperHeight / 2.54f * 100.0f; float clipWidth = paperWidth < e.Graphics.VisibleClipBounds.Width ? paperWidth : e.Graphics.VisibleClipBounds.Width; float clipHeight = paperHeight < e.Graphics.VisibleClipBounds.Height ? paperHeight : e.Graphics.VisibleClipBounds.Height; // 打印机边距 float marginOX = paperWidth - clipWidth + e.Graphics.VisibleClipBounds.Left; float marginOY = paperHeight - clipHeight + e.Graphics.VisibleClipBounds.Top; // 左侧留2.5 cm 装订 //float left = 2.5f / 2.54f * 100.0f; float left = 0.4f / 2.54f * 100.0f; // 左右平均分配空间 float marginX = (clipWidth + marginOX - left - (float)width) / 2; // 上下平均分配空间,但上面最多空1 cm float top = 1f / 2.54f * 100.0f; float marginY = (clipHeight + marginOY - (float)height) / 2; if (marginY > top) { marginY = top; } marginX = left + marginX - marginOX / 2; marginY = marginY - marginOY / 2; e.Graphics.DrawImage(file, new RectangleF(marginX, marginY, (float)width, (float)height)); }
/// <summary> /// Saves the specified <see cref="Metafile"/> to the specified <see cref="Stream"/>. /// </summary> /// <exception cref="ArgumentNullException"> /// <para> /// <paramref name="streamToSaveTo"/> is <see langword="null"/>. /// </para> /// -or- /// <para> /// <paramref name="metafileToSave"/> is <see langword="null"/>. /// </para> /// </exception> public static void Save(Stream streamToSaveTo, Metafile metafileToSave) { if (streamToSaveTo == null) { throw new ArgumentNullException("streamToSaveTo"); } if (metafileToSave == null) { throw new ArgumentNullException("metafileToSave"); } Metafile bufferMetafile = null; using (Bitmap bitmap = new Bitmap(1, 1)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { IntPtr ptr = graphics.GetHdc(); bufferMetafile = new Metafile(streamToSaveTo, ptr); graphics.ReleaseHdc(ptr); } } using (Graphics graphics = Graphics.FromImage(bufferMetafile)) { graphics.DrawImage(metafileToSave, 0, 0); } }
/// <summary> /// Copies the given <see cref="T:System.Drawing.Imaging.MetaFile" /> to the clipboard. /// The given <see cref="T:System.Drawing.Imaging.MetaFile" /> is set to an invalid state inside this function. /// </summary> public static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile metafile, bool clearClipboard) { if (metafile == null) throw new ArgumentNullException("metafile"); bool bResult = false; IntPtr hEMF, hEMF2; hEMF = metafile.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(IntPtr.Zero)) { try { hEMF2 = CopyEnhMetaFile(hEMF, null); if (!hEMF2.Equals(IntPtr.Zero)) { if (OpenClipboard(hWnd)) { try { if (clearClipboard) { if (!EmptyClipboard()) return false; } IntPtr hRes = SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2); bResult = hRes.Equals(hEMF2); } finally { CloseClipboard(); } } } } finally { DeleteEnhMetaFile(hEMF); } } return bResult; }
// Загрузка рисунка из файла private void LoadWMFFile(String name) { // Создание рисунка из файла this.wmfImage = new Metafile(name); // Вызов метода перерисовки формы this.Invalidate(); }
private void PrintPage(object sender, PrintPageEventArgs ev) { Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); ev.Graphics.DrawImage(pageImage, ev.PageBounds); m_currentPageIndex++; ev.HasMorePages = (m_currentPageIndex < m_streams.Count); }
protected virtual void SaveMetafileToFile(System.Drawing.Imaging.Metafile image, string output) { using (Stream s = new FileStream(output, FileMode.Create)) { Log.LogMessage("Saving image as jpg to {0}", output); image.Save(s, ImageFormat.Jpeg); } }
/// <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; }
/* * MetafileToString */ /// <summary> /// </summary> /// <exception cref="ArgumentNullException"> /// <paramref name="metafileToConvert"/> is <see langword="null"/>. /// </exception> public static string MetafileToString(Metafile metafileToConvert) { if (metafileToConvert == null) { throw new ArgumentNullException("metafileToConvert"); } byte[] buffer = NuGenMetafileConverter.MetafileToBytes(metafileToConvert); return Convert.ToBase64String(buffer); }
public EMFRenderer(int width, int height) { Bitmap bmp = new Bitmap(width, height); m_graphics = Graphics.FromImage(bmp); m_stream = new MemoryStream(); m_metafile = new Metafile(m_graphics.GetHdc(), new RectangleF(0, 0, width, height), MetafileFrameUnit.Pixel); m_graphics.ReleaseHdc(); m_graphics.Dispose(); bmp.Dispose(); m_graphics = Graphics.FromImage(m_metafile); }
private void CreateInternalMetafile(EmfType type) { //Create a temporary bitmap to get an HDC Graphics graphics = Component.Instance.CreateGraphics(); IntPtr hDC = graphics.GetHdc(); //Create metafile based on type and get graphics handle mMetafile = new System.Drawing.Imaging.Metafile(hDC, type); graphics.ReleaseHdc(hDC); graphics.Dispose(); }
public override void skolaUppdaterad() { if ( _mf!=null ) _mf.Dispose(); string strMF = Global.Skola.HomePathCombine( "!fotoorder.emf" ); if ( System.IO.File.Exists(strMF) ) _mf = new Metafile( strMF ); else _mf = null; resize2(this.ClientSize); this.Invalidate(); }
public static void SaveMetafile(Metafile mf, Stream stream) { IntPtr henh = mf.GetHenhmetafile (); int size = GetEnhMetaFileBits (henh, 0, null); byte[] buffer = new byte[size]; if (GetEnhMetaFileBits (henh, size, buffer) <= 0) throw new SystemException ("GetEnhMetaFileBits"); stream.Write (buffer, 0, buffer.Length); stream.Flush (); }
public void visa( string strPath ) { if ( _mf!=null ) _mf.Dispose(); _mf = null; if ( strPath!=null ) { string strMF = Path.Combine( strPath, "!fotoorder.emf" ); if ( System.IO.File.Exists(strMF) ) _mf = new Metafile( strMF ); } this.Invalidate(); }
/// <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> // ReSharper disable UnusedMember.Local public static string GetRtfImage(Image image) { // Allows the x-coordinates and y-coordinates of the metafile to be adjusted // independently const int mmAnisotropic = 8; var rtf = new StringBuilder(); var stream = new MemoryStream(); // Get a graphics context from the RichTextBox Graphics graphics; Metafile metaFile; using (graphics = Graphics.FromHwnd(new IntPtr(0))) { // Get the device context from the graphics context var hdc = graphics.GetHdc(); // Create a new Enhanced Metafile from the device context metaFile = new Metafile(stream, hdc); // Release the device context graphics.ReleaseHdc(hdc); } // Get a graphics context from the Enhanced Metafile using (graphics = Graphics.FromImage(metaFile)) graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); // Get the handle of the Enhanced Metafile var 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. var bufferSize = NativeMethods.GdipEmfToWmfBits(hEmf, 0, null, mmAnisotropic, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Create an array to hold the bits var 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. NativeMethods.GdipEmfToWmfBits(hEmf, bufferSize, buffer, mmAnisotropic, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Append the bits to the RTF string foreach (var b in buffer) rtf.Append(String.Format("{0:X2}", b)); return rtf.ToString(); }
/// <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; }
/* * MetafileToBytes */ /// <summary> /// </summary> /// <exception cref="ArgumentNullException"> /// <paramref name="metafile"/> is <see langword="null"/>. /// </exception> public static byte[] MetafileToBytes(Metafile metafile) { if (metafile == null) { throw new ArgumentNullException("metafile"); } MemoryStream stream = new MemoryStream(); NuGenMetafileSaver.Save(stream, metafile); stream.Flush(); byte[] buffer = stream.GetBuffer(); stream.Close(); return buffer; }
public RadBitmapData Decode(Stream stream) { Metafile metaFile = new Metafile(stream); int width = metaFile.Width; int height = metaFile.Height; float scaleFactor = 1f; if (metaFile.Width > maxPixelSize || metaFile.Height > maxPixelSize) { scaleFactor = Math.Max((float)metaFile.Width / (float)maxPixelSize, (float)metaFile.Height / (float)maxPixelSize); width = (int)(width / scaleFactor); height = (int)(height / scaleFactor); } // Create a PictureBox control and load the metafile PictureBox box = new PictureBox(); box.Width = width; box.Height = height; box.BackColor = Color.White; box.SizeMode = PictureBoxSizeMode.StretchImage; box.Image = metaFile; // Create snapshot of the PictureBox and save it as a bitmap Bitmap bmp = new Bitmap(width, height); box.DrawToBitmap(bmp, new Rectangle(0, 0, width, height)); //load the image in WPF RadBitmap result = null; RadBitmapData data = null; using (MemoryStream output = new MemoryStream()) { BitmapImage image = new BitmapImage(); image.BeginInit(); bmp.Save(output, this.encoder, null); output.Seek(0, SeekOrigin.Begin); image.StreamSource = output; image.EndInit(); result = new RadBitmap(image); data = new RadBitmapData(result.Width, result.Height, result.GetPixels()); } return data; }
/// <summary> /// Converts a Metafile to specified image format(s). /// </summary> static void ExportMetafile(System.Drawing.Imaging.Metafile metafile, string baseSheetFileName, Options options) { if (options.ExportBMP) { // Build full path to BMP. var bmpFileName = String.Format("{0}.bmp", baseSheetFileName); // Convert EMF to BMP. metafile.Save(bmpFileName, ImageFormat.Bmp); Console.WriteLine("Extracted '{0}'.", bmpFileName); } if (options.ExportJPG) { // Build full path to JPG. var jpgFileName = String.Format("{0}.jpg", baseSheetFileName); // Convert EMF to JPG. metafile.Save(jpgFileName, ImageFormat.Jpeg); Console.WriteLine("Extracted '{0}'.", jpgFileName); } if (options.ExportPNG) { // Build full path to PNG. var pngFileName = String.Format("{0}.png", baseSheetFileName); // Convert EMF to PNG. metafile.Save(pngFileName, ImageFormat.Png); Console.WriteLine("Extracted '{0}'.", pngFileName); } if (options.ExportTIF) { // Build full path to TIF. var tifFileName = String.Format("{0}.tif", baseSheetFileName); // Convert EMF to TIF. metafile.Save(tifFileName, ImageFormat.Tiff); Console.WriteLine("Extracted '{0}'.", tifFileName); } }
TryPasteEnhancedMetafile() { // This interop code was adapted from the following post: // // http://www.eggheadcafe.com/community/aspnet/12/10018506/ // how-to-paste--metafile-fr.aspx // // NOTE: Do not try this non-interop technique: // // Object oData = Clipboard.GetData(DataFormats.EnhancedMetafile); // // if (oData != null) // { // System.Drawing.Imaging.Metafile oMetafile = // (System.Drawing.Imaging.Metafile)oData; // } // // When pasting from a chart image copied from Excel, the GetData() // call crashes Excel. Although the Clipboard class reports that the // DataFormats.EnhancedMetafile format is available (along with // "Preferred DropEffect", "InShellDragLoop", and "MetaFilePict"), it // does not seem to be the format that the .NET Framework is expecting. // Using the interop technique below works properly, however. Boolean bReturn = false; if ( OpenClipboard(this.Handle) ) { if ( IsClipboardFormatAvailable(CF_ENHMETAFILE) ) { IntPtr oPtr = GetClipboardData(CF_ENHMETAFILE); if ( !oPtr.Equals( new IntPtr(0) ) ) { Metafile oMetafile = new Metafile(oPtr, true); this.Image = (Metafile)oMetafile.Clone(); bReturn = true; } } CloseClipboard(); } return (bReturn); }
private static void Main(string[] args) { try { using (Metafile inFile = new Metafile(args[0])) { using (Metafile outFile = new Metafile(args[1], Graphics.FromHwnd(IntPtr.Zero).GetHdc(), EmfType.EmfOnly)) { using (Graphics graphics = Graphics.FromImage(outFile)) { graphics.DrawImage(inFile, Point.Empty); } } } } catch (Exception exception) { Console.Error.WriteLine("Error: {0}", exception.Message); } }
public static void SaveAsEmf(Metafile me, string fileName) { /* http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/12a1c749-b320-4ce9-aff7-9de0d7fd30ea How to save or serialize a Metafile: Solution found by : SWAT Team member _1 Date : Friday, February 01, 2008 1:38 PM */ int enfMetafileHandle = me.GetHenhmetafile().ToInt32(); int bufferSize = GetEnhMetaFileBits(enfMetafileHandle, 0, null); // Get required buffer size. byte[] buffer = new byte[bufferSize]; // Allocate sufficient buffer if (GetEnhMetaFileBits(enfMetafileHandle, bufferSize, buffer) <= 0) // Get raw metafile data. throw new SystemException("Fail"); FileStream ms = File.Open(fileName, FileMode.Create); ms.Write(buffer, 0, bufferSize); ms.Close(); ms.Dispose(); if (!DeleteEnhMetaFile(enfMetafileHandle)) //free handle throw new SystemException("Fail Free"); }
public static void TestWmf() { var path = @"C:\1.Wmf"; Bitmap bmp = new Bitmap(220, 220); Graphics gs = Graphics.FromImage(bmp); Metafile metafile = new Metafile(path, gs.GetHdc()); Graphics g = Graphics.FromImage(metafile); HatchBrush hb = new HatchBrush(HatchStyle.LightUpwardDiagonal, Color.Black, Color.White); g.FillEllipse(Brushes.Gray, 10f, 10f, 200, 200); g.DrawEllipse(new Pen(Color.Black, 1f), 10f, 10f, 200, 200); g.FillEllipse(hb, 30f, 95f, 30, 30); g.DrawEllipse(new Pen(Color.Black, 1f), 30f, 95f, 30, 30); g.FillEllipse(hb, 160f, 95f, 30, 30); g.DrawEllipse(new Pen(Color.Black, 1f), 160f, 95f, 30, 30); g.FillEllipse(hb, 95f, 30f, 30, 30); g.DrawEllipse(new Pen(Color.Black, 1f), 95f, 30f, 30, 30); g.FillEllipse(hb, 95f, 160f, 30, 30); g.DrawEllipse(new Pen(Color.Black, 1f), 95f, 160f, 30, 30); g.FillEllipse(Brushes.Blue, 60f, 60f, 100, 100); g.DrawEllipse(new Pen(Color.Black, 1f), 60f, 60f, 100, 100); g.FillEllipse(Brushes.BlanchedAlmond, 95f, 95f, 30, 30); g.DrawEllipse(new Pen(Color.Black, 1f), 95f, 95f, 30, 30); g.DrawRectangle(new Pen(System.Drawing.Brushes.Blue, 0.1f), 6, 6, 208, 208); g.DrawLine(new Pen(Color.Black, 0.1f), 110f, 110f, 220f, 25f); g.DrawString("剖面图", new Font("宋体", 9f), Brushes.Green, 220f, 20f); g.Save(); g.Dispose(); // bmp.Save(; }
/// <summary> /// Saves the graph as an enhanced windows metafile into the stream <paramref name="stream"/>. /// </summary> /// <param name="doc">The graph document used.</param> /// <param name="stream">The stream to save the metafile into.</param> /// <param name="dpiResolution">Resolution of the bitmap in dpi. Determines the pixel size of the bitmap.</param> /// <param name="backbrush">Brush used to fill the background of the image. Can be <c>null</c>.</param> /// <param name="pixelformat">The pixel format to use.</param> /// <returns>The metafile that was created using the stream.</returns> public static Metafile SaveAsMetafile(GraphDocument doc, System.IO.Stream stream, int dpiResolution, Brush backbrush, PixelFormat pixelformat) { // Create a bitmap just to have a graphics context System.Drawing.Bitmap helperbitmap = new System.Drawing.Bitmap(4, 4, pixelformat); helperbitmap.SetResolution(dpiResolution, dpiResolution); Graphics grfx = Graphics.FromImage(helperbitmap); // Code to write the stream goes here. IntPtr ipHdc = grfx.GetHdc(); System.Drawing.Imaging.Metafile mf = new System.Drawing.Imaging.Metafile(stream, ipHdc, doc.PageBounds, MetafileFrameUnit.Point); grfx.ReleaseHdc(ipHdc); grfx.Dispose(); grfx = Graphics.FromImage(mf); grfx.PageUnit = GraphicsUnit.Point; grfx.PageScale = 1; grfx.TranslateTransform(doc.PrintableBounds.X, doc.PrintableBounds.Y); doc.DoPaint(grfx, true); grfx.Dispose(); helperbitmap.Dispose(); return(mf); }
override internal void RunPage(Pages pgs, Row row) { Report rpt = pgs.Report; if (IsHidden(pgs.Report, row)) { return; } _ChartMatrix.RunReset(rpt); Rows _Data = GetFilteredData(rpt, row); SetMyData(rpt, _Data); SetPagePositionBegin(pgs); if (!AnyRowsPage(pgs, _Data)) // if no rows return { return; // nothing left to do } // Build the Chart bitmap, along with data regions Page p = pgs.CurrentPage; ChartBase cb = null; try { cb = RunChartBuild(rpt, row); // Build the chart if (!_isHYNEsWonderfulVector.EvaluateBoolean(rpt, row)) //AJM GJL 14082008 'Classic' Rendering { System.Drawing.Image im = cb.Image(rpt); // Grab the image int height = im.Height; // save height and width int width = im.Width; MemoryStream ostrm = new MemoryStream(); /* The following is a new image saving logic which will allow for higher * quality images using JPEG with 100% quality * 06122007AJM */ System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); // 20022008 AJM GJL - Centralised class with global encoder settings encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.ChartImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); // 06122007AJM The follow has been replaced with the code above //im.Save(ostrm, info); // generate a jpeg TODO: get png to work with pdf byte[] ba = ostrm.ToArray(); ostrm.Close(); PageImage pi = new PageImage(IMAGEFORMAT, ba, width, height); // Create an image RunPageRegionBegin(pgs); SetPagePositionAndStyle(rpt, pi, row); pi.SI.BackgroundImage = null; // chart already has the background image if (pgs.CurrentPage.YOffset + pi.Y + pi.H >= pgs.BottomOfPage && !pgs.CurrentPage.IsEmpty()) { // force page break if it doesn't fit on the page pgs.NextOrNew(); pgs.CurrentPage.YOffset = OwnerReport.TopOfPage; if (this.YParents != null) { pi.Y = 0; } } p = pgs.CurrentPage; p.AddObject(pi); // Put image onto the current page RunPageRegionEnd(pgs); if (!this.PageBreakAtEnd && !IsTableOrMatrixCell(rpt)) { float newY = pi.Y + pi.H; p.YOffset += newY; // bump the y location } SetPagePositionEnd(pgs, pi.Y + pi.H); } else //Ultimate Rendering - Vector //AJM GJL 14082008 { System.Drawing.Imaging.Metafile im = cb.Image(rpt); // Grab the image //im could still be saved to a bitmap at this point //if we were to offer a choice of raster or vector, it would probably //be easiest to draw the chart to the EMF and then save as bitmap if needed int height = im.Height; // save height and width int width = im.Width; byte[] ba = cb._aStream.ToArray(); cb._aStream.Close(); PageImage pi = new PageImage(ImageFormat.Wmf, ba, width, height); RunPageRegionBegin(pgs); SetPagePositionAndStyle(rpt, pi, row); pi.SI.BackgroundImage = null; // chart already has the background image if (pgs.CurrentPage.YOffset + pi.Y + pi.H >= pgs.BottomOfPage && !pgs.CurrentPage.IsEmpty()) { // force page break if it doesn't fit on the page pgs.NextOrNew(); pgs.CurrentPage.YOffset = OwnerReport.TopOfPage; if (this.YParents != null) { pi.Y = 0; } } p = pgs.CurrentPage; //GJL 25072008 - Charts now draw in EMFplus format and not in bitmap. Still using the "PageImage" for the positioning //paging etc, but we don't add it to the page. // ****************************************************************************************************************** // New EMF Processing... we want to add the EMF Components to the page and not the actual EMF... EMF emf = new EMF(pi.X, pi.Y, width, height); emf.ProcessEMF(ba); //Process takes the bytearray of EMFplus data and breaks it down into lines,ellipses,text,rectangles //etc... There are still a lot of GDI+ functions I haven't got to (and some I have no intention of getting to!). foreach (PageItem emfItem in emf.PageItems) { p.AddObject(emfItem); } // ****************************************************************************************************************** //p.AddObject(pi); RunPageRegionEnd(pgs); pi.Y += p.YOffset; if (!this.PageBreakAtEnd && !IsTableOrMatrixCell(rpt)) { float newY = pi.Y + pi.H; p.YOffset += newY; // bump the y location } SetPagePositionEnd(pgs, pi.Y + pi.H); //our emf size seems to be bigger than the jpeg... } } catch (Exception ex) { rpt.rl.LogError(8, string.Format("Exception in Chart handling.\n{0}\n{1}", ex.Message, ex.StackTrace)); } finally { if (cb != null) { cb.Dispose(); } } return; }
/// <summary> /// /// </summary> /// <param name="metafile"></param> public MetafileNode(System.Drawing.Imaging.Metafile metafile) { this.metafile = metafile; this.Bounds = this.metafile.GetBounds(ref this.grfxUnit); }
public void EnumerateMetafile(Imaging.Metafile metafile, Point destPoint, Graphics.EnumerateMetafileProc callback) { throw new NotImplementedException(); }
protected virtual void PrintPage(System.Drawing.Imaging.Metafile file, PrintPageEventArgs e, int width, int height) { e.Graphics.DrawImage(file, new Rectangle(e.MarginBounds.X, e.MarginBounds.Y, width, height)); }
protected virtual void doc_PrintPage(object sender, PrintPageEventArgs e) { //如果允许分页,则打印每一页,否则则打印当前页 if (_baseDoc.PagerSetting.AllowPage) { _baseDoc.PageIndexChanged(_baseDoc.PagerSetting.PagerDesc[_pageIndex].PageIndex, _baseDoc.PagerSetting.PagerDesc[_pageIndex].IsMain, _baseDoc.DataSource); } //创建 metafile _printMetafile = GetPageMetafile(); //_printMetafile.Save(@"D:\printMetafile0.emf"); //调整边距 Rectangle rect = new Rectangle(0, 0, _printMetafile.Width, _printMetafile.Height); double widthZoom = 1; double heightZoom = 1; double widthSize = (e.MarginBounds.Width); double heightSize = (e.MarginBounds.Height); if (widthSize < rect.Width) { widthZoom = widthSize / rect.Width; } //纵轴缩小 if (heightSize < rect.Height) { heightZoom = heightSize / rect.Height; } double zoom = (widthZoom < heightZoom) ? widthZoom : heightZoom; Rectangle zoomRect = new Rectangle(rect.X, rect.Y, (int)(rect.Width * zoom), (int)(rect.Height * zoom)); MemoryStream mStream = new MemoryStream(); Graphics ggggg = _baseDoc.CreateGraphics(); IntPtr ipHdctemp = ggggg.GetHdc(); Metafile mf = new Metafile(mStream, ipHdctemp); ggggg.ReleaseHdc(ipHdctemp); ggggg.Dispose(); Graphics gMf = Graphics.FromImage(mf); gMf.DrawImage(_printMetafile, zoomRect); gMf.Save(); gMf.Dispose(); _printMetafile = mf; //_printMetafile.Save(@"D:\printMetafile1.emf"); metafileDelegate = new Graphics.EnumerateMetafileProc(MetafileCallback); //开始正式打印 PrintPage(_printMetafile, e, zoomRect.Width, zoomRect.Height); metafileDelegate = null; _pageIndex++; if (_pageFromHeight) { Rectangle r = GetPrintRect(); if ((_pageIndex) * _pagePrintHeight < r.Height) { e.HasMorePages = true; } } else { if (_baseDoc.PagerSetting.AllowPage && _pageIndex < _baseDoc.PagerSetting.TotalPageCount) { e.HasMorePages = true; } else { _pageIndex = 0; } } }
/// <summary> /// /// </summary> /// <param name="metafile"></param> /// <param name="bounds"></param> /// <param name="grfxUnit"></param> public MetafileNode(System.Drawing.Imaging.Metafile metafile, RectangleF bounds, System.Drawing.GraphicsUnit grfxUnit) { this.metafile = metafile; this.Bounds = bounds; this.grfxUnit = grfxUnit; }
/// <summary> /// 打印——LocalReport利用PrintDocument方式打印 /// </summary> /// <param name="templatepath"></param> /// <param name="datasetname"></param> /// <param name="datasource"></param> /// <param name="rparams"></param> public static bool Print(string templatepath, string datasetname, object datasource, List <ReportParameter> rparams = null) { List <Stream> m_streams = new List <Stream>(); int m_currentPageIndex = 0; PrintDialog pdg = new PrintDialog(); pdg.Document = new System.Drawing.Printing.PrintDocument(); DialogResult result = pdg.ShowDialog(); if (result != DialogResult.OK && result != DialogResult.Yes) { return(false); } pdg.Document.PrinterSettings = pdg.PrinterSettings; PrintDocument pd = pdg.Document; LocalReport lr = new LocalReport(); lr.ReportPath = templatepath; lr.DataSources.Add(new ReportDataSource(datasetname, datasource)); if (rparams != null) { lr.SetParameters(rparams); } lr.Refresh(); string deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + //" <PageWidth>8.5in</PageWidth>" + //" <PageHeight>11in</PageHeight>" + //" <MarginTop>0.15in</MarginTop>" + //" <MarginLeft>0.5cm</MarginLeft>" + //" <MarginRight>0.1in</MarginRight>" + //" <MarginBottom>0.1in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; m_streams = new List <Stream>(); m_currentPageIndex = 0; CreateStreamCallback createStream = (name, fileNameExtension, encoding, mimeType, willSeek) => { //Stream stream = new FileStream(name + "." + fileNameExtension, FileMode.Create); Stream stream = new MemoryStream(); m_streams.Add(stream); return(stream); }; lr.Render("Image", deviceInfo, createStream, out warnings); lr.ReleaseSandboxAppDomain(); foreach (Stream stream in m_streams) { stream.Position = 0; } pd.PrintPage += (sender, e) => { System.Drawing.Imaging.Metafile pageImage = new System.Drawing.Imaging.Metafile(m_streams[m_currentPageIndex]); //e.Graphics.DrawImage(pageImage, 0, 0,e.PageSettings.PaperSize.Width,e.PageSettings.PaperSize.Height); e.Graphics.DrawImage(pageImage, e.PageBounds); m_currentPageIndex++; e.HasMorePages = (m_currentPageIndex < m_streams.Count); }; pd.Print(); return(true); }