示例#1
0
    public MemoryStream?MakeMetafileStream(object bitmap, FrameContainerViewModel container, IImageCache ic)
    {
        var g  = default(Graphics);
        var mf = default(Metafile);
        var ms = new MemoryStream();

        if (bitmap is not Bitmap image)
        {
            return(null);
        }

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

            using (g = Graphics.FromImage(mf))
            {
                var p = new ExportPresenter();
                var r = new WinFormsRenderer(_serviceProvider, 72.0 / 96.0);
                r.State.DrawShapeState = ShapeStateFlags.Printable;
                r.State.ImageCache     = ic;

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

                g.PageUnit = GraphicsUnit.Display;

                if (container is PageContainerViewModel page)
                {
                    p.Render(g, r, null, page.Template, 0, 0);
                }
                p.Render(g, r, null, container, 0, 0);

                r.ClearCache();
            }
        }
        finally
        {
            g?.Dispose();

            mf?.Dispose();
        }
        return(ms);
    }
        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            _metafile?.Dispose();

            _stream?.Dispose();

            Close();
        }
示例#3
0
        public MemoryStream MakeMetafileStream(Bitmap bitmap, IEnumerable <BaseShapeViewModel> shapes, 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 WinFormsRenderer(_serviceProvider, 72.0 / 96.0);
                    r.State.DrawShapeState = ShapeStateFlags.Printable;
                    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;

                    foreach (var shape in shapes)
                    {
                        shape.DrawShape(g, r, null);
                    }

                    r.ClearCache();
                }
            }
            finally
            {
                g?.Dispose();

                mf?.Dispose();
            }
            return(ms);
        }
示例#4
0
        void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.HasMorePages = true;
            this.chartControl1.PrimaryXAxis.LabelIntersectAction = ChartLabelIntersectAction.Wrap;
            if (mx == 0.0 && mi == 0.0)
            {
                mx = Convert.ToDouble(this.comboBox1.SelectedItem);
                mi = 0;
            }
            bool grayScale         = this.chartControl1.PrintDocument.ColorMode == ChartPrintColorMode.GrayScale;
            bool toolBatVisibility = this.chartControl1.ShowToolbar;

            if (!this.chartControl1.PrintDocument.PrintToolBar)
            {
                this.chartControl1.ShowToolbar = false;
            }

            if (m_currectAction.Value == PrintAction.PrintToPrinter &&
                this.chartControl1.PrintDocument.ColorMode == ChartPrintColorMode.CheckPrinter)
            {
                grayScale = this.chartControl1.PrintDocument.PrinterSettings.SupportsColor;
            }

            if (!grayScale)
            {
                this.chartControl1.PrimaryXAxis.Range.Min      = mi;
                this.chartControl1.PrimaryXAxis.Range.Max      = mx;
                this.chartControl1.PrimaryXAxis.Range.Interval = (this.chartControl1.PrimaryXAxis.Range.Max - this.chartControl1.PrimaryXAxis.Range.Min) / this.chartControl1.PrimaryXAxis.Range.NumberOfIntervals;
                mi = mx;
                mx = mx + Convert.ToDouble(this.comboBox1.SelectedItem);
                GraphicsContainer container = BeginTransform(e.Graphics);
                e.Graphics.ResetTransform();
                this.chartControl1.Draw(e.Graphics, e.MarginBounds);
                EndTransform(e.Graphics, container);
            }
            else if (grayScale)
            {
                ChartStyleInfo[] tempStyles = new ChartStyleInfo[this.chartControl1.Series.Count];
                Array            ps         = System.Enum.GetValues(typeof(PatternStyle));
                Array            ds         = System.Enum.GetValues(typeof(DashStyle));

                for (int i = 0; i < this.chartControl1.Series.Count; i++)
                {
                    tempStyles[i] = new ChartStyleInfo();
                    tempStyles[i].CopyFrom(this.chartControl1.Series[i].StylesImpl.Style);

                    this.chartControl1.Series[i].Style.Interior = new BrushInfo((PatternStyle)ps.GetValue(i % ps.Length), Color.Black, Color.White);
                    this.chartControl1.Series[i].Style.Border.MakeCopy(tempStyles[i], this.chartControl1.Series[i].Style.Border.Sip);
                    this.chartControl1.Series[i].Style.Border.Color     = Color.Transparent;
                    this.chartControl1.Series[i].Style.Border.DashStyle = (DashStyle)ds.GetValue(i % ds.Length);

                    if (this.chartControl1.Series[i].Type == ChartSeriesType.Line || this.chartControl1.Series[i].Type == ChartSeriesType.Spline || this.chartControl1.Series[i].Type == ChartSeriesType.StepLine || this.chartControl1.Series[i].Type == ChartSeriesType.RotatedSpline)
                    {
                        this.chartControl1.Series[i].Style.Interior = new BrushInfo((PatternStyle)ps.GetValue(i % ps.Length), Color.White, Color.Black);

                        if (this.chartControl1.Series3D || this.chartControl1.ChartInterior.BackColor == Color.Black)
                        {
                            this.chartControl1.Series[i].Style.Interior     = new BrushInfo((PatternStyle)ps.GetValue(i % ps.Length), Color.Black, Color.White);
                            this.chartControl1.Series[i].Style.Border.Color = Color.Transparent;
                        }
                    }
                }

                GraphicsContainer container = BeginTransform(e.Graphics);
                e.Graphics.ResetTransform();

                using (Image img = new Bitmap(e.MarginBounds.Width, e.MarginBounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(img))
                    {
                        this.chartControl1.ChartArea.PrimaryXAxis.Range.Min      = mi;
                        this.chartControl1.ChartArea.PrimaryXAxis.Range.Max      = mx;
                        this.chartControl1.ChartArea.PrimaryXAxis.Range.Interval = (this.chartControl1.ChartArea.PrimaryXAxis.Range.Max - this.chartControl1.ChartArea.PrimaryXAxis.Range.Min) / this.chartControl1.ChartArea.PrimaryXAxis.Range.NumberOfIntervals;
                        mi = mx;
                        mx = mx + Convert.ToDouble(this.comboBox1.SelectedItem);
                        IntPtr   hdc    = g.GetHdc();
                        Stream   stream = new MemoryStream();
                        Metafile mf     = new Metafile(stream, hdc);

                        this.chartControl1.Draw(mf, img.Size);

                        DrawingUtils.DrawGrayedImage(e.Graphics, mf, e.MarginBounds, new Rectangle(Point.Empty, img.Size));

                        g.ReleaseHdc(hdc);
                        g.Dispose();
                        mf.Dispose();
                    }
                }

                EndTransform(e.Graphics, container);

                for (int i = 0; i < this.chartControl1.Series.Count; i++)
                {
                    this.chartControl1.Series[i].StylesImpl.Style.ResetInterior();
                    this.chartControl1.Series[i].StylesImpl.Style.ResetBorder();
                    this.chartControl1.Series[i].StylesImpl.Style.CopyFrom(tempStyles[i]);
                }
            }
            ////END A little experimental code

            if (!this.chartControl1.PrintDocument.PrintToolBar)
            {
                this.chartControl1.ShowToolbar = toolBatVisibility;
            }

            this.chartControl1.Redraw(true);
            if (mx > end)
            {
                e.HasMorePages = false;
            }


            this.chartControl1.PrimaryXAxis.Range.Min      = start;
            this.chartControl1.PrimaryXAxis.Range.Max      = end;
            this.chartControl1.PrimaryXAxis.Range.Interval = Intervel;
        }
