public async Task<CommandResult> InvokeAsync() { string filePath = Path.GetTempFileName(); try { await InteractiveWorkflow.Plots.ExportToMetafileAsync( VisualComponent.ActivePlot, filePath, PixelsToInches(VisualComponent.Device.PixelWidth), PixelsToInches(VisualComponent.Device.PixelHeight), VisualComponent.Device.Resolution); InteractiveWorkflow.Shell.DispatchOnUIThread(() => { try { var mf = new System.Drawing.Imaging.Metafile(filePath); Clipboard.SetData(DataFormats.EnhancedMetafile, mf); } catch (Exception e) when (!e.IsCriticalException()) { InteractiveWorkflow.Shell.ShowErrorMessage(string.Format(Resources.Plots_CopyToClipboardError, e.Message)); } finally { try { File.Delete(filePath); } catch (IOException) { } } }); } catch (RPlotManagerException ex) { InteractiveWorkflow.Shell.ShowErrorMessage(ex.Message); } catch (OperationCanceledException) { } return CommandResult.Executed; }
/// <summary> /// Stream to file /// </summary> /// <param name="inputStream"></param> /// <param name="outputFile"></param> /// <param name="fileMode"></param> /// <param name="sourceRectangle"></param> /// <returns></returns> public static string StreamToFile(Stream inputStream, string outputFile, FileMode fileMode, DocumentFormat.OpenXml.Drawing.SourceRectangle sourceRectangle) { try { if (inputStream == null) throw new ArgumentNullException("inputStream"); if (String.IsNullOrEmpty(outputFile)) throw new ArgumentException("Argument null or empty.", "outputFile"); if (Path.GetExtension(outputFile).ToLower() == ".emf" || Path.GetExtension(outputFile).ToLower() == ".wmf") { System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(inputStream); System.Drawing.Rectangle cropRectangle; double leftPercentage = (sourceRectangle != null && sourceRectangle.Left != null) ? ToPercentage(sourceRectangle.Left.Value) : 0; double topPercentage = (sourceRectangle != null && sourceRectangle.Top != null) ? ToPercentage(sourceRectangle.Top.Value) : 0; double rightPercentage = (sourceRectangle != null && sourceRectangle.Left != null) ? ToPercentage(sourceRectangle.Right.Value) : 0; double bottomPercentage = (sourceRectangle != null && sourceRectangle.Left != null) ? ToPercentage(sourceRectangle.Bottom.Value) : 0; cropRectangle = new System.Drawing.Rectangle( (int)(emf.Width * leftPercentage), (int)(emf.Height * topPercentage), (int)(emf.Width - emf.Width * (leftPercentage + rightPercentage)), (int)(emf.Height - emf.Height * (bottomPercentage + topPercentage))); System.Drawing.Bitmap newBmp = new System.Drawing.Bitmap(cropRectangle.Width, cropRectangle.Height); using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(newBmp)) { graphic.Clear(System.Drawing.Color.White); graphic.DrawImage(emf, new System.Drawing.Rectangle(0, 0, cropRectangle.Width, cropRectangle.Height), cropRectangle, System.Drawing.GraphicsUnit.Pixel); } outputFile = outputFile.Replace(".emf", ".jpg"); newBmp.Save(outputFile, System.Drawing.Imaging.ImageFormat.Jpeg); return outputFile; } else { if (!File.Exists(outputFile)) { using (FileStream outputStream = new FileStream(outputFile, fileMode, FileAccess.Write)) { int cnt = 0; const int LEN = 4096; byte[] buffer = new byte[LEN]; while ((cnt = inputStream.Read(buffer, 0, LEN)) != 0) outputStream.Write(buffer, 0, cnt); } } return outputFile; } } catch (Exception ex) { throw ex; } }
internal override void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using (Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin)); // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g); Layout.BottomMargin = caSize.Height; // 20022008 AJM GJL - Added required info AdjustMargins(lRect,rpt,g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Category Axis if (caSize.Height > 0) DrawCategoryAxis(rpt, g, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, caSize.Height)); if (ChartDefn.Type == ChartTypeEnum.Doughnut) DrawPlotAreaDoughnut(rpt, g); else DrawPlotAreaPie(rpt, g); DrawLegend(rpt, g, false, false); } }
override internal void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); //_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height),System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using(Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; double max=0,min=0; // Get the max and min values // GetValueMaxMin(rpt, ref max, ref min,0, 1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin)); Layout.LeftMargin = 0; Layout.RightMargin = 0; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); Layout.BottomMargin = 0; AdjustMargins(lRect,rpt, g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); string subtype = _ChartDefn.Subtype.EvaluateString(rpt, _row); DrawMap(rpt, g, subtype, max, min); DrawLegend(rpt, g, false, false); } }
public GraphDocumentDataObject(GraphDocumentBase graphDocument, ProjectFileComObject fileComObject, ComManager comManager) : base(comManager) { ComDebug.ReportInfo("{0} constructor.", this.GetType().Name); _dataAdviseHolder = new ManagedDataAdviseHolder(); _graphDocumentName = graphDocument.Name; _graphDocumentSize = graphDocument.Size; _graphExportOptions = graphDocument.GetPropertyValue(ClipboardRenderingOptions.PropertyKeyClipboardRenderingOptions, () => new ClipboardRenderingOptions()).Clone(); var embeddedRenderingOptions = graphDocument.GetPropertyValue(EmbeddedObjectRenderingOptions.PropertyKeyEmbeddedObjectRenderingOptions, () => null); if (null != embeddedRenderingOptions) _graphExportOptions.CopyFrom(embeddedRenderingOptions); // merge embedded rendering options if ((_graphExportOptions.RenderEnhancedMetafile && _graphExportOptions.RenderEnhancedMetafileAsVectorFormat) || (_graphExportOptions.RenderDropFile && _graphExportOptions.DropFileImageFormat == System.Drawing.Imaging.ImageFormat.Emf) ) { if (graphDocument is Altaxo.Graph.Gdi.GraphDocument) _graphDocumentMetafileImage = GraphDocumentExportActions.RenderAsEnhancedMetafileVectorFormat((Altaxo.Graph.Gdi.GraphDocument)graphDocument, _graphExportOptions); } if (null == _graphDocumentMetafileImage || _graphExportOptions.RenderBitmap || _graphExportOptions.RenderWindowsMetafile || (_graphExportOptions.RenderEnhancedMetafile && !_graphExportOptions.RenderEnhancedMetafileAsVectorFormat) || _graphExportOptions.RenderDropFile) { if (graphDocument is Altaxo.Graph.Gdi.GraphDocument) _graphDocumentBitmapImage = GraphDocumentExportActions.RenderAsBitmap((Altaxo.Graph.Gdi.GraphDocument)graphDocument, _graphExportOptions.BackgroundBrush, System.Drawing.Imaging.PixelFormat.Format32bppArgb, _graphExportOptions.SourceDpiResolution, _graphExportOptions.SourceDpiResolution / _graphExportOptions.OutputScalingFactor); else if (graphDocument is Altaxo.Graph.Graph3D.GraphDocument) _graphDocumentBitmapImage = Altaxo.Graph.Graph3D.GraphDocumentExportActions.RenderAsBitmap((Altaxo.Graph.Graph3D.GraphDocument)graphDocument, _graphExportOptions.BackgroundBrush, System.Drawing.Imaging.PixelFormat.Format32bppArgb, _graphExportOptions.SourceDpiResolution, _graphExportOptions.SourceDpiResolution / _graphExportOptions.OutputScalingFactor); else throw new NotImplementedException(); } if (_graphExportOptions.RenderEmbeddedObject) { var miniProjectBuilder = new Altaxo.Graph.Procedures.MiniProjectBuilder(); _altaxoMiniProject = miniProjectBuilder.GetMiniProject(graphDocument, true); } else { _altaxoMiniProject = null; } }
private System.Drawing.Image GetImage(byte[] thumbnailBytes, int width, int height) { byte[] thumbnailRaw = thumbnailBytes; System.Drawing.Image retVal = null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream(thumbnailRaw)) { // we don't know what format the image is in, so we try a couple of formats try { // try the meta file format ms.Seek(12, System.IO.SeekOrigin.Begin); System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(ms); retVal = metafile.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(GetThumbnailImageAbort), System.IntPtr.Zero); } catch { // I guess it's not a metafile retVal = null; } if (retVal == null) { try { // try to stream to System.Drawing.Image ms.Seek(0, System.IO.SeekOrigin.Begin); System.Drawing.Image rawImage = System.Drawing.Image.FromStream(ms, true); retVal = rawImage.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(GetThumbnailImageAbort), System.IntPtr.Zero); } catch { // not compatible Image object retVal = null; } } } return(retVal); }
public static void CopyXAMLStreamToWmfClipBoard(Visual visual, Window clipboardOwnerWindow) { // http://xamltoys.codeplex.com/ try { var drawing = Utility.GetDrawingFromXaml(visual); var bounds = drawing.Bounds; Console.WriteLine("Drawing Bounds: {0}", bounds); MemoryStream wmfStream = new MemoryStream(); using (var g = CreateEmf(wmfStream, bounds)) Utility.RenderDrawingToGraphics(drawing, g); wmfStream.Position = 0; System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(wmfStream); IntPtr hEMF, hEMF2; hEMF = metafile.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { hEMF2 = NativeMethods.CopyEnhMetaFile(hEMF, new IntPtr(0)); if (!hEMF2.Equals(new IntPtr(0))) { if (NativeMethods.OpenClipboard(((IWin32Window)clipboardOwnerWindow.OwnerAsWin32()).Handle)) { if (NativeMethods.EmptyClipboard()) { NativeMethods.SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2); NativeMethods.CloseClipboard(); } } } NativeMethods.DeleteEnhMetaFile(hEMF); } } catch (Exception e) { MessageBox.Show(e.ToString()); } }
private BitmapSource ToBitmapSource(System.Drawing.Imaging.Metafile metafile) { BitmapSource bitmap; var img = (System.Drawing.Image)metafile; var bmp = new System.Drawing.Bitmap(img); //image // ┣bitmap // ┗enhancedMetafile using (var stream = new System.IO.MemoryStream()) { //img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); //metafile.Save(stream, System.Drawing.Imaging.ImageFormat.Png); bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Seek(0, System.IO.SeekOrigin.Begin); bitmap = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } return(bitmap); }
void ConvertToWMF(Stream emfStream, Stream wmfStream) { const int MM_ANISOTROPIC = 8; System.Drawing.Imaging.Metafile mf = new System.Drawing.Imaging.Metafile(emfStream); System.Drawing.Imaging.Metafile mf2 = new System.Drawing.Imaging.Metafile(@"c:\trash\test.emf"); int handle = mf.GetHenhmetafile().ToInt32(); int handle2 = mf2.GetHenhmetafile().ToInt32(); int bufferSize = GdipEmfToWmfBits(handle, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsIncludePlaceable); byte[] buf = new byte[bufferSize]; GdipEmfToWmfBits(handle, bufferSize, buf, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsIncludePlaceable); wmfStream.Write(buf, 0, bufferSize); }
/// <summary> /// Saves the image using the user's selections. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butExport_Click(object sender, EventArgs e) { //EXPORT. SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = GetSaveFilter(); saveFileDialog1.FileName = VectorDraw.Professional.Utilities.vdGlobals.GetFileNameWithoutExtension(mDoc.FileName); saveFileDialog1.InitialDirectory = VectorDraw.Professional.Utilities.vdGlobals.GetDirectoryName(mDoc.FileName); saveFileDialog1.RestoreDirectory = true; DialogResult res = saveFileDialog1.ShowDialog(this); Application.DoEvents(); if (res == DialogResult.OK) { string filename = saveFileDialog1.FileName; if ((filename != "") && (filename != null)) { if (filename.EndsWith(".emf", StringComparison.CurrentCultureIgnoreCase) || filename.EndsWith(".wmf", StringComparison.CurrentCultureIgnoreCase)) { IntPtr referencedc = VectorDraw.Render.GDIDraw.GDI.IntCreateDC("DISPLAY", "", "", IntPtr.Zero); System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(filename, referencedc, System.Drawing.Imaging.EmfType.EmfOnly, "FromVectorDraw6"); Color bkcolor = mDoc.ActiveRender.BkColor; System.Drawing.Size renderingSize = new System.Drawing.Size(mImg.Width, mImg.Height); System.Drawing.Graphics gr = Graphics.FromImage(emf); gr.FillRectangle(new SolidBrush(bkcolor), new Rectangle(new Point(0, 0), renderingSize)); mDoc.ActiveLayOut.RenderToGraphics(gr, mRenderBox, mImg.Width, mImg.Height); gr.Dispose(); emf.Dispose(); VectorDraw.Render.GDIDraw.GDI.DeleteDC(referencedc); } else { mImg.Save(filename); } this.DialogResult = DialogResult.OK; this.Close(); } } }
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 = CustomBaseDoc.PaperLeftOff / 2.54f * 100.0f; // 左右平均分配空间 float marginX = (clipWidth + marginOX - left - (float)width) / 2; if (marginX < 0) { marginX = 10; } // 上下平均分配空间,但上面最多空1 cm float top = CustomBaseDoc.PaperTopOff / 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; if (marginY < 30) { marginY = 30; } e.Graphics.DrawImage(file, new RectangleF(marginX, marginY, (float)width, (float)height)); }
private static System.Drawing.Bitmap ConvertMetafileToBitmap(System.Drawing.Imaging.Metafile emf) { using (System.IO.MemoryStream bmpStream = new System.IO.MemoryStream()) { using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(emf.Width, emf.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)) { bmp.SetResolution(emf.HorizontalResolution, emf.VerticalResolution); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp)) { g.Clear(System.Drawing.Color.Transparent); g.DrawImage(emf, 0, 0); } bmp.Save(bmpStream, System.Drawing.Imaging.ImageFormat.Png); } bmpStream.Flush(); bmpStream.Position = 0; System.Drawing.Bitmap final = new System.Drawing.Bitmap(bmpStream); return(final); } }
public static System.Drawing.Imaging.Metafile GetEnhMetafileOnClipboard(IntPtr hWnd) { System.Drawing.Imaging.Metafile meta = null; if (OpenClipboard(hWnd)) { try { if (IsClipboardFormatAvailable(CF_ENHMETAFILE) != 0) { IntPtr hmeta = GetClipboardData(CF_ENHMETAFILE); meta = new System.Drawing.Imaging.Metafile(hmeta, true); } } finally { CloseClipboard(); } } return(meta); }
private void PrintPage(object sender, PrintPageEventArgs ev) { System.Drawing.Imaging.Metafile pageImage = new System.Drawing.Imaging.Metafile(m_streams[m_currentPageIndex]); // Adjust rectangular area with printer margins. Rectangle adjustedRect = new Rectangle( ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX, ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY, ev.PageBounds.Width, ev.PageBounds.Height); // Draw a white background for the report ev.Graphics.FillRectangle(Brushes.White, adjustedRect); // Draw the report content ev.Graphics.DrawImage(pageImage, adjustedRect); // Prepare for the next page. Make sure we haven't hit the end. m_currentPageIndex++; ev.HasMorePages = (m_currentPageIndex < m_streams.Count); }
private async System.Threading.Tasks.Task CopyToClipboardAsMetafileAsync() { if (_rSession != null) { string fileName = Path.GetTempFileName(); using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { await eval.ExportToMetafileAsync(fileName, PixelsToInches(_lastPixelWidth), PixelsToInches(_lastPixelHeight), _lastResolution); VsAppShell.Current.DispatchOnUIThread( () => { try { var mf = new System.Drawing.Imaging.Metafile(fileName); Clipboard.SetData(DataFormats.EnhancedMetafile, mf); SafeFileDelete(fileName); } catch (Exception e) when(!e.IsCriticalException()) { MessageBox.Show(string.Format(Resources.PlotCopyToClipboardError, e.Message)); } }); } } }
public WindowTopBar(Form parent) { InitializeComponent(); this.Dock = DockStyle.Top; this.BackColor = System.Drawing.ColorTranslator.FromHtml("#242931"); this.ForeColor = System.Drawing.ColorTranslator.FromHtml("#acb0b7"); this.parent = parent; reduceIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.reduce)); selectedReduceIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.reduce_selected)); clickedReduceIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.reduce_clicked)); minimizeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.minimize)); selectedMinimizeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.minimize_selected)); clickedMinimizeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.minimize_clicked)); maximizeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.maximize)); selectedMaximizeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.maximize_selected)); clickedMaximizeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.maximize_clicked)); closeIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.close)); selectedCloseIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.close_selected)); clickedCloseIcon = new System.Drawing.Imaging.Metafile(new System.IO.MemoryStream(Properties.Resources.close_clicked)); reduceMetafile = reduceIcon; minimizeMetafile = minimizeIcon; maximizeMetafile = maximizeIcon; closeMetafile = closeIcon; mouseDown = false; lastLocation = Point.Empty; parent.Controls.Add(this); }
private static KeyValuePair<Range, Content> ProcessInlineShape( InlineShape _shape ) { float width = _shape.Width; float height = _shape.Height; string altText = ""; string title = ""; try { float scaleWidth = _shape.ScaleWidth; if ( scaleWidth > 0.0 ) { //width *= (scaleWidth / 100.0f); } } catch { } try { float scaleHeight = _shape.ScaleHeight; if ( scaleHeight > 0.0 ) { //height *= (scaleHeight / 100.0f); } } catch { } try { altText = _shape.AlternativeText; } catch { } try { title = _shape.Title; } catch { } PngImageContent imageContent = null; _shape.Range.CopyAsPicture(); object pngData = Clipboard.GetData( "PNG" ); if ( pngData is System.IO.MemoryStream ) { imageContent = new PngImageContent( (System.IO.MemoryStream) pngData, altText, title, width, height ); } else { if ( Clipboard.ContainsData( DataFormats.EnhancedMetafile ) ) { if ( ClipboardFunctions.OpenClipboard( IntPtr.Zero ) ) { width *= 1.5f; height *= 1.5f; IntPtr data = ClipboardFunctions.GetClipboardData( DataFormats.GetFormat( DataFormats.EnhancedMetafile ).Id ); System.Drawing.Imaging.Metafile metaFile = new System.Drawing.Imaging.Metafile( data, true ); ClipboardFunctions.CloseClipboard(); System.Drawing.Bitmap pngImage = new System.Drawing.Bitmap( (int) width, (int) height ); using ( System.Drawing.Graphics g = System.Drawing.Graphics.FromImage( pngImage ) ) { g.DrawImage( metaFile, new System.Drawing.Rectangle( 0, 0, (int) width, (int) height ) ); } metaFile.Dispose(); System.IO.MemoryStream pngDataStream = new System.IO.MemoryStream(); pngImage.Save( pngDataStream, System.Drawing.Imaging.ImageFormat.Png ); pngDataStream.Seek( 0, System.IO.SeekOrigin.Begin ); imageContent = new PngImageContent( pngDataStream, altText, title, width, height ); pngImage.Dispose(); } } } Clipboard.Clear(); if ( imageContent == null ) { return new KeyValuePair<Range, Content>( _shape.Range, new TextContent( String.Format( "INTERNAL ERROR: Could not convert shape to PNG image." ), Edward.ERROR_STYLE ) ); } else { return new KeyValuePair<Range, Content>( _shape.Range, imageContent ); } }
private async System.Threading.Tasks.Task CopyToClipboardAsMetafileAsync() { if (_rSession != null) { string fileName = Path.GetTempFileName(); using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { await eval.ExportToMetafile(fileName, PixelsToInches(_lastPixelWidth), PixelsToInches(_lastPixelHeight)); VsAppShell.Current.DispatchOnUIThread( () => { try { var mf = new System.Drawing.Imaging.Metafile(fileName); Clipboard.SetData(DataFormats.EnhancedMetafile, mf); SafeFileDelete(fileName); } catch (Exception e) when (!e.IsCriticalException()) { MessageBox.Show(string.Format(Resources.PlotCopyToClipboardError, e.Message)); } }); } } }
private void minimize_maximize_MouseLeave(object sender, EventArgs e) { minimizeMetafile = minimizeIcon; maximizeMetafile = maximizeIcon; minimize_maximize.Invalidate(); }
private static void SaveMasterPicture(string picture_filename, Master master) { stdole.IPicture master_picture_pic = (stdole.IPicture) master.Picture; IntPtr metafile_handle = (IntPtr) master_picture_pic.Handle; using (var metafile = new System.Drawing.Imaging.Metafile(metafile_handle, true)) { metafile.Save(picture_filename); } FormGetMasterImages.DeleteEnhMetaFile(metafile_handle); }
public void EnumerateMetafile(System.Drawing.Imaging.Metafile metafile, RectangleF destRect, RectangleF srcRect, GraphicsUnit unit, Graphics.EnumerateMetafileProc callback, IntPtr callbackData, System.Drawing.Imaging.ImageAttributes imageAttr) { throw new NotImplementedException(); }
private void close_MouseEnter(object sender, EventArgs e) { closeMetafile = selectedCloseIcon; close.Invalidate(); }
internal override void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); //_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height),System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using(Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; double max=0,min=0; // Get the max and min values GetValueMaxMin(rpt, ref max, ref min,0, 1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, min, max); Layout.LeftMargin = vaSize.Width; // Adjust the right margin to depend on the Value Axis bool Show2ndY = ShowRightYAxis(rpt); Size vaSize2= vaSize; if (Show2ndY) { double rmax = 0, rmin = 0; GetMaxMinDataValue(rpt, out rmax, out rmin, 0, 2); vaSize2 = ValueAxisSize(rpt, g, rmin, rmax); Layout.RightMargin = vaSize2.Width; } // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g); Layout.BottomMargin = caSize.Height; AdjustMargins(lRect,rpt, g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); int intervalCount = 0; //GJL - Used to get the interval count out of DrawValueAxis so that we don't recalculate it again. double incr = 0.0; //GJL - As above // Draw Value Axis //GJL now as by ref params to return the values to the above variables if (vaSize.Width > 0) // If we made room for the axis - we need to draw it DrawValueAxis(rpt, g, min, max, new System.Drawing.Rectangle(Layout.LeftMargin - vaSize.Width, Layout.TopMargin, vaSize.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin), Layout.LeftMargin, Layout.Width - Layout.RightMargin,out incr,out intervalCount); //******************************************************************************************************************************************** //Draw the 2nd value axis - obviously we will only want to do this if we choose a second axis double ScaleFactor = 1.0; //Secong value axis if (Show2ndY) Draw2ndValueAxis(rpt, g, min, max, new System.Drawing.Rectangle(Layout.LeftMargin + Layout.PlotArea.Width, Layout.TopMargin, vaSize2.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin), Layout.LeftMargin, Layout.Width - Layout.RightMargin, incr, intervalCount, ref ScaleFactor); // Draw Category Axis if (caSize.Height > 0) // 090508ajm passing chart bounds in DrawCategoryAxis(rpt, g, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, Layout.PlotArea.Width, caSize.Height), Layout.TopMargin, caSize.Width); if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked) DrawPlotAreaStacked(rpt, g, max, min); else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked) DrawPlotAreaPercentStacked(rpt, g); else DrawPlotAreaPlain(rpt, g, max, min,ScaleFactor); DrawLegend(rpt, g, false, false); } }
private void reduce_MouseLeave(object sender, EventArgs e) { reduceMetafile = reduceIcon; reduce.Invalidate(); }
private void reduce_MouseEnter(object sender, EventArgs e) { reduceMetafile = selectedReduceIcon; reduce.Invalidate(); }
private void close_MouseUp(object sender, MouseEventArgs e) { closeMetafile = selectedCloseIcon; close.Invalidate(); parent.Close(); }
private void close_MouseDown(object sender, MouseEventArgs e) { closeMetafile = clickedCloseIcon; close.Invalidate(); }
private void close_MouseLeave(object sender, EventArgs e) { closeMetafile = closeIcon; close.Invalidate(); }
public static List<System.Drawing.Imaging.Metafile> RenderMetafilesForReport( SSRSCommon.ReportService2005.ReportingService2005 rep_svc, SSRSCommon.ReportExecutionService.ReportExecutionService rep_exec_svc, string reportpath, EMFRenderPrefs userprintprefs, int FirstNPages) { var exec_header = new SSRSCommon.ReportExecutionService.ExecutionHeader(); rep_exec_svc.ExecutionHeaderValue = exec_header; string historyid = null; Console.WriteLine("Loading Report"); var exec_info = rep_exec_svc.LoadReport(reportpath, historyid); //rs2.SetExecutionParameters(parameters, "en-us"); var session_id = rep_exec_svc.ExecutionHeaderValue.ExecutionID; Console.WriteLine("Session ID: {0}", rep_exec_svc.ExecutionHeaderValue.ExecutionID); var streams = new List<System.IO.Stream>(); var metafiles = new List<System.Drawing.Imaging.Metafile>(); string render_format = "IMAGE"; int cur_page_count = 0; try { // Create the Viewer and Bind it to the Server Report Console.WriteLine("Creating the ReportViewer Control"); var viewer = new Microsoft.Reporting.WinForms.ReportViewer(); viewer.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote; var server_report = viewer.ServerReport; Console.WriteLine("Server Report DisplayName: {0}", server_report.DisplayName); Console.WriteLine("Server Report ReportPath: {0}", server_report.ReportPath); Console.WriteLine("Server Report ReportServerUrl: {0}", server_report.ReportServerUrl); Console.WriteLine("Server Report Timeout: {0}", server_report.Timeout); viewer.ServerReport.ReportServerUrl = new Uri(get_correct_url(rep_svc.Url)); viewer.ServerReport.ReportPath = reportpath; Console.WriteLine("Report Viewer ProcessingMode: {0}", viewer.ProcessingMode); Console.WriteLine("Report Viewer ReportServerUrl: {0}", viewer.ServerReport.ReportServerUrl); Console.WriteLine("Report Viewer ReportPath: {0}", viewer.ServerReport.ReportPath); // Setup URL Parameters Console.WriteLine("Creating the URL Parameters"); var url_params = new System.Collections.Specialized.NameValueCollection(); url_params.Add("rs:PersistStreams", "True"); // Create DeviceInfo XML var devinfo = new SSRSCommon.DeviceInfo(); devinfo.OutputFormat = "EMF"; // force it to emf devinfo.Toolbar = false; devinfo.PrintDpiX = emf_render_dpi.Width; devinfo.PrintDpiY = emf_render_dpi.Height; // Finished with DeviceInfo XML string device_info = devinfo.ToString(); Console.WriteLine("DeviceInfo: {0}", device_info); // render first stream Console.WriteLine("Starting Rendering First Stream"); string rendered_mimetype; string rendered_extension; var rendered_stream = server_report.Render( render_format, device_info, url_params, out rendered_mimetype, out rendered_extension); Console.WriteLine("Finished Rendering First Stream"); streams.Add(rendered_stream); cur_page_count++; // Handle the addtional streams Console.WriteLine("Retrieving Additional Streams"); url_params.Remove("rs:PersistStreams"); url_params.Add("rs:GetNextStream", "True"); do { // Check to see if user only wanted the first N pages of the report if (FirstNPages > 0) { if (cur_page_count >= FirstNPages) { break; } } // ------------ Console.WriteLine("Starting Rendering Additional Stream"); rendered_stream = server_report.Render( render_format, device_info, url_params, out rendered_mimetype, out rendered_extension); if (rendered_stream.Length != 0) { Console.WriteLine("Storing stream"); streams.Add(rendered_stream); } else { Console.WriteLine("Received stream of length zero"); } Console.WriteLine("Finished Rendering Additional Stream"); cur_page_count++; } while (rendered_stream.Length > 0); Console.WriteLine("Finished Retrieving Additional Streams"); } catch (System.Web.Services.Protocols.SoapException err) { Console.WriteLine("Caught SoapException"); Console.WriteLine("Message: {0}", err.Message); throw err; } finally { // Convert each stream into a metafile foreach (var stream in streams) { try { Console.WriteLine("Stream type: {0}", stream.GetType()); Console.WriteLine("Converting to metafile"); var memstream = (System.IO.MemoryStream)stream; Console.WriteLine("memstream size: {0}", memstream.Length); var metafile = new System.Drawing.Imaging.Metafile(memstream); metafiles.Add(metafile); Console.WriteLine("metafile size: {0}", metafile.Size); } finally { // Get rid of the steams stream.Close(); stream.Dispose(); } } streams = null; } return metafiles; }
public void EnumerateMetafile(System.Drawing.Imaging.Metafile metafile, Point destPoint, Graphics.EnumerateMetafileProc callback, IntPtr callbackData) { throw new NotImplementedException(); }
internal override void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using(Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.PageUnit = GraphicsUnit.Pixel; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; // 20022008 AJM GJL - Added new required info double ymax=0,ymin=0; // Get the max and min values for the y axis GetValueMaxMin(rpt, ref ymax, ref ymin, 1,1); double xmax = 0, xmin = 0; // Get the max and min values for the x axis GetValueMaxMin(rpt, ref xmax, ref xmin, 0,1); double bmax = 0, bmin = 0; // Get the max and min values for the bubble size if (ChartDefn.Type == ChartTypeEnum.Bubble) // only applies to bubble (not scatter) GetValueMaxMin(rpt, ref bmax, ref bmin, 2,1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, Layout.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, ymin, ymax); Layout.LeftMargin = vaSize.Width; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt,g, false, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g, xmin, xmax); Layout.BottomMargin = caSize.Height; AdjustMargins(lRect,rpt,g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Value Axis if (vaSize.Width > 0) // If we made room for the axis - we need to draw it DrawValueAxis(rpt, g, ymin, ymax, new System.Drawing.Rectangle(Layout.LeftMargin - vaSize.Width, Layout.TopMargin, vaSize.Width, Layout.PlotArea.Height), Layout.LeftMargin, _bm.Width - Layout.RightMargin); // Draw Category Axis if (caSize.Height > 0) DrawCategoryAxis(rpt, g, xmin, xmax, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin); // Draw Plot area data DrawPlot(rpt, g, xmin, xmax, ymin, ymax, bmin, bmax); DrawLegend(rpt, g, false, false); } }
public void EnumerateMetafile(System.Drawing.Imaging.Metafile metafile, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, Graphics.EnumerateMetafileProc callback) { throw new NotImplementedException(); }
public void EnumerateMetafile(System.Drawing.Imaging.Metafile metafile, RectangleF destRect, Graphics.EnumerateMetafileProc callback) { throw new NotImplementedException(); }
private void minimize_maximize_MouseDown(object sender, MouseEventArgs e) { minimizeMetafile = clickedMinimizeIcon; maximizeMetafile = clickedMaximizeIcon; minimize_maximize.Invalidate(); }
public void EnumerateMetafile(System.Drawing.Imaging.Metafile metafile, PointF[] destPoints, Graphics.EnumerateMetafileProc callback, IntPtr callbackData, System.Drawing.Imaging.ImageAttributes imageAttr) { throw new NotImplementedException(); }
/// <summary> /// Метод конвертирует исходный графический файл в wmetafile /// и создает строку для вставки в RTF-документ /// wmetafile т.к. его поддерживает большинство RTF редакторов /// </summary> private static StringBuilder BitmapToRtfImage(Image image) { StringBuilder sb = new StringBuilder(); MemoryStream memory = null; System.Drawing.Imaging.Metafile metaFile = null; try { memory = new MemoryStream(); using (Graphics graphics = Graphics.FromImage(image)) { IntPtr ptr = graphics.GetHdc(); metaFile = new System.Drawing.Imaging.Metafile(memory, ptr); graphics.ReleaseHdc(ptr); } using (Graphics graphics = Graphics.FromImage(metaFile)) { graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); } IntPtr metaPtr = metaFile.GetHenhmetafile(); // указатель на метафайл uint bufferSize = NativeMethods.GdipEmfToWmfBits(metaPtr, 0, null, MM_ANISOTROPIC, NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // получаем размер массива byte[] buffer = new byte[bufferSize]; // здесь хранится метафайл NativeMethods.GdipEmfToWmfBits(metaPtr, bufferSize, buffer, MM_ANISOTROPIC, NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); //копируем файл в буфер NativeMethods.DeleteEnhMetaFile(metaPtr);//удаление метафайла byte[] block; int blockSize = 0x100000; int bufferBytesToRead = buffer.Length; int currentBufferPosition = 0; // копируем байты метафайла в StringBuilder попутно переводя в правильный текстовый формат while (bufferBytesToRead > blockSize) { block = new byte[blockSize]; Buffer.BlockCopy(buffer, currentBufferPosition, block, 0, blockSize); currentBufferPosition += blockSize; bufferBytesToRead -= blockSize; sb.Append(BitConverter.ToString(block, 0).Replace("-", string.Empty)); } if (bufferBytesToRead > 0) { block = new byte[bufferBytesToRead]; Buffer.BlockCopy(buffer, currentBufferPosition, block, 0, bufferBytesToRead); sb.Append(BitConverter.ToString(block, 0).Replace("-", string.Empty)); } //return sb.ToString(); } finally { if (metaFile != null) metaFile.Dispose(); if (memory != null) memory.Close(); } return sb; }
public void EnumerateMetafile(System.Drawing.Imaging.Metafile metafile, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit, Graphics.EnumerateMetafileProc callback, IntPtr callbackData) { throw new NotImplementedException(); }
private static void ConvertWmfFile(string sourcePath, string filePath, string destPath, FormatType format) { System.Windows.Controls.Canvas WPFCanvas = null; var convert = new WMFConversion.WMF2WPF(); var dpiX = 96; var dpiY = 96; string imageSavePath = null; try { Console.WriteLine("Converting: " + filePath); if (format == FormatType.Png) { dpiX = 96; dpiY = 96; } else if (format == FormatType.Xaml) { // For xaml we need to save bitmaps to file imageSavePath = Path.Combine(destPath, Path.GetFileNameWithoutExtension(filePath) + "_"); } if (format != FormatType.PngNative) { using (var loadStream = new FileStream(filePath, FileMode.Open)) { WPFCanvas = convert.Convert(loadStream, dpiX, dpiY, imageSavePath); } } if (format == FormatType.Png) { Directory.CreateDirectory(Path.Combine(destPath, Path.GetDirectoryName( filePath.Substring(sourcePath.Length + 1))) ); var outStream = new FileStream(Path.Combine(destPath, Path.Combine(Path.GetDirectoryName(filePath.Substring(sourcePath.Length + 1)), Path.GetFileNameWithoutExtension(filePath) + ".png")), FileMode.Create); var renderBitmap = new RenderTargetBitmap( (int)WPFCanvas.Width, (int)WPFCanvas.Height, 96d, 96d, PixelFormats.Pbgra32); renderBitmap.Render(WPFCanvas); // Use png encoder for our data var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(outStream); outStream.Close(); outStream.Dispose(); } else if (format == FormatType.PngNative) { Directory.CreateDirectory(Path.Combine(destPath, Path.GetDirectoryName( filePath.Substring(sourcePath.Length + 1))) ); var outStream = new FileStream(Path.Combine(destPath, Path.Combine(Path.GetDirectoryName(filePath.Substring(sourcePath.Length + 1)), Path.GetFileNameWithoutExtension(filePath) + "_native.png")), FileMode.Create); var metafile1 = new System.Drawing.Imaging.Metafile(filePath); metafile1.Save(outStream, System.Drawing.Imaging.ImageFormat.Png); outStream.Close(); outStream.Dispose(); } else { File.WriteAllText(Path.Combine(destPath, Path.GetFileNameWithoutExtension(filePath) + ".xaml"), System.Windows.Markup.XamlWriter.Save(WPFCanvas)); } } catch (Exception ex) { Console.Write(ex.ToString()); } }
override internal void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using (Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin)); // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g); Layout.BottomMargin = caSize.Height; // 20022008 AJM GJL - Added required info AdjustMargins(lRect, rpt, g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Category Axis if (caSize.Height > 0) { DrawCategoryAxis(rpt, g, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, caSize.Height)); } if (ChartDefn.Type == ChartTypeEnum.Doughnut) { DrawPlotAreaDoughnut(rpt, g); } else { DrawPlotAreaPie(rpt, g); } DrawLegend(rpt, g, false, false); } }
override internal void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using (Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; // 20022008 AJM GJL - Added new required info double max = 0, min = 0; // Get the max and min values GetValueMaxMin(rpt, ref max, ref min, 0, 1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, Layout.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, min, max); Layout.LeftMargin = vaSize.Width; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, ChartDefn.Type == ChartTypeEnum.Area? false: true, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g); Layout.BottomMargin = caSize.Height; AdjustMargins(lRect, rpt, g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); int intervalCount = 0; double incr = 0; // Draw Value Axis if (vaSize.Width > 0) // If we made room for the axis - we need to draw it { DrawValueAxis(rpt, g, min, max, new System.Drawing.Rectangle(Layout.LeftMargin - vaSize.Width, Layout.TopMargin, vaSize.Width, Layout.PlotArea.Height), Layout.LeftMargin, _bm.Width - Layout.RightMargin, out incr, out intervalCount); } // Draw Category Axis if (caSize.Height > 0) { //09052008ajm passing chart bounds int DrawCategoryAxis(rpt, g, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, Layout.PlotArea.Width, caSize.Height), Layout.TopMargin, caSize.Width); } // Draw Plot area data if (ChartDefn.Type == ChartTypeEnum.Area) { if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked) { DrawPlotAreaAreaStacked(rpt, g, min, max); } else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked) { DrawPlotAreaAreaPercentStacked(rpt, g); } else { DrawPlotAreaArea(rpt, g, min, max); } } else { DrawPlotAreaLine(rpt, g, min, max); } DrawLegend(rpt, g, ChartDefn.Type == ChartTypeEnum.Area? false: true, false); } }
override public void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using (Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.PageUnit = GraphicsUnit.Pixel; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; // 20022008 AJM GJL - Added new required info double ymax = 0, ymin = 0; // Get the max and min values for the y axis GetValueMaxMin(rpt, ref ymax, ref ymin, 1, 1); double xmax = 0, xmin = 0; // Get the max and min values for the x axis GetValueMaxMin(rpt, ref xmax, ref xmin, 0, 1); double bmax = 0, bmin = 0; // Get the max and min values for the bubble size if (ChartDefn.Type == ChartTypeEnum.Bubble) // only applies to bubble (not scatter) { GetValueMaxMin(rpt, ref bmax, ref bmin, 2, 1); } DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, Layout.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, ymin, ymax); Layout.LeftMargin = vaSize.Width; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g, xmin, xmax); Layout.BottomMargin = caSize.Height; AdjustMargins(lRect, rpt, g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Value Axis if (vaSize.Width > 0) // If we made room for the axis - we need to draw it { DrawValueAxis(rpt, g, ymin, ymax, new System.Drawing.Rectangle(Layout.LeftMargin - vaSize.Width, Layout.TopMargin, vaSize.Width, Layout.PlotArea.Height), Layout.LeftMargin, _bm.Width - Layout.RightMargin); } // Draw Category Axis if (caSize.Height > 0) { DrawCategoryAxis(rpt, g, xmin, xmax, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin); } // Draw Plot area data DrawPlot(rpt, g, xmin, xmax, ymin, ymax, bmin, bmax); DrawLegend(rpt, g, false, false); } }
private void minimize_maximize_MouseEnter(object sender, EventArgs e) { minimizeMetafile = selectedMinimizeIcon; maximizeMetafile = selectedMaximizeIcon; minimize_maximize.Invalidate(); }
public static List <System.Drawing.Imaging.Metafile> RenderMetafilesForReport( SSRSCommon.ReportService2005.ReportingService2005 rep_svc, SSRSCommon.ReportExecutionService.ReportExecutionService rep_exec_svc, string reportpath, EMFRenderPrefs userprintprefs, int FirstNPages) { var exec_header = new SSRSCommon.ReportExecutionService.ExecutionHeader(); rep_exec_svc.ExecutionHeaderValue = exec_header; string historyid = null; Console.WriteLine("Loading Report"); var exec_info = rep_exec_svc.LoadReport(reportpath, historyid); //rs2.SetExecutionParameters(parameters, "en-us"); var session_id = rep_exec_svc.ExecutionHeaderValue.ExecutionID; Console.WriteLine("Session ID: {0}", rep_exec_svc.ExecutionHeaderValue.ExecutionID); var streams = new List <System.IO.Stream>(); var metafiles = new List <System.Drawing.Imaging.Metafile>(); string render_format = "IMAGE"; int cur_page_count = 0; try { // Create the Viewer and Bind it to the Server Report Console.WriteLine("Creating the ReportViewer Control"); var viewer = new Microsoft.Reporting.WinForms.ReportViewer(); viewer.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote; var server_report = viewer.ServerReport; Console.WriteLine("Server Report DisplayName: {0}", server_report.DisplayName); Console.WriteLine("Server Report ReportPath: {0}", server_report.ReportPath); Console.WriteLine("Server Report ReportServerUrl: {0}", server_report.ReportServerUrl); Console.WriteLine("Server Report Timeout: {0}", server_report.Timeout); viewer.ServerReport.ReportServerUrl = new Uri(get_correct_url(rep_svc.Url)); viewer.ServerReport.ReportPath = reportpath; Console.WriteLine("Report Viewer ProcessingMode: {0}", viewer.ProcessingMode); Console.WriteLine("Report Viewer ReportServerUrl: {0}", viewer.ServerReport.ReportServerUrl); Console.WriteLine("Report Viewer ReportPath: {0}", viewer.ServerReport.ReportPath); // Setup URL Parameters Console.WriteLine("Creating the URL Parameters"); var url_params = new System.Collections.Specialized.NameValueCollection(); url_params.Add("rs:PersistStreams", "True"); // Create DeviceInfo XML var devinfo = new SSRSCommon.DeviceInfo(); devinfo.OutputFormat = "EMF"; // force it to emf devinfo.Toolbar = false; devinfo.PrintDpiX = emf_render_dpi.Width; devinfo.PrintDpiY = emf_render_dpi.Height; // Finished with DeviceInfo XML string device_info = devinfo.ToString(); Console.WriteLine("DeviceInfo: {0}", device_info); // render first stream Console.WriteLine("Starting Rendering First Stream"); string rendered_mimetype; string rendered_extension; var rendered_stream = server_report.Render( render_format, device_info, url_params, out rendered_mimetype, out rendered_extension); Console.WriteLine("Finished Rendering First Stream"); streams.Add(rendered_stream); cur_page_count++; // Handle the addtional streams Console.WriteLine("Retrieving Additional Streams"); url_params.Remove("rs:PersistStreams"); url_params.Add("rs:GetNextStream", "True"); do { // Check to see if user only wanted the first N pages of the report if (FirstNPages > 0) { if (cur_page_count >= FirstNPages) { break; } } // ------------ Console.WriteLine("Starting Rendering Additional Stream"); rendered_stream = server_report.Render( render_format, device_info, url_params, out rendered_mimetype, out rendered_extension); if (rendered_stream.Length != 0) { Console.WriteLine("Storing stream"); streams.Add(rendered_stream); } else { Console.WriteLine("Received stream of length zero"); } Console.WriteLine("Finished Rendering Additional Stream"); cur_page_count++; } while (rendered_stream.Length > 0); Console.WriteLine("Finished Retrieving Additional Streams"); } catch (System.Web.Services.Protocols.SoapException err) { Console.WriteLine("Caught SoapException"); Console.WriteLine("Message: {0}", err.Message); throw err; } finally { // Convert each stream into a metafile foreach (var stream in streams) { try { Console.WriteLine("Stream type: {0}", stream.GetType()); Console.WriteLine("Converting to metafile"); var memstream = (System.IO.MemoryStream)stream; Console.WriteLine("memstream size: {0}", memstream.Length); var metafile = new System.Drawing.Imaging.Metafile(memstream); metafiles.Add(metafile); Console.WriteLine("metafile size: {0}", metafile.Size); } finally { // Get rid of the steams stream.Close(); stream.Dispose(); } } streams = null; } return(metafiles); }
internal void ProcessImage(FormatState formatState) { string contentType; string imagePartUriString; switch (formatState.ImageFormat) { case RtfImageFormat.Wmf: case RtfImageFormat.Png: contentType = "image/png"; break; case RtfImageFormat.Jpeg: contentType = "image/jpeg"; break; default: contentType = string.Empty; break; } bool skipImage = (formatState.ImageScaleWidth < 0) || (formatState.ImageScaleHeight < 0); if (_wpfPayload != null && contentType != string.Empty && !skipImage) { // Get image part URI string and image binary steam to write Rtf image data // into the container of WpfPayload Stream imageStream = _wpfPayload.CreateImageStream(_imageCount, contentType, out imagePartUriString); using (imageStream) { if (formatState.ImageFormat != RtfImageFormat.Wmf) { // Write the image binary data on the container from Rtf image data _lexer.WriteImageData(imageStream, formatState.IsImageDataBinary); } else { // Read the windows metafile from the rtf content and then convert it // to bitmap data then save it as PNG on the container image part MemoryStream metafileStream = new MemoryStream(); ; using (metafileStream) { // Get Windows Metafile from rtf content _lexer.WriteImageData(metafileStream, formatState.IsImageDataBinary); metafileStream.Position = 0; // Create the metafile from the windows metafile data that is on rtf content System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(metafileStream); // Save image from the metafile to the container's image part as PNG type metafile.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png); } } } // Increase the image count to generate the image source name _imageCount++; formatState.ImageSource = imagePartUriString; // Create the image document node DocumentNode dnImage = new DocumentNode(DocumentNodeType.dnImage); dnImage.FormatState = formatState; StringBuilder imageStringBuilder = new StringBuilder(); // Add the xaml image element imageStringBuilder.Append("<Image "); // Add the xaml image width property imageStringBuilder.Append(" Width=\""); double width; if (formatState.ImageScaleWidth != 0) { width = formatState.ImageWidth * (formatState.ImageScaleWidth / 100); } else { width = formatState.ImageWidth; } imageStringBuilder.Append(width.ToString(CultureInfo.InvariantCulture)); imageStringBuilder.Append("\""); // Add the xaml image height property imageStringBuilder.Append(" Height=\""); double height = formatState.ImageHeight * (formatState.ImageScaleHeight / 100); if (formatState.ImageScaleHeight != 0) { height = formatState.ImageHeight * (formatState.ImageScaleHeight / 100); } else { height = formatState.ImageHeight; } imageStringBuilder.Append(height.ToString(CultureInfo.InvariantCulture)); imageStringBuilder.Append("\""); // Add the xaml image stretch property imageStringBuilder.Append(" Stretch=\"Fill"); imageStringBuilder.Append("\""); // Add the xaml image close tag imageStringBuilder.Append(">"); // Add the image source property as the complex property // This is for specifying BitmapImage.CacheOption as OnLoad instead of // the default OnDemand option. imageStringBuilder.Append("<Image.Source>"); imageStringBuilder.Append("<BitmapImage "); imageStringBuilder.Append("UriSource=\""); imageStringBuilder.Append(imagePartUriString); imageStringBuilder.Append("\" "); imageStringBuilder.Append("CacheOption=\"OnLoad\" "); imageStringBuilder.Append("/>"); imageStringBuilder.Append("</Image.Source>"); imageStringBuilder.Append("</Image>"); // Set Xaml for image element dnImage.Xaml = imageStringBuilder.ToString(); // Insert the image document node to the document node array DocumentNodeArray dna = _converterState.DocumentNodeArray; dna.Push(dnImage); dna.CloseAt(dna.Count - 1); } else { // Skip the image data if the image type is unknown or WpfPayload is null _lexer.AdvanceForImageData(); } }
override public void Draw(Report rpt) { CreateSizedBitmap(); //AJM GJL 14082008 Using Vector Graphics using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using (Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; double max=0,min=0; // Get the max and min values // 20022008 AJM GJL - Now requires Y axis identifier GetValueMaxMin(rpt, ref max, ref min, 0,1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g); Layout.LeftMargin = caSize.Width; // Adjust the bottom margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, min, max); Layout.BottomMargin = vaSize.Height; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); // 20022008 AJM GJL - Requires Rpt and Graphics AdjustMargins(lRect,rpt,g ); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Value Axis if (vaSize.Width > 0) // If we made room for the axis - we need to draw it DrawValueAxis(rpt, g, min, max, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin); // Draw Category Axis if (caSize.Height > 0) DrawCategoryAxis(rpt, g, new System.Drawing.Rectangle(Layout.LeftMargin - caSize.Width, Layout.TopMargin, caSize.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin)); if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked) DrawPlotAreaStacked(rpt, g, min, max); else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked) DrawPlotAreaPercentStacked(rpt, g); else DrawPlotAreaPlain(rpt, g, min, max); DrawLegend(rpt, g, false, false); // after the plot is drawn } }
private string ConvertToMetafileHexDataString(Stream imageStream) { MemoryStream metafileStream = new MemoryStream(); // Get the graphics to write image on the metafile System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero); // Create the empty metafile System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(metafileStream, graphics.GetHdc(), System.Drawing.Imaging.EmfType.EmfOnly); // Release HDC graphics.ReleaseHdc(); // Create the graphics for metafile destination System.Drawing.Graphics graphicsTarget = System.Drawing.Graphics.FromImage(metafile); // Create bitmap from the image source stream System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imageStream); // Draw the bitmap image to the metafile graphicsTarget.DrawImage(bitmap, System.Drawing.Point.Empty); // Dispose graphics target graphicsTarget.Dispose(); // Move to the start position metafileStream.Position = 0; // Create the enhance metafile from metafile stream what we rendered from the bitmap image System.Drawing.Imaging.Metafile enhanceMetafile = new System.Drawing.Imaging.Metafile(metafileStream); // Get the enhance metafile handle from the enhance metafile IntPtr hdc = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(this, IntPtr.Zero)); IntPtr hEnhanceMetafile = enhanceMetafile.GetHenhmetafile(); // Convert the enhance metafile to the windows metafile with Win32 GDI uint windowsMetafileSize = UnsafeNativeMethods.GetWinMetaFileBits(hEnhanceMetafile, 0, null, /*MapMode:MM_ANISOTROPIC*/8, hdc); Byte[] windowsMetafileBytes = new Byte[windowsMetafileSize]; UnsafeNativeMethods.GetWinMetaFileBits(hEnhanceMetafile, windowsMetafileSize, windowsMetafileBytes, /*MapMode:MM_ANISOTROPIC*/8, hdc); // Dispose metafile and metafile stream metafile.Dispose(); metafileStream.Dispose(); // return the windows metafile hex data string return ConvertToImageHexDataString(windowsMetafileBytes); }