Ejemplo n.º 1
0
        /// <summary>
        /// 创建指定页的图元数据
        /// </summary>
        /// <param name="page">页面对象</param>
        /// <param name="DrawMargin">是否绘制边距线</param>
        /// <returns>包含图元数据的字节数组</returns>
        public byte[] GetMetafile(PrintPage page, bool DrawMargin)
        {
            XPageSettings pageSettings = page.PageSettings;

            System.Drawing.Imaging.Metafile meta = null;
            using (DeviceContexts dc = DeviceContexts.CreateCompatibleDC(IntPtr.Zero))
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                meta = new System.Drawing.Imaging.Metafile(
                    stream,
                    dc.HDC,
                    new System.Drawing.Rectangle(
                        0,
                        0,
                        (int)page.PageSettings.ViewPaperWidth,
                        (int)page.PageSettings.ViewPaperHeight),
                    //System.Drawing.Imaging.MetafileFrameUnit.Document );
                    PrintUtil.ConvertUnit(myDocument.DocumentGraphicsUnit));
                using (System.Drawing.Graphics g2 = System.Drawing.Graphics.FromImage(meta))
                {
                    if (intBackColor.A != 0)
                    {
                        g2.Clear(this.intBackColor);
                    }

                    g2.PageUnit = myDocument.DocumentGraphicsUnit;

                    PageFrameDrawer drawer = new PageFrameDrawer();
                    drawer.DrawMargin   = DrawMargin;
                    drawer.BackColor    = System.Drawing.Color.Transparent;
                    drawer.BorderColor  = this.intBorderColor;
                    drawer.BorderWidth  = 1;
                    drawer.LeftMargin   = (int)page.ViewLeftMargin;
                    drawer.TopMargin    = (int)page.ViewTopMargin;
                    drawer.RightMargin  = (int)page.ViewRightMargin;
                    drawer.BottomMargin = (int)page.ViewBottomMargin;

                    drawer.Bounds = new System.Drawing.Rectangle(
                        0,
                        0,
                        (int)pageSettings.ViewPaperWidth,
                        (int)pageSettings.ViewPaperHeight);
                    drawer.BackgroundImage = this.PageBackgroundImage;
                    g2.ScaleTransform(this.XZoomRate, this.YZoomRate);
                    drawer.DrawPageFrame(g2, System.Drawing.Rectangle.Empty);

                    DrawPage(page, g2, page.Bounds, true);
                }
                meta.Dispose();
                dc.Dispose();
                return(stream.ToArray());
            }
        }