示例#5
0
        public bool Export(Stream stream, string extension, Graphics referenceGraphics,
                           DiagramAlertHandler alerteDelegate, IDictionary <string, object> specificRendererParameters)
        {
            bool result = false;

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

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

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

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

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

                        streamWriter.Close();
                    }
                    result = true;
                }
                finally
                {
                    _diagram.Scale = scaleSave;
                    _diagram.Layout(referenceGraphics);
                }
            }
            return(result);
        }
示例#6
0
        public void Save()
        {
            try
            {
                _saving = true;
                if (_tempFiles.Count == 0)
                {
                    MessageBox.Show("No pages where printed.", FrmMain._strTittle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                Application.DoEvents();
                string             strName            = _savename;
                DocumentFormat     documentFormat     = DocumentFormat.User;
                DocumentOptions    documentOptions    = null;
                PdfDocumentOptions PdfdocumentOptions = new PdfDocumentOptions();

                InstallFonts();

                string strExt = "";

                if (_format.ToLower() == "pdf")
                {
                    documentFormat  = DocumentFormat.Pdf;
                    documentOptions = new PdfDocumentOptions();
                    (documentOptions as PdfDocumentOptions).DocumentType  = PdfDocumentType.Pdf;
                    (documentOptions as PdfDocumentOptions).FontEmbedMode = DocumentFontEmbedMode.Auto;
                    strExt = "pdf";
                }

                if (_format.ToLower() == "doc")
                {
                    documentFormat  = DocumentFormat.Doc;
                    documentOptions = new DocDocumentOptions();
                    (documentOptions as DocDocumentOptions).TextMode = DocumentTextMode.Framed;
                    strExt = "doc";
                }

                if (_format.ToLower() == "xps")
                {
                    documentFormat  = DocumentFormat.Xps;
                    documentOptions = new XpsDocumentOptions();
                    strExt          = "xps";
                }

                if (_format.ToLower() == "text")
                {
                    documentFormat  = DocumentFormat.Text;
                    documentOptions = new TextDocumentOptions();
                    strExt          = "txt";
                }

                if (!strName.Contains("." + strExt.ToLower()))
                {
                    strName += "." + strExt.ToLower();
                }

                if (_jobData != null)
                {
                    strName = Path.GetDirectoryName(strName) + "\\(" + _jobData.IPAddress + ") " + Path.GetFileName(strName);
                }

                _fileSaved = strName;

                DocumentWriter documentWriter = new DocumentWriter();
                documentWriter.SetOptions(documentFormat, documentOptions);
                documentWriter.BeginDocument(strName, documentFormat);

                foreach (string strFile in _tempFiles)
                {
#if LEADTOOLS_V20_OR_LATER
                    DocumentWriterEmfPage documentPage = new DocumentWriterEmfPage();
#elif LEADTOOLS_V19_OR_LATER
                    DocumentEmfPage documentPage = new DocumentEmfPage();
#else
                    DocumentPage documentPage = DocumentPage.Empty;
#endif // #if LEADTOOLS_V19_OR_LATER
                    Metafile metaFile = new Metafile(strFile);

                    documentPage.EmfHandle = metaFile.GetHenhmetafile();

                    documentWriter.AddPage(documentPage);

                    (new Metafile(documentPage.EmfHandle, true)).Dispose();
                    metaFile.Dispose();
                }
                documentWriter.EndDocument();

                _saved  = true;
                _saving = false;
            }
            catch (Exception Ex)
            {
                _saving = false;
                MessageBox.Show(Ex.Message, FrmMain._strTittle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
示例#7
0
            /// <summary>
            /// Fills the given serialization context with this object
            /// </summary>
            /// <param name="info">The field information for the class</param>
            /// <param name="context">The stream containing the serialized object</param>
            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                //Add key
                info.AddValue("key", this.key);
                //Add image in a special way
                byte[] bits = null;

                // The Image class is not capable of multithreaded access.
                // Simultaneous access will throw a
                //    "InvalidOperationException: The object is currently in use elsewhere."
                // So it needs to be locked, and also locked anywhere else the Image is accessed
                // (such as in ImageSheetRenderer.Paint).
                using (Synchronizer.Lock(this.m_image)) {
                    if (this.m_image.RawFormat.Guid == ImageFormat.Emf.Guid)
                    {
                        info.AddValue("type", "emf");
                        Metafile mf  = (Metafile)((Metafile)this.m_image).Clone();
                        IntPtr   ptr = mf.GetHenhmetafile();
                        Debug.Assert(ptr != IntPtr.Zero, "Failed to get pointer to image.");
                        uint size = GetEnhMetaFileBits(ptr, 0, null);
                        bits = new byte[size];
                        uint numBits = GetEnhMetaFileBits(ptr, size, bits);
                        mf.Dispose();
                        Debug.Assert(size == numBits, "Improper serialization of metafile!");
                    }
                    else if (this.m_image.RawFormat.Guid == ImageFormat.Wmf.Guid)
                    {
                        info.AddValue("type", "wmf");
                        Metafile mf  = (Metafile)((Metafile)this.m_image).Clone();
                        IntPtr   ptr = mf.GetHenhmetafile();
                        Debug.Assert(ptr != IntPtr.Zero, "Failed to get pointer to image.");
                        uint size = GetMetaFileBitsEx(ptr, 0, null);
                        bits = new byte[size];
                        uint numBits = GetMetaFileBitsEx(ptr, size, bits);
                        mf.Dispose();
                        Debug.Assert(size == numBits, "Improper serialization of metafile!");
                    }
                    else if (this.m_image.RawFormat.Guid == ImageFormat.Png.Guid)
                    {
                        info.AddValue("type", "png");
                        System.IO.MemoryStream ms = new System.IO.MemoryStream(100000);
                        this.m_image.Save(ms, ImageFormat.Png);
                        bits = ms.ToArray();
                    }
                    else if (this.m_image.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                    {
                        info.AddValue("type", "Jpeg");
                        System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        long[] quality            = new long[1];
                        quality[0] = 100;
                        System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                        System.Drawing.Imaging.EncoderParameter  encoderParam  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                        encoderParams.Param[0] = encoderParam;
                        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo   jpegICI  = null;
                        for (int x = 0; x < arrayICI.Length; x++)
                        {
                            if (arrayICI[x].FormatDescription.Equals("JPEG"))
                            {
                                jpegICI = arrayICI[x];
                                break;
                            }
                        }
                        if (jpegICI != null)
                        {
                            this.m_image.Save(ms, jpegICI, encoderParams);
                        }

                        bits = ms.ToArray();
                    }
                    else
                    {
                        info.AddValue("type", "png");
                        System.IO.MemoryStream ms = new System.IO.MemoryStream(100000);
                        this.m_image.Save(ms, ImageFormat.Png);
                        bits = ms.ToArray();
                    }
                }
                info.AddValue("image", bits);
            }
        /// <summary>
        /// Renders a document as enhanced metafile. The metafile is rendered into a stream. You can create a metafile object afterwards from that stream.
        /// </summary>
        /// <param name="renderingProc">Procedure for rendering the document.
        /// The argument is a graphics context, which is set to GraphicsUnits equal to Points.
        /// The drawing must be inside of the boundaries of docSize.X and docSize.Y.
        /// </param>
        /// <param name="stream">Destination stream. The metafile is rendered into this stream. The stream has to be writeable and seekable. At return, the position of the stream is set to 0, thus the stream is ready to be used to create a metafile object from it.</param>
        /// <param name="docSize">Size of the document in points (1/72 inch)</param>
        /// <param name="sourceDpiResolution">The resolution in dpi of the source. This parameter is used only if creating the reference graphics context from the current printer fails. In this case, a context from a bitmap with the provided resolution is created.</param>
        /// <param name="outputScalingFactor">Output scaling factor. If less than 1, the image will appear smaller than originally, if greater than 1, the image will appear larger than originally.</param>
        /// <param name="pixelFormat">Optional: Only used if the graphics context can not be created from a printer document. Pixel format of the bitmap that is used in this case to construct the graphics context.</param>
        /// <returns>The rendered enhanced metafile (vector format).</returns>
        /// <remarks>
        /// <para>
        /// I found no other way to realize different dpi resolutions, independently of screen or printer device contexts, as to patch the resulting metafile stream with
        /// informations about an 'artifical' device, which has exactly the resolution that is neccessary. By careful choice of the size of this artifical device one can
        /// avoid rounding errors concerning resolution and size.
        /// It happens that some programs (for instance MS Word 2010 when saving as PDF document) mess up the size of the metafile graphics, if the graphics was created with a PageUnit
        /// (of the graphics context) other than PIXELS.
        /// Thus I now always use PIXEL as PageUnit and scale the graphics context accordingly.
        /// </para>
        /// <para>
        /// Another problem, which is actually without solution, is that e.g. MS Office will not show polylines with more than 8125 points. These polylines are included in the metafile,
        /// but MS Office seems to ignore them. On the other hand, CorelDraw X5 can show these polylines correctly.
        /// This problem might be related to the EmfPlus format, because MS Office will show these polylines if the EmfOnly format is used. But EmfOnly can not handle transparencies, thus
        /// it is not really a choice.
        /// </para>
        /// </remarks>
        public static (int pixelsX, int pixelsY) RenderAsEnhancedMetafileToStream(Action <Graphics> renderingProc, System.IO.Stream stream, PointD2D docSize, double sourceDpiResolution, double outputScalingFactor, PixelFormat pixelFormat = PixelFormat.Format32bppArgb)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (!stream.CanWrite)
            {
                throw new ArgumentException("stream is not writeable");
            }
            if (!stream.CanSeek)
            {
                throw new ArgumentException("stream is not seekable");
            }
            stream.SetLength(0);

            var scaledDocSize = docSize * outputScalingFactor;

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

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

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

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

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

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

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

            Metafile metafile;

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

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

                    grfxReference.ReleaseHdc();
                }
            }

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

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

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

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

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

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

            stream.Position = 0x04;
            var buf4 = new byte[4];

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

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

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

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

            stream.Flush();

            stream.Position = 0;

            metafile.Dispose(); // we can safely dispose this metafile, because stream and metafile are independent of each other, and only the stream is patched

            return(devicePixelsX, devicePixelsY);
        }
示例#9
0
    private void saveEmf(String path)
    {
        FileStream fs = new FileStream(path,FileMode.Create );
        Graphics g = CreateGraphics();
        IntPtr hDC = g.GetHdc();
        Metafile m = new Metafile( fs, hDC );

        g.ReleaseHdc( hDC );
        g.Dispose();

        Graphics vg= Graphics.FromImage(m);
        Node.drawComponent(currentSymbol, vg);
        vg.Dispose();
        m.Dispose();
        fs.Close();
    }
            public virtual void OnPrintCtrl(object sender, PrintPageEventArgs e)
            {
                if (_ctrl == null || _printHandler._drawFunc == null)
                {
                    return;
                }

                RectangleF rf = _printRect;

                // if the print rectangle is empty, adjust it to margin limit
                if (rf.Width == 0)
                {
                    rf.Width = e.MarginBounds.Width;
                }
                if (rf.Height == 0)
                {
                    rf.Height = e.MarginBounds.Height;
                }

                float wRatio = 1f, hRatio = 1f;

                Matrix m = new Matrix();

                rf.Offset(e.MarginBounds.Location);
                m.Translate(rf.X, rf.Y);        // always translate, as ctrl is zero upper left

                switch (_printScale)
                {
                case PrintScale.None:
                    // None means print/draw ctrl in specified space
                    rf.Size = _ctrlSize;
                    break;

                case PrintScale.Fit:
                    // Fit means draw the chart assuming it should fill the specified space.
                    // No sizing transforms are used.  Does not preserve aspect ratio.
                    _resizeControl = true;
                    break;

                case PrintScale.Stretch:
                    // Stretch means draw the ctrl so it contains
                    // the same view, but shrink or stretch so it fills
                    // the specified region.  This does not maintain aspect ratio.
                    wRatio = rf.Width / _ctrlSize.Width;
                    hRatio = rf.Height / _ctrlSize.Height;
                    break;

                default:                            // aka Zoom
                    // Zoom means draw the ctrl, preserving the
                    // aspect ratio, but scale it so that printed image fits
                    // entirely in the specified region.  Either the Width
                    // or the Height will be filled.
                    wRatio = rf.Width / _ctrlSize.Width;
                    hRatio = rf.Height / _ctrlSize.Height;
                    if (wRatio < hRatio)
                    {
                        hRatio = wRatio;
                    }
                    else
                    {
                        wRatio = hRatio;
                    }
                    break;
                }

                if (wRatio != 1f || hRatio != 1f)
                {
                    m.Scale(wRatio, hRatio);
                }

                Rectangle r = new Rectangle(Point.Empty, Size.Round(_resizeControl ? rf.Size : _ctrlSize));

                Graphics      g     = e.Graphics;
                GraphicsState gsave = g.Save();

                g.MultiplyTransform(m, MatrixOrder.Append);

                Graphics gbits        = null;
                Bitmap   bitMapBuffer = null;

                if (_bitmap)
                {
                    gbits        = g;
                    bitMapBuffer = new Bitmap(r.Width, r.Height);
                    g            = Graphics.FromImage(bitMapBuffer);
                }

                bool inPreview = sender is PrintDocument && ((PrintDocument)sender).PrintController.IsPreview;

                if (_printHandler._ia_grayscale != null && (e.PageSettings.Color || inPreview))
                {
                    Graphics gc  = _ctrl.CreateGraphics();
                    IntPtr   hdc = gc.GetHdc();
                    Metafile mf  = new Metafile(hdc, r, MetafileFrameUnit.Pixel, EmfType.EmfPlusDual);
                    if (mf != null)
                    {
                        Graphics gmf = Graphics.FromImage(mf);
                        if (gmf != null)
                        {
                            _printHandler._drawFunc(gmf, r, _resizeControl);
                            gmf.Dispose();
                        }
                        g.DrawImage(mf, r, r.X, r.Y, r.Width, r.Height, GraphicsUnit.Pixel,
                                    _printHandler._ia_grayscale);

                        mf.Dispose();
                        mf = null;
                    }
                    if (gc != null)
                    {
                        gc.Dispose();
                    }
                }
                else
                {
                    _printHandler._drawFunc(g, r, _resizeControl);
                }

                if (_bitmap)
                {
                    g.Flush();
                    g.Dispose();

                    g = gbits;
                    g.DrawImage(bitMapBuffer, r);
                    bitMapBuffer.Dispose();
                    bitMapBuffer = null;
                }
                m.Dispose();
                g.Restore(gsave);

                e.HasMorePages = false;

                // Since values may have been recalculated in the ctrl
                // during the draw, but based on the printer graphics
                // object, repaint the ctrl on the screen so the internal
                // variables are recalculated for the screen.
                // this will need to be address more completely.
                _ctrl.Invalidate();
            }
示例#11
0
        // }}}

        //}}}
        private static string getRtfImage(Image image, Control control)// {{{
        {
            // Used to store the enhanced metafile
            MemoryStream stream = null;

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

            // The enhanced metafile
            Metafile metaFile = null;

            try {
                var sb = new StringBuilder();
                stream = new MemoryStream();

                // Get a graphics context from the RichTextBox
                using (graphics = control.CreateGraphics())
                {
                    // Get the device context from the graphics context
                    IntPtr 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))
                {
                    // Draw the image on the Enhanced Metafile
                    graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
                }

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

                // A call to EmfToWmfBits with a null buffer return the size of the
                // buffer need to store the WMF bits.  Use this to get the buffer
                // size.
                uint bufferSize = NativeMethods.GdipEmfToWmfBits(hEmf, 0, null, 8, NativeMethods.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.
                uint _convertedSize = NativeMethods.GdipEmfToWmfBits(hEmf, bufferSize, buffer, 8, NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                // Append the bits to the RTF string
                foreach (byte t in buffer)
                {
                    sb.Append(String.Format("{0:X2}", t));
                }
                return(sb.ToString());
            }
            finally {
                if (metaFile != null)
                {
                    metaFile.Dispose();
                }
            }
        }
示例#12
0
        public byte[] getWMETA8Data(Image _image)
        {
            Graphics g = Graphics.FromImage(_image);

            this.GraphObj = g;
            // Used to store the enhanced metafile
            MemoryStream _stream = null;
            // Used to create the metafile and draw the image
            Graphics _graphics = null;
            // The enhanced metafile
            Metafile _metaFile = null;
            // Handle to the device context used to create the metafile
            IntPtr _hdc;

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

                // Get a graphics context from the RichTextBox
                using (_graphics = this.GraphObj)
                {
                    // Get the device context from the graphics context
                    _hdc = _graphics.GetHdc();
                    // Create a new Enhanced Metafile from the device context
                    _metaFile = new Metafile(_stream, _hdc);
                    // Release the device context
                    _graphics.ReleaseHdc(_hdc);
                }

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

                // Get the handle of the Enhanced Metafile
                IntPtr _hEmf = _metaFile.GetHenhmetafile();
                // A call to EmfToWmfBits with a null buffer return the size of the
                // buffer need to store the WMF bits.  Use this to get the buffer
                // size.
                uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC,
                                                    EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
                // Create an array to hold the bits
                byte[] _buffer = new byte[_bufferSize];
                // A call to EmfToWmfBits with a valid buffer copies the bits into the
                // buffer an returns the number of bits in the WMF.
                uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC,
                                                       EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                return(_buffer);
            }
            finally
            {
                if (_graphics != null)
                {
                    _graphics.Dispose();
                }
                if (_metaFile != null)
                {
                    _metaFile.Dispose();
                }
                if (_stream != null)
                {
                    _stream.Close();
                }
            }
        }
示例#13
0
        private void Exp2PPT(string pFileSpec)
        {
            PowerPoint.Application application = new ApplicationClass();
            application.Visible     = MsoTriState.msoTrue;
            application.WindowState = PpWindowState.ppWindowMinimized;
            Presentation presentation = application.Presentations.Add(MsoTriState.msoTrue);
            float        slideWidth   = application.ActivePresentation.PageSetup.SlideWidth;
            float        slideHeight  = application.ActivePresentation.PageSetup.SlideHeight;
            string       text         = System.Windows.Forms.Application.StartupPath + "\\\\temp.emf";

            this.m_DrawingSymbols.Clear();
            this.ExpBanDo2EMF(text);
            int arg_75_0 = 1;
            int count    = this.myPages.Count;

            checked
            {
                for (int i = arg_75_0; i <= count; i++)
                {
                    Slide            slide = presentation.Slides.Add(i, PpSlideLayout.ppLayoutBlank);
                    PowerPoint.Shape shape = slide.Shapes.AddPicture(text, MsoTriState.msoFalse, MsoTriState.msoCTrue, 0f, 0f, slideWidth, slideHeight);
                    float            num   = slideWidth / this.AxMap1.MapScreenWidth;
                    float            num2  = slideHeight / this.AxMap1.MapScreenHeight;
                    this.ShowPage(i - 1);
                    RectangleF rect = unchecked (new RectangleF(-20f, -20f, this.AxMap1.MapScreenWidth + 40f, this.AxMap1.MapScreenHeight + 40f));
                    int        num3 = 0;
                    try
                    {
                        IEnumerator enumerator = this.m_DrawingSymbols.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            CSymbol cSymbol = (CSymbol)enumerator.Current;
                            if (cSymbol.HitTest(this.AxMap1, rect))
                            {
                                string[] array = text.Split(new char[]
                                {
                                    '.'
                                });
                                num3++;
                                string text2 = string.Concat(new string[]
                                {
                                    array[0],
                                    i.ToString("00"),
                                    num3.ToString("000"),
                                    ".",
                                    array[1]
                                });
                                Graphics graphics  = this.AxMap1.CreateGraphics();
                                IntPtr   hdc       = graphics.GetHdc();
                                Metafile metafile  = new Metafile(text2, hdc);
                                Graphics graphics2 = Graphics.FromImage(metafile);
                                cSymbol.Draw(this.AxMap1, graphics2);
                                graphics2.Dispose();
                                metafile.Dispose();
                                Metafile     metafile2    = new Metafile(text2);
                                Image        arg_202_0    = metafile2;
                                GraphicsUnit graphicsUnit = GraphicsUnit.Pixel;
                                RectangleF   bounds       = arg_202_0.GetBounds(ref graphicsUnit);
                                metafile2.Dispose();
                                unchecked
                                {
                                    float            increment  = bounds.Left * num;
                                    float            increment2 = bounds.Top * num2;
                                    float            width      = bounds.Width * num;
                                    float            height     = bounds.Height * num2;
                                    PowerPoint.Shape shape2     = slide.Shapes.AddPicture(text2, MsoTriState.msoFalse, MsoTriState.msoCTrue, 0f, 0f, width, height);
                                    PowerPoint.Shape shape3     = shape2;
                                    shape3.IncrementLeft(increment);
                                    shape3.IncrementTop(increment2);
                                }
                            }
                        }
                    }
                    finally
                    {
                        IEnumerator enumerator;
                        if (enumerator is IDisposable)
                        {
                            (enumerator as IDisposable).Dispose();
                        }
                    }
                }
                presentation.SaveAs(pFileSpec, PpSaveAsFileType.ppSaveAsPresentation, MsoTriState.msoTriStateMixed);
                presentation.Saved = MsoTriState.msoTrue;
                presentation.Close();
                presentation = null;
                application.Quit();
                application = null;
                GC.Collect();
                Interaction.MsgBox("Xuat ra PPT xong.", MsgBoxStyle.OkOnly, null);
            }
        }
示例#14
0
        // Specifies the flags/options for the unmanaged call to the GDI+ method
        // Metafile.EmfToWmfBits().


        /// <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)
        // ReSharper restore UnusedMember.Local
        {
            // Ensures that the metafile maintains a 1:1 aspect ratio
            //const int MM_ISOTROPIC = 7;

            // Allows the x-coordinates and y-coordinates of the metafile to be adjusted
            // independently
            const int mmAnisotropic = 8;

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

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

            // The enhanced metafile
            Metafile metaFile = null;

            // Handle to the device context used to create the metafile

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

                // Get a graphics context from the RichTextBox
                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))
                {
                    // Draw the image on the Enhanced 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 = 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.
                GdipEmfToWmfBits(hEmf, bufferSize, buffer, mmAnisotropic, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                // Append the bits to the RTF string
                foreach (byte t in buffer)
                {
                    rtf.Append(String.Format("{0:X2}", t));
                }

                return(rtf.ToString());
            }
            finally
            {
                if (graphics != null)
                {
                    graphics.Dispose();
                }

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

                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
 /// <summary>
 /// Unload the loaded file.
 /// </summary>
 public void UnloadMetafile()
 {
     _loadedMetafile.Dispose();
     _loadedMetafile = null;
 }
示例#16
0
        private string convertCoordinatesToHex()
        {
            string signatureHex = string.Empty;

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

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

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

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

                    IntPtr hEmf = signatureMetaFile.GetHenhmetafile();

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

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

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

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

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

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

            return(signatureHex);
        }
示例#17
0
        private static void SaveAsImage(IPrintable document, string path,
                                        ImageFormat format, bool selectedOnly, bool transparent)
        {
            const int Margin = 20;

            RectangleF areaF = document.GetPrintingArea(selectedOnly);

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

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

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

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

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

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

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

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

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

                        try
                        {
                            image.Save(path, format);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(
                                string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
                                              Strings.ErrorsReason, ex.Message),
                                Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
            }
        }
示例#18
0
        /// ///////////////////////////////////////
        protected override CResultAErreur MySerialize(C2iSerializer serializer)
        {
            int            nVersion = GetNumVersion();
            CResultAErreur result   = serializer.TraiteVersion(ref nVersion);

            if (!result)
            {
                return(result);
            }

            bool bHasImage = m_metafileDefault != null;

            serializer.TraiteBool(ref bHasImage);
            if (bHasImage)
            {
                switch (serializer.Mode)
                {
                case ModeSerialisation.Lecture:
                    Byte[] bt = null;
                    serializer.TraiteByteArray(ref bt);
                    if (m_metafileDefault != null)
                    {
                        m_metafileDefault.Dispose();
                    }
                    m_metafileDefault = null;
                    MemoryStream stream = new MemoryStream(bt);
                    try
                    {
                        Metafile meta = (Metafile)Metafile.FromStream(stream);
                        m_metafileDefault = meta;
                    }
                    catch
                    {
                        m_metafileDefault = null;
                    }
                    stream.Close();
                    break;

                case ModeSerialisation.Ecriture:
                    try
                    {
                        int    nHandle  = m_metafileDefault.GetHenhmetafile().ToInt32();
                        int    nBufSize = GetEnhMetaFileBits(nHandle, 0, null);
                        byte[] buffer   = new byte[nBufSize];
                        if (GetEnhMetaFileBits(nHandle, nBufSize, buffer) > 0)
                        {
                            serializer.TraiteByteArray(ref buffer);
                        }
                        else
                        {
                            buffer = new byte[0];
                            serializer.TraiteByteArray(ref buffer);
                        }
                    }
                    catch (Exception e)
                    {
                        string strVal = e.ToString();
                    }
                    break;
                }
            }

            return(result);
        }
示例#19
0
        public bool PrintReport(string printerName, string reportPath, int id, int printID, short paperSize, short copiesCount)
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            this.RenderedReport = this.RenderReport(reportPath, id, paperSize);
            if (null == this.RenderedReport)
            {
                return(false);
            }
            try
            {
                // Wait for the report to completely render.
                if (m_numberOfPages < 1)
                {
                    return(false);
                }
                PrintDocument pd = new PrintDocument();
                rs.ItemNamespaceHeaderValue = new RS.ItemNamespaceHeader();
                rs.ItemNamespaceHeaderValue.ItemNamespace = RS.ItemNamespaceEnum.PathBased;
                RS.Property[] properties = rs.GetProperties(reportPath, null);
                pheight = pd.DefaultPageSettings.PaperSize.Height;
                pwidth  = pd.DefaultPageSettings.PaperSize.Width;
                double theight = 0;
                double twidth  = 0;
                ma = new Margins(0, 0, 0, 0);
                bool size = false;
                foreach (RS.Property property in properties)
                {
                    switch (property.Name.ToLower())
                    {
                    case "pageheight":
                        theight = (double.Parse(property.Value) / 0.254);
                        pheight = (int)System.Math.Round(theight);
                        size    = true;
                        break;

                    case "pagewidth":
                        twidth = double.Parse(property.Value) / 0.254;
                        pwidth = (int)System.Math.Round(twidth);
                        size   = true;
                        break;

                    case "topmargin":
                        ma.Top = (int)(double.Parse(property.Value) / 0.254);
                        break;

                    case "bottommargin":
                        ma.Bottom = (int)(double.Parse(property.Value) / 0.254);
                        break;

                    case "rightmargin":
                        ma.Right = (int)(double.Parse(property.Value) / 0.254);
                        break;

                    case "leftmargin":
                        ma.Left = (int)(double.Parse(property.Value) / 0.254);
                        break;
                    }
                    //Console.WriteLine(property.Name + ": " + property.Value);
                }
                Console.WriteLine("{0}: paper change", DateTime.Now.ToString("HH:mm:ss fff"));

                if (!size)
                {
                    if (this.m_currentPageStream != null)
                    {
                        this.m_currentPageStream.Close();
                        this.m_currentPageStream = null;
                    }
                    m_currentPageStream = new MemoryStream(this.m_renderedReport[0]);
                    // Set its postion to start.
                    m_currentPageStream.Position = 0;
                    // Initialize the metafile
                    if (null != m_metafile)
                    {
                        m_metafile.Dispose();
                        m_metafile = null;
                    }
                    // Load the metafile image for this page
                    m_metafile = new Metafile((Stream)m_currentPageStream);
                    pheight    = m_metafile.Height;
                    pwidth     = m_metafile.Width;
                }

                landscape = false;
                if (pwidth > pheight && !pd.DefaultPageSettings.Landscape)
                {
                    landscape = true;
                }

                PrinterSettings printerSettings = new PrinterSettings();
                printerSettings.MaximumPage = m_numberOfPages;
                printerSettings.MinimumPage = 1;
                printerSettings.PrintRange  = PrintRange.SomePages;
                printerSettings.FromPage    = 1;
                printerSettings.ToPage      = m_numberOfPages;
                printerSettings.Copies      = copiesCount;
                m_currentPrintingPage       = 1;
                m_lastPrintingPage          = m_numberOfPages;
                printerSettings.PrinterName = printerName;
                pd.PrinterSettings          = printerSettings;

                if (landscape)
                {
                    if (pd.DefaultPageSettings.PaperSize.Width != pheight || pd.DefaultPageSettings.PaperSize.Height != pwidth)
                    {
                        PaperSize papers = new PaperSize(reportPath, pheight, pwidth);
                        papers.PaperName = "ReportPrintingLandscape";
                        pd.DefaultPageSettings.PaperSize = papers;
                    }
                    pd.DefaultPageSettings.Landscape = true;
                }
                else
                {
                    if (pd.DefaultPageSettings.PaperSize.Width != pwidth || pd.DefaultPageSettings.PaperSize.Height != pheight)
                    {
                        PaperSize papers = new PaperSize(reportPath, pwidth, pheight);
                        papers.PaperName = "ReportPrinting";
                        pd.DefaultPageSettings.PaperSize = papers;
                    }
                    pd.DefaultPageSettings.Landscape = false;
                }

                pd.OriginAtMargins             = true;
                pd.DefaultPageSettings.Margins = ma;
                pd.PrintPage += pd_PrintPage;

                pd.DocumentName = "?docviewprint=" + id.ToString() + "&docviewtypeid=" + printID.ToString() + "&id=" + id.ToString();
                pd.EndPrint    += pd_EndPrint;

                // Print report
                Console.WriteLine("{0}: Printing report...", DateTime.Now.ToString("HH:mm:ss fff"));
                if (pd.PrinterSettings.IsValid)
                {
                    pd.Print();
                }
                else
                {
                    Console.WriteLine("{0}: Encorrect parameters", DateTime.Now.ToString("HH:mm:ss fff"));
                }
                pd.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Clean up goes here.
            }
            return(true);
        }
示例#20
0
        private void DrawRich(FRPaintEventArgs e)
        {
            // avoid GDI+ errors
            if (Width < Padding.Horizontal + 1 || Height < Padding.Vertical + 1)
            {
                return;
            }

            // draw to emf because we need to zoom the image
            Metafile emf = null;

            try
            {
                // create metafile
                Graphics measureGraphics = Report == null ? e.Graphics : Report.PrintSettings.MeasureGraphics;
                if (measureGraphics == null)
                {
                    measureGraphics = e.Graphics;
                }
                // lock because of multi-thread html export issues
                lock (measureGraphics)
                {
                    float  scaleX = measureGraphics.DpiX / 96f;
                    float  scaleY = measureGraphics.DpiY / 96f;
                    IntPtr hdc    = measureGraphics.GetHdc();
                    emf = new Metafile(hdc,
                                       new RectangleF(0, 0, (Width - Padding.Horizontal) * scaleX, (Height - Padding.Vertical) * scaleY),
                                       MetafileFrameUnit.Pixel);
                    measureGraphics.ReleaseHdc(hdc);

                    // create metafile canvas and draw on it
                    using (Graphics g = Graphics.FromImage(emf))
                    {
                        Color color = Color.White;
                        if (Fill is SolidFill)
                        {
                            color = (Fill as SolidFill).Color;
                        }
                        if (color == Color.Transparent)
                        {
                            color = Color.White;
                        }

                        FRichTextBox.BackColor = color;
                        int textStart  = ActualTextStart;
                        int textLength = ActualTextLength != 0 ? ActualTextLength : FRichTextBox.TextLength - textStart;
                        FRichTextBox.FormatRange(g, measureGraphics,
                                                 new RectangleF(0, 0, Width - Padding.Horizontal, Height - Padding.Vertical),
                                                 textStart, textStart + textLength, false);
                    }

                    // draw the resulting metafile on a screen/printer
                    e.Graphics.DrawImage(emf,
                                         new RectangleF((AbsLeft + Padding.Left) * e.ScaleX,
                                                        (AbsTop + Padding.Top) * e.ScaleY,
                                                        (Width - Padding.Horizontal) * e.ScaleX,
                                                        (Height - Padding.Vertical) * e.ScaleY));
                }
            }
            finally
            {
                if (emf != null)
                {
                    emf.Dispose();
                }
            }
        }
示例#21
0
        private static byte[] GetWmfBytes(Bitmap bitmap)
        {
            MemoryStream stream   = null;
            Graphics     graphics = null;
            Metafile     metaFile = null;
            IntPtr       hEmf     = IntPtr.Zero;

            byte[] data = null;

            try
            {
                using (stream = new MemoryStream())
                {
                    using (graphics = Graphics.FromImage(bitmap))
                    {
                        // Get the device context from the graphics context
                        IntPtr 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))
                    {
                        // Draw the image on the Enhanced Metafile
                        graphics.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                    }

                    using (metaFile)
                    {
                        hEmf = metaFile.GetHenhmetafile();

                        uint bufferSize = GdipEmfToWmfBits(hEmf, 0, null, 8, EmfToWmfBitsFlags.Default);

                        data = new byte[bufferSize];

                        GdipEmfToWmfBits(hEmf, bufferSize, data, 8, EmfToWmfBitsFlags.Default);
                    }
                }
            }
            catch
            {
                data = null;
            }
            finally
            {
                if (hEmf != IntPtr.Zero)
                {
                    DeleteEnhMetaFile(hEmf);
                }

                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                }

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

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

            return(data);
        }
示例#22
0
        /// <summary>
        /// Wraps the image in an Enhanced Metafile by drawing the image onto the
        /// graphics context, then converts the Enhanced Metafile to a Windows
        /// Metafile, and finally appends the bits of the Windows Metafile in HEX
        /// to a string and returns the string.
        /// </summary>
        /// <param name="image"></param>
        /// <returns>
        /// A string containing the bits of a Windows Metafile in HEX
        /// </returns>
        public static string GetRtfImage(Image image)
        {
            StringBuilder rtf = null;

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

            // The enhanced metafile
            Metafile metaFile = null;

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

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

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

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

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

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

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

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

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

                return(rtf.ToString());
            }
            finally
            {
                if (metaFile != null)
                {
                    metaFile.Dispose();
                }
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
示例#23
0
            /// <summary>
            /// Wraps the image in an Enhanced Metafile by drawing the image onto the
            /// graphics context, then converts the Enhanced Metafile to a Windows
            /// Metafile, and finally appends the bits of the Windows Metafile in HEX
            /// to a string and returns the string.
            /// </summary>
            /// <param name="_image"></param>
            /// <returns>
            /// A string containing the bits of a Windows Metafile in HEX
            /// </returns>
            private void WriteRtfImage(Image _image)
            {
                // Used to store the enhanced metafile
                MemoryStream _stream = null;

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

                // The enhanced metafile
                Metafile _metaFile = null;

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

                try
                {
                    using (_stream = new MemoryStream())
                    {
                        // Get a graphics context from the RichTextBox
                        using (_graphics = Graphics.FromImage(_image))
                        {
                            // Get the device context from the graphics context
                            _hdc = _graphics.GetHdc();

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

                            // Release the device context
                            _graphics.ReleaseHdc(_hdc);
                        }

                        // Get a graphics context from the Enhanced Metafile
                        using (_graphics = Graphics.FromImage(_metaFile))
                        {
                            // Draw the image on the Enhanced Metafile
                            _graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
                        }
                        byte[] _buffer = null;
                        using (_metaFile)
                        {
                            // Get the handle of the Enhanced Metafile
                            IntPtr _hEmf = _metaFile.GetHenhmetafile();

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

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

                            // A call to EmfToWmfBits with a valid buffer copies the bits into the
                            // buffer an returns the number of bits in the WMF.
                            uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
                        }
                        // Append the bits to the RTF string
                        for (int i = 0; i < _buffer.Length; ++i)
                        {
                            this.sb.Append(String.Format("{0:X2}", _buffer[i]));
                        }
                        if (_stream != null)
                        {
                            _stream.Flush();
                            _stream.Close();
                        }
                    }
                }
                finally
                {
                    if (_graphics != null)
                    {
                        _graphics.Dispose();
                    }
                    if (_metaFile != null)
                    {
                        _metaFile.Dispose();
                    }
                    if (_stream != null)
                    {
                        _stream.Flush();
                        _stream.Close();
                    }
                }
            }
示例#24
0
    /// <summary>
    /// Wraps the image in an Enhanced Metafile by drawing the image onto the
    /// graphics context, then converts the Enhanced Metafile to a Windows
    /// Metafile, and finally appends the bits of the Windows Metafile in HEX
    /// to a string and returns the string.
    /// </summary>
    /// <param name="_image"></param>
    /// <returns>
    /// A string containing the bits of a Windows Metafile in HEX
    /// </returns>
    private string GetRtfImage(Image _image)
    {
        StringBuilder _rtf = null;

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

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

        // The enhanced metafile
        Metafile _metaFile = null;

        // Handle to the device context used to create the metafile
        IntPtr _hdc = default(IntPtr);

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

            // Get a graphics context from the RichTextBox
            using (var __graphics = this.CreateGraphics())
            {

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

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

                // Release the device context
                __graphics.ReleaseHdc(_hdc);
            }

            // Get a graphics context from the Enhanced Metafile
            using (var __graphics = Graphics.FromImage(_metaFile))
            {

                // Draw the image on the Enhanced Metafile

                __graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
            }

            // Get the handle of the Enhanced Metafile
            IntPtr _hEmf = _metaFile.GetHenhmetafile();

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

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

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

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

            return _rtf.ToString();
        }
        finally
        {
            if (_graphics != null)
            {
                _graphics.Dispose();
            }
            if (_metaFile != null)
            {
                _metaFile.Dispose();
            }
            if (_stream != null)
            {
                _stream.Close();
            }
        }
    }