Ejemplo n.º 2
0
        public static void ImageToWMF(string imgFileName, string wmfFileName)
        {
            Image     image    = Image.FromFile(imgFileName);
            Bitmap    bmp      = new Bitmap(image.Width, image.Height);
            Graphics  graphics = Graphics.FromImage(bmp);
            Rectangle rect     = new Rectangle(0, 0, image.Width, image.Height);

            System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(wmfFileName, graphics.GetHdc(), rect, System.Drawing.Imaging.MetafileFrameUnit.Pixel);
            graphics = Graphics.FromImage(metafile);
            graphics.DrawImage(image, 0, 0, image.Width, image.Height);
            graphics.Save();
            graphics.Dispose();
            metafile.Dispose();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Saves the image using the user's selections.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butExport_Click(object sender, EventArgs e)
        {
            //EXPORT.
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = GetSaveFilter();

            saveFileDialog1.FileName         = VectorDraw.Professional.Utilities.vdGlobals.GetFileNameWithoutExtension(mDoc.FileName);
            saveFileDialog1.InitialDirectory = VectorDraw.Professional.Utilities.vdGlobals.GetDirectoryName(mDoc.FileName);

            saveFileDialog1.RestoreDirectory = true;
            DialogResult res = saveFileDialog1.ShowDialog(this);

            Application.DoEvents();
            if (res == DialogResult.OK)
            {
                string filename = saveFileDialog1.FileName;

                if ((filename != "") && (filename != null))
                {
                    if (filename.EndsWith(".emf", StringComparison.CurrentCultureIgnoreCase) || filename.EndsWith(".wmf", StringComparison.CurrentCultureIgnoreCase))
                    {
                        IntPtr referencedc = VectorDraw.Render.GDIDraw.GDI.IntCreateDC("DISPLAY", "", "", IntPtr.Zero);
                        System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(filename, referencedc, System.Drawing.Imaging.EmfType.EmfOnly, "FromVectorDraw6");
                        Color bkcolor = mDoc.ActiveRender.BkColor;
                        System.Drawing.Size     renderingSize = new System.Drawing.Size(mImg.Width, mImg.Height);
                        System.Drawing.Graphics gr            = Graphics.FromImage(emf);
                        gr.FillRectangle(new SolidBrush(bkcolor), new Rectangle(new Point(0, 0), renderingSize));
                        mDoc.ActiveLayOut.RenderToGraphics(gr, mRenderBox, mImg.Width, mImg.Height);
                        gr.Dispose();
                        emf.Dispose();
                        VectorDraw.Render.GDIDraw.GDI.DeleteDC(referencedc);
                    }
                    else
                    {
                        mImg.Save(filename);
                    }
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Метод конвертирует исходный графический файл в wmetafile 
        /// и создает строку для вставки в RTF-документ
        /// wmetafile т.к. его поддерживает большинство RTF редакторов
        /// </summary>
        private static StringBuilder BitmapToRtfImage(Image image)
        {
            StringBuilder sb = new StringBuilder();

            MemoryStream memory = null;
            System.Drawing.Imaging.Metafile metaFile = null;
            try
            {
                memory = new MemoryStream();
                using (Graphics graphics = Graphics.FromImage(image))
                {
                    IntPtr ptr = graphics.GetHdc();
                    metaFile = new System.Drawing.Imaging.Metafile(memory, ptr);
                    graphics.ReleaseHdc(ptr);
                }

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

                IntPtr metaPtr = metaFile.GetHenhmetafile(); // указатель на метафайл

                uint bufferSize = NativeMethods.GdipEmfToWmfBits(metaPtr, 0, null, MM_ANISOTROPIC,
                     NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // получаем размер массива

                byte[] buffer = new byte[bufferSize]; // здесь хранится метафайл

                NativeMethods.GdipEmfToWmfBits(metaPtr, bufferSize, buffer, MM_ANISOTROPIC,
                     NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); //копируем файл в буфер

                NativeMethods.DeleteEnhMetaFile(metaPtr);//удаление метафайла

                byte[] block;
                int blockSize = 0x100000;

                int bufferBytesToRead = buffer.Length;
                int currentBufferPosition = 0;
                // копируем байты метафайла в StringBuilder попутно переводя в правильный текстовый формат
                while (bufferBytesToRead > blockSize)
                {

                    block = new byte[blockSize];
                    Buffer.BlockCopy(buffer, currentBufferPosition, block, 0, blockSize);
                    currentBufferPosition += blockSize;
                    bufferBytesToRead -= blockSize;

                    sb.Append(BitConverter.ToString(block, 0).Replace("-", string.Empty));
                }

                if (bufferBytesToRead > 0)
                {
                    block = new byte[bufferBytesToRead];
                    Buffer.BlockCopy(buffer, currentBufferPosition, block, 0, bufferBytesToRead);

                    sb.Append(BitConverter.ToString(block, 0).Replace("-", string.Empty));
                }
                //return sb.ToString();
            }
            finally
            {
                if (metaFile != null)
                    metaFile.Dispose();

                if (memory != null)
                    memory.Close();
            }
            return sb;
        }
Ejemplo n.º 5
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
            System.IO.MemoryStream _stream = null;

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

            // The enhanced metafile
            System.Drawing.Imaging.Metafile _metaFile = null;

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

            try
            {
                _rtf    = new StringBuilder();
                _stream = new System.IO.MemoryStream();

                // Get a graphics context from the RichTextBox
                using (_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 System.Drawing.Imaging.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();
                }
            }
        }
Ejemplo n.º 6
0
        private string ConvertToMetafileHexDataString(Stream imageStream)
        { 
            MemoryStream metafileStream = new MemoryStream();
 
            // Get the graphics to write image on the metafile 
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero);
 
            // Create the empty metafile
            System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(metafileStream, graphics.GetHdc(), System.Drawing.Imaging.EmfType.EmfOnly);

            // Release HDC 
            graphics.ReleaseHdc();
 
            // Create the graphics for metafile destination 
            System.Drawing.Graphics graphicsTarget = System.Drawing.Graphics.FromImage(metafile);
 
            // Create bitmap from the image source stream
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imageStream);

            // Draw the bitmap image to the metafile 
            graphicsTarget.DrawImage(bitmap, System.Drawing.Point.Empty);
 
            // Dispose graphics target 
            graphicsTarget.Dispose();
 
            // Move to the start position
            metafileStream.Position = 0;

            // Create the enhance metafile from metafile stream what we rendered from the bitmap image 
            System.Drawing.Imaging.Metafile enhanceMetafile = new System.Drawing.Imaging.Metafile(metafileStream);
 
            // Get the enhance metafile handle from the enhance metafile 
            IntPtr hdc = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(this, IntPtr.Zero));
            IntPtr hEnhanceMetafile = enhanceMetafile.GetHenhmetafile(); 

            // Convert the enhance metafile to the windows metafile with Win32 GDI
            uint windowsMetafileSize = UnsafeNativeMethods.GetWinMetaFileBits(hEnhanceMetafile, 0, null, /*MapMode:MM_ANISOTROPIC*/8, hdc);
            Byte[] windowsMetafileBytes = new Byte[windowsMetafileSize]; 
            UnsafeNativeMethods.GetWinMetaFileBits(hEnhanceMetafile, windowsMetafileSize, windowsMetafileBytes, /*MapMode:MM_ANISOTROPIC*/8, hdc);
 
            // Dispose metafile and metafile stream 
            metafile.Dispose();
            metafileStream.Dispose(); 

            // return the windows metafile hex data string
            return ConvertToImageHexDataString(windowsMetafileBytes);
        } 
 private static KeyValuePair<Range, Content> ProcessInlineShape( InlineShape _shape )
 {
     float width = _shape.Width;
      float height = _shape.Height;
      string altText = "";
      string title = "";
      try
      {
     float scaleWidth = _shape.ScaleWidth;
     if ( scaleWidth > 0.0 )
     {
        //width *= (scaleWidth / 100.0f);
     }
      }
      catch
      {
      }
      try
      {
     float scaleHeight = _shape.ScaleHeight;
     if ( scaleHeight > 0.0 )
     {
        //height *= (scaleHeight / 100.0f);
     }
      }
      catch
      {
      }
      try
      {
     altText = _shape.AlternativeText;
      }
      catch
      {
      }
      try
      {
     title = _shape.Title;
      }
      catch
      {
      }
      PngImageContent imageContent = null;
      _shape.Range.CopyAsPicture();
      object pngData = Clipboard.GetData( "PNG" );
      if ( pngData is System.IO.MemoryStream )
      {
     imageContent = new PngImageContent( (System.IO.MemoryStream) pngData, altText, title, width, height );
      }
      else
      {
     if ( Clipboard.ContainsData( DataFormats.EnhancedMetafile ) )
     {
        if ( ClipboardFunctions.OpenClipboard( IntPtr.Zero ) )
        {
           width *= 1.5f;
           height *= 1.5f;
           IntPtr data = ClipboardFunctions.GetClipboardData( DataFormats.GetFormat( DataFormats.EnhancedMetafile ).Id );
           System.Drawing.Imaging.Metafile metaFile = new System.Drawing.Imaging.Metafile( data, true );
           ClipboardFunctions.CloseClipboard();
           System.Drawing.Bitmap pngImage = new System.Drawing.Bitmap( (int) width, (int) height );
           using ( System.Drawing.Graphics g = System.Drawing.Graphics.FromImage( pngImage ) )
           {
              g.DrawImage( metaFile, new System.Drawing.Rectangle( 0, 0, (int) width, (int) height ) );
           }
           metaFile.Dispose();
           System.IO.MemoryStream pngDataStream = new System.IO.MemoryStream();
           pngImage.Save( pngDataStream, System.Drawing.Imaging.ImageFormat.Png );
           pngDataStream.Seek( 0, System.IO.SeekOrigin.Begin );
           imageContent = new PngImageContent( pngDataStream, altText, title, width, height );
           pngImage.Dispose();
        }
     }
      }
      Clipboard.Clear();
      if ( imageContent == null )
      {
     return new KeyValuePair<Range, Content>( _shape.Range, new TextContent( String.Format( "INTERNAL ERROR: Could not convert shape to PNG image." ), Edward.ERROR_STYLE ) );
      }
      else
      {
     return new KeyValuePair<Range, Content>( _shape.Range, imageContent );
      }
 }
Ejemplo n.º 8
0
        public System.Drawing.Imaging.Metafile ToMetaFile_(string html, double width, double height, double marginL, double marginT, double marginR, double marginB)
        {
            double w             = width - marginL - marginR;
            double h             = height - marginT - marginB;
            string pageSizeStyle = string.Format("width: {0}mm;height: {1}mm;margin-left: 0px;margin-right: 0px;", w, h);

            wb.Document.OpenNew(false);
            wb.Document.Write(html);
            wb.Refresh();

            wb.Document.Body.Style = pageSizeStyle;
            wb.Refresh();

            wb.Width  = wb.Document.Body.ScrollRectangle.Width;
            wb.Height = wb.Document.Body.ScrollRectangle.Height;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            using (var graHandle = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
            {
                double dpix = graHandle.DpiX;
                double dpiy = graHandle.DpiY;
                var    hdc  = graHandle.GetHdc();
                System.Drawing.Imaging.Metafile meta
                    = new System.Drawing.Imaging.Metafile(ms, hdc, new System.Drawing.RectangleF(0, 0, (float)w, (float)h), System.Drawing.Imaging.MetafileFrameUnit.Millimeter);
                using (var g = Graphics.FromImage(meta))
                {
                }
                double hres = meta.HorizontalResolution;
                double vres = meta.VerticalResolution;

                meta = new System.Drawing.Imaging.Metafile(ms, hdc, new System.Drawing.RectangleF(0, 0, (float)w, (float)h), System.Drawing.Imaging.MetafileFrameUnit.Millimeter);
                using (var g = Graphics.FromImage(meta))
                {
                    double scale = hres / 25.4;
                    RECT   r     = new RECT();
                    r.Left   = 0;
                    r.Top    = 0;
                    r.Right  = (int)w;
                    r.Bottom = (int)((double)w * (double)wb.Document.Body.ScrollRectangle.Height / (double)wb.Document.Body.ScrollRectangle.Width);
                    r.Right *= 10;
                    //g.PageUnit = GraphicsUnit.Millimeter;
                    try
                    {
                        var hdc2 = g.GetHdc();
                        try
                        {
                            var unknown = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(wb.ActiveXInstance);
                            try
                            {
                                OleDraw(unknown, (int)System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT, hdc2, ref r);
                            }
                            finally
                            {
                                System.Runtime.InteropServices.Marshal.Release(unknown);
                            }
                        }
                        finally
                        {
                            g.ReleaseHdc(hdc2);
                        }
                        for (int x = 0; x <= width; x += 10)
                        {
                            g.DrawLine(System.Drawing.Pens.Red, new System.Drawing.Point(x, 0), new System.Drawing.Point(x, 297));
                        }
                    }
                    finally
                    {
                        graHandle.ReleaseHdc(hdc);
                    }
                }
                meta.Dispose();
            }

            ms.Position = 0;
            using (System.IO.FileStream fs = System.IO.File.OpenWrite("j:\\test.emf"))
            {
                ms.WriteTo(fs);
            }
            ms.Position = 0;

            return(System.Drawing.Imaging.Metafile.FromStream(ms) as System.Drawing.Imaging.Metafile);
        }
Ejemplo n.º 9
0
        public System.Drawing.Imaging.Metafile ToMetaFile(string html, double width, double height, double marginL, double marginT, double marginR, double marginB)
        {
            double w             = width - marginL - marginR;
            double h             = height - marginT - marginB;
            string pageSizeStyle = string.Format("width: {0}mm;height: {1}mm;margin-left: 0px;margin-right: 0px;", w, h);

            wb.Document.OpenNew(false);
            wb.Document.Write(html);
            wb.Refresh();

            wb.Document.Body.Style = pageSizeStyle;
            wb.Refresh();

            wb.Width  = wb.Document.Body.ScrollRectangle.Width;
            wb.Height = wb.Document.Body.ScrollRectangle.Height;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            using (var graHandle = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
            {
                double dpix = graHandle.DpiX;
                double dpiy = graHandle.DpiY;
                var    hdc  = graHandle.GetHdc();
                System.Drawing.Imaging.Metafile meta
                    = new System.Drawing.Imaging.Metafile(ms, hdc, new System.Drawing.RectangleF(0, 0, (float)w, (float)h), System.Drawing.Imaging.MetafileFrameUnit.Millimeter);

                using (var g = Graphics.FromImage(meta))
                {
                    g.PageUnit = GraphicsUnit.Millimeter;

                    var xd = dpix / meta.PhysicalDimension.Width;
                    var yd = dpiy / meta.PhysicalDimension.Height;


                    RECT r = new RECT();
                    r.Left   = 0;
                    r.Top    = 0;
                    r.Right  = (int)(w * xd);
                    r.Bottom = (int)((double)w * (double)wb.Document.Body.ScrollRectangle.Height / (double)wb.Document.Body.ScrollRectangle.Width * yd);


                    try
                    {
                        var hdc2 = g.GetHdc();
                        try
                        {
                            var unknown = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(wb.ActiveXInstance);
                            try
                            {
                                OleDraw(unknown, (int)System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT, hdc2, ref r);
                            }
                            finally
                            {
                                System.Runtime.InteropServices.Marshal.Release(unknown);
                            }
                        }
                        finally
                        {
                            g.ReleaseHdc(hdc2);
                        }


                        var state = g.Save();
                        g.TranslateTransform(0, 100);
                        g.RotateTransform(-45);

                        g.DrawString("てすと", new Font("Meiryo", 100), Brushes.Red, 0, 0);
                        g.Restore(state);
                    }
                    finally
                    {
                        graHandle.ReleaseHdc(hdc);
                    }
                }
                meta.Dispose();
            }

            ms.Position = 0;

            return(System.Drawing.Imaging.Metafile.FromStream(ms) as System.Drawing.Imaging.Metafile);
        }