示例#25
0
        /// <summary>
        /// Wraps the image in an Enhanced Metafile by drawing the image onto the
        /// graphics context, then converts the Enhanced Metafile to a Windows
        /// Metafile, and finally appends the bits of the Windows Metafile in HEX
        /// to a string and returns the string.
        /// </summary>
        /// <param name="_image"></param>
        /// <returns>
        /// A string containing the bits of a Windows Metafile in HEX
        /// </returns>
        private string GetRtfImage(Image _image)
        {
            // Ensures that the metafile maintains a 1:1 aspect ratio
            //const int MM_ISOTROPIC = 7;

            // Allows the x-coordinates and y-coordinates of the metafile to be adjusted
            // independently
            const int MM_ANISOTROPIC = 8;



            StringBuilder _rtf = null;

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

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

            // The enhanced metafile
            Metafile _metaFile = null;

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

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

                // Get a graphics context from the RichTextBox
                using (_graphics = System.Drawing.Graphics.FromHwnd(new IntPtr(0)))
                {
                    // Get the device context from the graphics context
                    _hdc = _graphics.GetHdc();

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

                    // Release the device context
                    _graphics.ReleaseHdc(_hdc);
                }

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

                // Get the handle of the Enhanced Metafile
                IntPtr _hEmf = _metaFile.GetHenhmetafile();

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

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

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

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

                return(_rtf.ToString());
            }
            finally
            {
                if (_graphics != null)
                {
                    _graphics.Dispose();
                }
                if (_metaFile != null)
                {
                    _metaFile.Dispose();
                }
                if (_stream != null)
                {
                    _stream.Close();
                }
            }
        }
示例#26
0
        public static IEnumerable <IEditor> AddMetafile(IEditor editor, Point location, Metafile meta, bool useCommandExecutor, bool arrange)
        {
            using (editor.Figure.DirtManager.BeginDirty())
                using (var mem = new MemoryStream()) {
                    if (useCommandExecutor && arrange)
                    {
                        editor.Site.CommandExecutor.BeginChain();
                    }

                    var existingEditorBounds = default(Rectangle[]);
                    if (arrange)
                    {
                        existingEditorBounds = editor.Children.Select(e => e.Figure.Bounds).ToArray();
                    }

                    using (var bmp = new Bitmap(1, 1))
                        using (var bmpg = Graphics.FromImage(bmp)) {
                            var hdc = bmpg.GetHdc();
                            using (var mf = new Metafile(mem, hdc)) {
                                bmpg.ReleaseHdc(hdc);
                                using (var g = Graphics.FromImage(mf)) {
                                    g.DrawImage(meta, Point.Empty);
                                }
                            }
                        }

                    var imgFilePath = GetNewImageFilePath();
                    File.WriteAllBytes(imgFilePath, mem.GetBuffer());
                    var desc = new FileImageDescription(Path.GetFileName(imgFilePath));

                    var req = new CreateNodeRequest();
                    req.ModelFactory = new DelegatingModelFactory <MemoImage>(
                        () => {
                        var ret   = MemoFactory.CreateImage();
                        ret.Image = desc;
                        return(ret);
                    }
                        );
                    req.Bounds           = new Rectangle(location, meta.Size);
                    req.AdjustSizeToGrid = false;

                    var cmd = editor.GetCommand(req) as CreateNodeCommand;
                    if (useCommandExecutor)
                    {
                        editor.Site.CommandExecutor.Execute(cmd);
                    }
                    else
                    {
                        cmd.Execute();
                    }

                    meta.Dispose();


                    if (arrange)
                    {
                        var newLoc = RectUtil.GetPreferredLocation(
                            cmd.CreatedEditor.Figure.Bounds,
                            existingEditorBounds,
                            editor.Root.Figure.Right,
                            MemopadConsts.DefaultCaretPosition.X,
                            MemopadConsts.DefaultCaretPosition.Y
                            );
                        var move = new ChangeBoundsCommand(
                            cmd.CreatedEditor,
                            (Size)newLoc - (Size)cmd.CreatedEditor.Figure.Location,
                            Size.Empty,
                            Directions.None,
                            new [] { cmd.CreatedEditor }
                            );
                        if (useCommandExecutor)
                        {
                            editor.Site.CommandExecutor.Execute(move);
                        }
                        else
                        {
                            move.Execute();
                        }
                        if (useCommandExecutor)
                        {
                            editor.Site.CommandExecutor.EndChain();
                        }
                    }

                    return(new[] { cmd.CreatedEditor });
                }
        }