protected override void OnPrintPage(PrintPageEventArgs e) { base.OnPrintPage(e); Stream pageToPrint = m_pages[m_currentPage]; pageToPrint.Position = 0; // Load each page into a Metafile to draw it. using (Metafile pageMetaFile = new Metafile(pageToPrint)) { Rectangle adjustedRect = new Rectangle( e.PageBounds.Left - (int)e.PageSettings.HardMarginX, e.PageBounds.Top - (int)e.PageSettings.HardMarginY, e.PageBounds.Width, e.PageBounds.Height); // Draw a white background for the report e.Graphics.FillRectangle(Brushes.White, adjustedRect); // Draw the report content e.Graphics.DrawImage(pageMetaFile, adjustedRect); // Prepare for next page. Make sure we haven't hit the end. m_currentPage++; e.HasMorePages = m_currentPage < m_pages.Count; } }
protected override void OnPrintPage(PrintPageEventArgs e) { if (this.PrinterSettings.PrintRange == System.Drawing.Printing.PrintRange.SomePages) { while (++_page < this.PrinterSettings.FromPage) { // Fake the pages that need to be skipped by printing them to a Metafile IntPtr hDev = e.Graphics.GetHdc(); try { using (var mf = new Metafile(hDev, e.PageBounds)) using (var gr = Graphics.FromImage(mf)) { var ppe = new PrintPageEventArgs(gr, e.MarginBounds, e.PageBounds, e.PageSettings); base.OnPrintPage(ppe); } } finally { e.Graphics.ReleaseHdc(hDev); } } // Print the real page base.OnPrintPage(e); // No need to continue past PageTo if (this.PrinterSettings.ToPage > 0 && _page >= this.PrinterSettings.ToPage) e.HasMorePages = false; } else { base.OnPrintPage(e); } }
public static Bitmap GetImage(IntPtr hwnd) { try { if (OpenClipboard(hwnd)) { IntPtr data = GetClipboardData(14); // CF_ENHMETAFILE 14 if (data != IntPtr.Zero) { using (Metafile mf = new Metafile(data, true)) { Bitmap b = new Bitmap(mf); return b; } } } } finally { CloseClipboard(); } return null; }
// Metafile mf is set to a state that is not valid inside this function. static public bool PutEnhMetafileOnClipboard( IntPtr hWnd, Metafile mf ) { bool bResult = false; IntPtr hEMF, hEMF2; hEMF = mf.GetHenhmetafile(); // invalidates mf if( ! hEMF.Equals( new IntPtr(0) ) ) { hEMF2 = CopyEnhMetaFile( hEMF, new IntPtr(0) ); if( ! hEMF2.Equals( new IntPtr(0) ) ) { if( OpenClipboard( hWnd ) ) { if( EmptyClipboard() ) { IntPtr hRes = SetClipboardData( 14 /*CF_ENHMETAFILE*/, hEMF2 ); bResult = hRes.Equals( hEMF2 ); CloseClipboard(); } } } DeleteEnhMetaFile( hEMF ); } return bResult; }
public void EnumerateMetafile(Metafile metafile, RectangleF destinationRectangle, RectangleF sourceRectangle, GraphicsUnit unit, System.Drawing.Graphics.EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttributes) { this.baseGraphics.EnumerateMetafile(metafile, destinationRectangle, sourceRectangle, unit, callback, callbackData, imageAttributes); }
/// <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> ///加载路径下的一张图片,读取失败或格式不支持返回一张默认图片 /// </summary> /// ///<note> ///外部使用完 Image 之后,必须明确调用 Image.Dipose() 立刻释放,因 ///为 svg 文件会生成 emf 临时文件,需要释放资源才能删除 ///</note> static public Image LoaderImage(string path) { Bitmap defaultBitmap = global::BesPrinter.Properties.Resources.unsupported_image; Image image = null; if (!File.Exists(path)) { image = defaultBitmap; //文件不存在,返回默认图片 } else { FileInfo fileInfo = new FileInfo(path); if (fileInfo.Extension == ".bmp" || fileInfo.Extension == ".png" || fileInfo.Extension == ".jpg" || fileInfo.Extension == ".jpeg") { FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); //从文件流打开,不占用文件 image = Image.FromStream(fileStream); fileStream.Close(); fileStream.Dispose(); } else if (fileInfo.Extension == ".svg") { //临时创建一个 svg 转换而来的 emf 文件 string emfTempPath = Path.GetTempFileName(); try { SvgDocument svg = SvgDocument.Open(path); using (Graphics bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero)) { using (var metafile = new Metafile(emfTempPath, bufferGraphics.GetHdc())) { using (Graphics graphics = Graphics.FromImage(metafile)) { svg.Draw(graphics); } } image = new Metafile(emfTempPath); //读取 emf 文件 } } catch (Exception e) { MessageBox.Show(e.Message, Trans.tr("Tip"), MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { //现在获得图片不能立刻删除文件,不然得到 image 也无法获得其中的数据 if (listTempEmfFiles == null) { listTempEmfFiles = new List <string>(); } listTempEmfFiles.Add(emfTempPath); } } else if (fileInfo.Extension == ".emf") { FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); //从文件流打开,不占用文件 image = new Metafile(fileStream); fileStream.Close(); fileStream.Dispose(); } else { image = defaultBitmap; //格式不支持不存在,返回默认图片 } } if (image == null) { image = defaultBitmap; //如果存在读取失败的情况,使用默认图片返回 } return(image); }
private void PrintPage(object sender, PrintPageEventArgs ev) { Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); ev.Graphics.DrawImage(pageImage, ev.PageBounds); m_currentPageIndex++; ev.HasMorePages = (m_currentPageIndex < m_streams.Count); }
public Metafile[] DrawPlot(Element_ND[] Elements, Node_ND[] Nodes, Vector[] GlobalUnknowns, out Vector MinV, out Vector MaxV) { int NP = GlobalUnknowns.Length; Metafile[] Plots = new Metafile[NP]; Graphics[] gs = new Graphics[NP]; for (int i = 0; i < NP; i++) { Plots[i] = ImageMethods.MakeMetafile(PageWidth, PageHeight); gs[i] = Graphics.FromImage(Plots[i]); } SetPlotTypeToDisplay(); MinV = new Vector(NP); MaxV = new Vector(NP); Node_ND.Set_UnknownForNode(Nodes, GlobalUnknowns[0]); Surfaces[] TheSurfaces = Element_ND.Make_GraphicSurfaces(Elements, Plot_ObjectResolution); Surfaces.CalculateMinMax_Values(TheSurfaces, out MinV.Values[0], out MaxV.Values[0]); for (int i = 1; i < NP; i++) { Node_ND.Set_UnknownForNode(Nodes, GlobalUnknowns[i]); Element_ND.Change_GraphicSurfaces_Values(Elements, ref TheSurfaces, Plot_ObjectResolution); Surfaces.CalculateMinMax_Values(TheSurfaces, out MinV.Values[i], out MaxV.Values[i]); } double Min = MinV.Min(); double Max = MaxV.Max(); for (int i = 0; i < NP; i++) { Node_ND.Set_UnknownForNode(Nodes, GlobalUnknowns[i]); Element_ND.Change_GraphicSurfaces_Values(Elements, ref TheSurfaces, Plot_ObjectResolution); if (FixedScale) { TheGraph.DrawGraph(gs[i], Xo, TheSurfaces, Min, Max); } else { TheGraph.DrawGraph(gs[i], Xo, TheSurfaces, MinV.Values[i], MaxV.Values[i]); } if (ColorPlotOn) { if (FixedScale) { Plot_ColorScale.Initialize_Calculate_WidthAndHeight(ref gs[i], Min, Max); } else { Plot_ColorScale.Initialize_Calculate_WidthAndHeight(ref gs[i], MinV.Values[i], MaxV.Values[i]); } Plot_ColorScale.x_c = new Vector(X_TR); Plot_ColorScale.x_c.Values[0] += ColorScalePad + Plot_ColorScale.Width / 2.0D; Plot_ColorScale.AddColorScale(ref gs[i]); } Vector Title_c = new Vector(X_TC); Plot_Title.GetWidthAndHeight(gs[i]); Title_c.Values[1] += -TitlePad - Plot_Title.Height; Plot_Title.DrawTitle(gs[i], Title_c); Vector OPPS_Graphics_c = new Vector(2); OOPS_Graphics_Title.GetWidthAndHeight(gs[i]); OPPS_Graphics_c.Values[0] = PageWidth - ColorScalePad - OOPS_Graphics_Title.Width / 2.0D; OPPS_Graphics_c.Values[1] = PageHeight - ColorScalePad - OOPS_Graphics_Title.Height; OOPS_Graphics_Title.DrawTitle(gs[i], OPPS_Graphics_c); gs[i].Dispose(); } return(Plots); }
public string GetSelectionImg(string paperName) { cutTimes = 1; cutTimesCount = 0; const int MAX_height = 3000; //string timeResult = ""; Range range = Globals.ThisAddIn.Application.Selection.Range; Range range2 = Globals.ThisAddIn.Application.Selection.Range; //timeResult = timeResult + "Time1:" + DateTime.Now.ToString() + "\n"; string imgName = Guid.NewGuid().ToString() + ".png"; if (!Directory.Exists(Globals.ThisAddIn.exerciseJsonPath + paperName)) { Directory.CreateDirectory(Globals.ThisAddIn.exerciseJsonPath + paperName); } double zoom = 0.33; const int imgWidth = 1188; Image imgTemp = Metafile.FromStream(new MemoryStream(range.EnhMetaFileBits)); //imgTemp.Save(Globals.ThisAddIn.exerciseJsonPath + paperName + "\\" + imgName, System.Drawing.Imaging.ImageFormat.Png); if (MAX_height < imgTemp.Height) { Paragraphs paragraphs = range.Paragraphs; Tables tables = range.Tables; List <StartEnd> paragraphList = new List <StartEnd>(); List <StartEnd> tableList = new List <StartEnd>(); for (int i = 0; i < paragraphs.Count; i++) { Paragraph paragraph = paragraphs[i + 1]; StartEnd startEnd = new StartEnd(); startEnd.Start = paragraph.Range.Start; startEnd.End = paragraph.Range.End; paragraphList.Add(startEnd); } for (int i = 0; i < tables.Count; i++) { Table table = tables[i + 1]; StartEnd startEnd = new StartEnd(); startEnd.Start = table.Range.Start; startEnd.End = table.Range.End; tableList.Add(startEnd); } List <StartEnd> resultList = CutRange(paragraphList, tableList); List <StartEnd> finalImgRangeList = new List <StartEnd>(); for (int i = 0; i < resultList.Count; i++) { StartEnd startendImg = new StartEnd(); startendImg.Start = resultList[i].Start; startendImg.End = resultList[i].End; for (int j = i; j < resultList.Count; j++) { range2.SetRange((int)resultList[i].Start, (int)resultList[j].End); Image img = Metafile.FromStream(new MemoryStream(range2.EnhMetaFileBits)); if (img.Height < MAX_height) { startendImg.End = resultList[j].End; if (j == resultList.Count - 1) { i = j; } } else { if (i == j) { MessageBox.Show("请确定没有超过一页的段落或表格"); Globals.ThisAddIn.Application.ActiveWindow.ScrollIntoView(range2); return(""); } i = j - 1; break; } } finalImgRangeList.Add(startendImg); } cutTimes = finalImgRangeList.Count; //timeResult = timeResult + "Time2:" + DateTime.Now.ToString() + "\n"; int allImgHeight = 0; int allImgWidth = 0; for (int i = 0; i < finalImgRangeList.Count; i++) { range2.SetRange((int)finalImgRangeList[i].Start, (int)finalImgRangeList[i].End); Image img = Metafile.FromStream(new MemoryStream(range2.EnhMetaFileBits)); if (img.Width > allImgWidth) { allImgWidth = img.Width; } allImgHeight += img.Height; } //for(int i=0;i<resultList.Count;i++) //{ // int start=(int)resultList[i].Start; // int end=(int)resultList[i].End; // range2.SetRange(start,end); // if (i % 2 == 0) // range2.HighlightColorIndex = WdColorIndex.wdRed; // else // range2.HighlightColorIndex = WdColorIndex.wdYellow; //} //zoom = (double)imgWidth / (double)allImgWidth; System.Drawing.Bitmap bmp = new Bitmap(imgWidth, (int)(allImgHeight * zoom)); System.Drawing.Graphics gx = System.Drawing.Graphics.FromImage(bmp); // 创建Graphics对象 gx.InterpolationMode = InterpolationMode.HighQualityBicubic; // 指定高质量、低速度呈现。 gx.SmoothingMode = SmoothingMode.HighQuality; gx.CompositingQuality = CompositingQuality.HighQuality; gx.CompositingMode = CompositingMode.SourceOver; gx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; int startPosition = 0; double oldZoom = zoom; for (int i = 0; i < finalImgRangeList.Count; i++) { range2.SetRange((int)finalImgRangeList[i].Start, (int)finalImgRangeList[i].End); Image img = Metafile.FromStream(new MemoryStream(range2.EnhMetaFileBits)); if ((double)imgWidth / (double)img.Width < zoom) { zoom = (double)imgWidth / (double)img.Width; } gx.FillRectangle(new SolidBrush(System.Drawing.Color.Transparent), 0, startPosition, (int)(img.Width * zoom), (int)(img.Height * zoom)); gx.DrawImage(img, new System.Drawing.Rectangle(0, startPosition, (int)(img.Width * zoom), (int)(img.Height * zoom))); startPosition += (int)(img.Height * zoom); zoom = oldZoom; cutTimesCount = i + 1; } //bmp = KiSharpen(bmp,(float)0.3); bmp.Save(Globals.ThisAddIn.exerciseJsonPath + paperName + "\\" + imgName, System.Drawing.Imaging.ImageFormat.Png); } else { //zoom = (double)imgWidth / (double)imgTemp.Width; System.Drawing.Bitmap bmp = new Bitmap(imgWidth, (int)(imgTemp.Height * zoom)); System.Drawing.Graphics gx = System.Drawing.Graphics.FromImage(bmp); // 创建Graphics对象 gx.InterpolationMode = InterpolationMode.HighQualityBicubic; // 指定高质量、低速度呈现。 gx.SmoothingMode = SmoothingMode.HighQuality; gx.CompositingQuality = CompositingQuality.HighQuality; gx.CompositingMode = CompositingMode.SourceOver; gx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; gx.FillRectangle(new SolidBrush(System.Drawing.Color.Transparent), 0, 0, (int)(imgTemp.Width * zoom), (int)(imgTemp.Height * zoom)); gx.DrawImage(imgTemp, new System.Drawing.Rectangle(0, 0, (int)(imgTemp.Width * zoom), (int)(imgTemp.Height * zoom))); //imgTemp.Save(Globals.ThisAddIn.exerciseJsonPath + paperName + "\\" + imgName, System.Drawing.Imaging.ImageFormat.Png); bmp.Save(Globals.ThisAddIn.exerciseJsonPath + paperName + "\\" + imgName, System.Drawing.Imaging.ImageFormat.Png); } //timeResult = timeResult + "Time3:" + DateTime.Now.ToString() + "\n"; cutTimes = 1; cutTimesCount = 0; //MessageBox.Show(timeResult); return(imgName); }
/// <summary> /// Sends different message/image depending on what state the system currently has. /// </summary> /// <param name="sender"></param> /// <param name="systemRunStateEventArgs"></param> private void WhenSystemDataAPIOnSystemState(object sender, SystemRunStateEventArgs systemRunStateEventArgs) { try { SystemRunState state = systemRunStateEventArgs.State; //Updating the current system state #region Some logic. Check if the system have started a run, if the state is the previous state etc. if (state == SystemRunState.Manual || state == SystemRunState.Running) { mHasOneRun = true; return; } if (!mHasOneRun) { return; } if (mPreviousState == state) { return; } #endregion #region Get the current relevant information from the current run currentSystemStatus = mSystemDataAPI.GetCurrentSystemStatus(); systemName = mSystemDataAPI.GetInstrumentInformation().SystemName; methodName = mSystemDataAPI.GetCurrentSystemStatus().MethodName; methodInfo = string.IsNullOrEmpty(methodName) ? "Manual run" : "Method " + methodName; #endregion mPreviousState = state; //Updating the previous system state #region logic for the different states switch (state) { #region Pause states case SystemRunState.ManualUserPause: //if a user manually pauses the proccess. numberOfInterrupts++; messageToTwitter = formTheStringToTwitter("is now paused by a user."); SendTweet(messageToTwitter); break; case SystemRunState.Pause: numberOfInterrupts++; messageToTwitter = formTheStringToTwitter("is now paused."); SendTweet(messageToTwitter); break; #endregion #region Error state case SystemRunState.AlarmError: //if the proccess receives an error if (!hasEnded) { numberOfInterrupts++; messageToTwitter = formTheStringToTwitter("encountered an error!"); metafile = mReportingAPI.GetMetafile(); SendTweet(messageToTwitter, metafile); } break; #endregion #region User Ended run state case SystemRunState.TransitToEnd: //if a user manually ends the run messageToTwitter = formTheStringToTwitter("has #ended."); metafile = mReportingAPI.GetMetafile(); SendTweet(messageToTwitter, metafile); //reset and updates values numberOfInterrupts = 0; hasEnded = true; break; #endregion #region User resumed state case SystemRunState.TransitToManualRun: //if a user continues the run after (if it was paused) messageToTwitter = formTheStringToTwitter("is resumed."); SendTweet(messageToTwitter); break; #endregion default: break; } #endregion } catch (Exception e) { //Writing the error message to a logger mLogger.LogErrorToUNICORNLog(e.Message); } }
/// <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); }
public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) { Debug.Assert(dc != null && graphics == null, "PrintController methods called in the wrong order?"); // For security purposes, don't assume our public methods methods are called in any particular order CheckSecurity(); base.OnStartPage(document, e); try { IntSecurity.AllPrintingAndUnmanagedCode.Assert(); if (e.CopySettingsToDevMode) { e.PageSettings.CopyToHdevmode(modeHandle); } Size size = e.PageBounds.Size; // Metafile framing rectangles apparently use hundredths of mm as their unit of measurement, // instead of the GDI+ standard hundredth of an inch. Size metafileSize = PrinterUnitConvert.Convert(size, PrinterUnit.Display, PrinterUnit.HundredthsOfAMillimeter); // Create a Metafile which accepts only GDI+ commands since we are the ones creating // and using this ... // Framework creates a dual-mode EMF for each page in the preview. // When these images are displayed in preview, // they are added to the dual-mode EMF. However, // GDI+ breaks during this process if the image // is sufficiently large and has more than 254 colors. // This code path can easily be avoided by requesting // an EmfPlusOnly EMF.. Metafile metafile = new Metafile(dc.Hdc, new Rectangle(0, 0, metafileSize.Width, metafileSize.Height), MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusOnly); PreviewPageInfo info = new PreviewPageInfo(metafile, size); list.Add(info); PrintPreviewGraphics printGraphics = new PrintPreviewGraphics(document, e); graphics = Graphics.FromImage(metafile); if (graphics != null && document.OriginAtMargins) { // Adjust the origin of the graphics object to be at the // user-specified margin location // int dpiX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.LOGPIXELSX); int dpiY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.LOGPIXELSY); int hardMarginX_DU = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.PHYSICALOFFSETX); int hardMarginY_DU = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.PHYSICALOFFSETY); float hardMarginX = hardMarginX_DU * 100 / dpiX; float hardMarginY = hardMarginY_DU * 100 / dpiY; graphics.TranslateTransform(-hardMarginX, -hardMarginY); graphics.TranslateTransform(document.DefaultPageSettings.Margins.Left, document.DefaultPageSettings.Margins.Top); } graphics.PrintingHelper = printGraphics; if (antiAlias) { graphics.TextRenderingHint = TextRenderingHint.AntiAlias; graphics.SmoothingMode = SmoothingMode.AntiAlias; } } finally { CodeAccessPermission.RevertAssert(); } return(graphics); }
public void EnumerateMetafile(Metafile metafile, RectangleF destinationRectangle, RectangleF sourceRectangle, GraphicsUnit sourceUnit, System.Drawing.Graphics.EnumerateMetafileProc callback, IntPtr callbackData) { this.baseGraphics.EnumerateMetafile(metafile, destinationRectangle, sourceRectangle, sourceUnit, callback, callbackData); }
// ** overrides /// <summary> /// Selects the text or image that will be rendered by the field. /// </summary> /// <param name="value">Field text.</param> /// <param name="img">Field image.</param> /// <param name="designTime">Whether we in design time or runtime.</param> override protected void GetRenderContent(ref string value, ref Image img, bool designTime) { // create image C1Report parentReport = ParentReport; using (Bitmap bmp = new Bitmap(1, 1)) using (Graphics g = Graphics.FromImage(bmp)) { // PointF dpi = new PointF(g.DpiX, g.DpiY); // calculate field size in pixels // (based on field size in twips and screen resolution) Rectangle rc = new Rectangle(Point.Empty, GetFieldSizePixels(dpi)); // create metafile image (this is the return value) IntPtr hdc = g.GetHdc(); // consider the real screen logical dpi (144 in the big fonts mode (150%), and 96 and 120 in 100% and 125% accordingly) // the folowing coefficients will != 1 in the big fonts mode only float kX = dpi.X / GraphicsUtils.RealScreenDpiX; float kY = dpi.Y / GraphicsUtils.RealScreenDpiY; // set clipping area with taking account of the coefficients img = new Metafile(hdc, new RectangleF(0, 0, rc.Width * kX, rc.Height * kY), MetafileFrameUnit.Pixel, this.ParentReport.EmfType); using (Graphics meta = Graphics.FromImage(img)) { // some multiples of 90 degrees create spurious lines <<B168>> meta.PageUnit = GraphicsUnit.Pixel; int angle = _angle; while (angle < 0) { angle += 360; } if (angle % 90 == 0) { angle++; } // draw background using (LinearGradientBrush br = new LinearGradientBrush(rc, _clrFrom, _clrTo, angle)) { // fill background as usual if (BackColor != Utils.TransparentColor) { // update brush if (_brBack == null || _brBack.Color != Utils.FromWpfColor(BackColor)) { _brBack = new SolidBrush(Utils.FromWpfColor(BackColor)); } meta.FillRectangle(_brBack, rc); } // create pen if necessary Pen pen = null; if (BorderColor != Utils.TransparentColor && BorderStyle == BorderStyleEnum.Transparent && LineWidth > 0) { int lineWidth = Math.Max(1, (int)(LineWidth * dpi.X / 1440f)); rc.Inflate(-lineWidth / 2, -lineWidth / 2); //rc.Inflate(-1, -1); pen = new Pen(Utils.FromWpfColor(BorderColor), lineWidth); } // draw the background and border rc.Width--; rc.Height--; // calculate corner radius in pixels var cornerRadiusPixel = new CornerRadius( (int)(_cornerRadius.TopLeftX * dpi.X / 1440f), (int)(_cornerRadius.TopLeftY * dpi.Y / 1440f), (int)(_cornerRadius.TopRightX * dpi.X / 1440f), (int)(_cornerRadius.TopRightY * dpi.Y / 1440f), (int)(_cornerRadius.BottomLeftX * dpi.X / 1440f), (int)(_cornerRadius.BottomLeftY * dpi.Y / 1440f), (int)(_cornerRadius.BottomRightX * dpi.X / 1440f), (int)(_cornerRadius.BottomRightY * dpi.Y / 1440f)); RoundRect(meta, br, pen, rc, cornerRadiusPixel); // dispose of pen if (pen != null) { pen.Dispose(); } } // draw string content if (value != null && value.Length > 0) { // update brush if (_brFore == null || _brFore.Color != Utils.FromWpfColor(ForeColor)) { _brFore = new SolidBrush(Utils.FromWpfColor(ForeColor)); } // draw string meta.DrawString(value, Font, _brFore, rc, GetStringFormat()); } } img = FixMetafile((Metafile)img, hdc, dpi); // done with reference dc g.ReleaseHdc(hdc); } }
public void EnumerateMetafile(Metafile metafile, PointF[] destinationPoints, RectangleF sourceRectangle, GraphicsUnit sourceUnit, System.Drawing.Graphics.EnumerateMetafileProc callback) { this.baseGraphics.EnumerateMetafile(metafile, destinationPoints, sourceRectangle, sourceUnit, callback); }
public void EnumerateMetafile(Metafile metafile, PointF[] destinationPoints, System.Drawing.Graphics.EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttributes) { this.baseGraphics.EnumerateMetafile(metafile, destinationPoints, callback, callbackData, imageAttributes); }
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(); }
protected virtual void ExportToMetafile(FileStream stream, string path) { Metafile metafile = new Metafile(); metafile.AddDiagram(this); if (stream != null) { metafile.Save(stream); } else { metafile.Save(path); } }
/// <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(); } } }
private void DoPrintPage(object sender, PrintPageEventArgs e) { using (Graphics g = e.Graphics) { if (mDoc.PageCount == 0) { return; } if (mDoc.Page == 0) { return; } XRect cropBox = mDoc.CropBox; double srcWidth = (cropBox.Width / 72) * 100; double srcHeight = (cropBox.Height / 72) * 100; double pageWidth = e.PageBounds.Width; double pageHeight = e.PageBounds.Height; double marginX = e.PageSettings.HardMarginX; double marginY = e.PageSettings.HardMarginY; double dstWidth = pageWidth - (marginX * 2); double dstHeight = pageHeight - (marginY * 2); // if source bigger than destination then scale if ((srcWidth > dstWidth) || (srcHeight > dstHeight)) { double sx = dstWidth / srcWidth; double sy = dstHeight / srcHeight; double s = Math.Min(sx, sy); srcWidth *= s; srcHeight *= s; } // now center double x = (pageWidth - srcWidth) / 2; double y = (pageHeight - srcHeight) / 2; // save state RectangleF theRect = new RectangleF((float)x, (float)y, (float)srcWidth, (float)srcHeight); int theRez = e.PageSettings.PrinterResolution.X; // draw content mDoc.Rect.SetRect(cropBox); mDoc.Rendering.DotsPerInch = theRez; mDoc.Rendering.ColorSpace = "RGB"; mDoc.Rendering.BitsPerChannel = 8; if (mRenderTextAsPolygon) { //i.e. render text as polygon (non default) mDoc.SetInfo(0, "RenderTextAsText", "0"); } byte[] theData = mDoc.Rendering.GetData(".emf"); if (mTempFilePath != null) { File.WriteAllBytes(mTempFilePath + @"\" + mDoc.PageNumber + ".emf", theData); } using (MemoryStream theStream = new MemoryStream(theData)) { using (Metafile theEMF = new Metafile(theStream)) { g.DrawImage(theEMF, theRect); } } e.HasMorePages = mDoc.PageNumber < mDoc.PageCount; if (!e.HasMorePages) { return; } //increment to next page, corrupted PDF's have occasionally failed to increment //which would otherwise put us in a spooling infinite loop, which is bad, so this check avoids it int oldPageNumber = mDoc.PageNumber; ++mDoc.PageNumber; int newPageNumber = mDoc.PageNumber; if ((oldPageNumber + 1) != newPageNumber) { throw new Exception("PDF cannot be printed as it is corrupt, pageNumbers will not increment properly."); } } }
// ** overrides /// <summary> /// Selects the text or image that will be rendered by the field. /// </summary> /// <param name="value">Field text.</param> /// <param name="img">Field image.</param> /// <param name="designTime">Whether we in design time or runtime.</param> override protected void GetRenderContent(ref string value, ref Image img, bool designTime) { // create image using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { // calculate field size in pixels // (based on field size in twips and screen resolution) Size size = GetFieldSizePixels(g); Rectangle rc = new Rectangle(Point.Empty, size); // create metafile image (this is the return value) IntPtr hdc = g.GetHdc(); img = new Metafile(hdc, rc, MetafileFrameUnit.Pixel); using (Graphics meta = Graphics.FromImage(img)) { // some multiples of 90 degrees create spurious lines <<B168>> int angle = _angle; while (angle < 0) { angle += 360; } if (angle % 90 == 0) { angle++; } // calculate border radius in pixels int radius = (int)(_radius * 96f / 1440f); // draw background using (LinearGradientBrush br = new LinearGradientBrush(rc, _clrFrom, _clrTo, angle)) { // fill background as usual if (BackColor != Utils.TransparentColor) { // update brush if (_brBack == null || _brBack.Color != Utils.FromWpfColor(BackColor)) { _brBack = new SolidBrush(Utils.FromWpfColor(BackColor)); } meta.FillRectangle(_brBack, rc); } // create pen if necessary Pen pen = null; if (BorderColor != Utils.TransparentColor && BorderStyle == BorderStyleEnum.Transparent && LineWidth > 0) { int lineWidth = Math.Max(1, (int)(LineWidth * 96f / 1440f)); rc.Inflate(-lineWidth / 2, -lineWidth / 2); pen = new Pen(Utils.FromWpfColor(BorderColor), lineWidth); } // draw the background and border RoundRect(meta, br, pen, rc, radius, radius); // dispose of pen if (pen != null) { pen.Dispose(); } } // draw string content if (value != null && value.Length > 0) { // update brush if (_brFore == null || _brFore.Color != Utils.FromWpfColor(ForeColor)) { _brFore = new SolidBrush(Utils.FromWpfColor(ForeColor)); } // draw string meta.DrawString(value, Font, _brFore, rc, GetStringFormat()); } } // adjust image size for actual screen resolution // (as opposed to 'logical dpi') img = AdjustImageSize(hdc, img); // done with reference dc g.ReleaseHdc(hdc); } }
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); }
private void saveImage(string fileName) { var format = ImageFormat.Png; var ext = Path.GetExtension(fileName); if (StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".jpg") == 0 || StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".jpeg") == 0) { format = ImageFormat.Jpeg; } else if (StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".bmp") == 0) { format = ImageFormat.Bmp; } else if (StringComparer.InvariantCultureIgnoreCase.Compare(ext, ".emf") == 0) { format = ImageFormat.Emf; } var size = Canvas.ComputeCanvasBounds(true).Size *(Settings.SaveAt100 ? 1.0f : Canvas.ZoomFactor); size.X = Numeric.Clamp(size.X, 16, 8192); size.Y = Numeric.Clamp(size.Y, 16, 8192); try { if (format == ImageFormat.Emf) { // export as a metafile using (var nativeGraphics = Graphics.FromHwnd(Canvas.Handle)) { using (var stream = new MemoryStream()) { try { var dc = nativeGraphics.GetHdc(); using (var metafile = new Metafile(stream, dc)) { using (var imageGraphics = Graphics.FromImage(metafile)) { using (var graphics = XGraphics.FromGraphics(imageGraphics, new XSize(size.X, size.Y))) { Canvas.Draw(graphics, true, size.X, size.Y); } } var handle = metafile.GetHenhmetafile(); var copy = CopyEnhMetaFile(handle, fileName); DeleteEnhMetaFile(copy); } } finally { nativeGraphics.ReleaseHdc(); } } } } else { // export as an image using (var bitmap = new Bitmap((int)Math.Ceiling(size.X), (int)Math.Ceiling(size.Y))) { using (var imageGraphics = Graphics.FromImage(bitmap)) { using (var graphics = XGraphics.FromGraphics(imageGraphics, new XSize(size.X, size.Y))) { Canvas.Draw(graphics, true, size.X, size.Y); } } bitmap.Save(fileName, format); } } } catch (Exception ex) { MessageBox.Show(Program.MainForm, string.Format("There was a problem exporting the map:\n\n{0}", ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <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; _graphics = Graphics.FromImage(_image); try { _rtf = new StringBuilder(); _stream = new MemoryStream(); // Get a graphics context from the RichTextBox using (_graphics = Graphics.FromImage(_image)) { // was created from the inherited richTextBox // 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(); } } }
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); }
/// <summary> /// gets the Twitter credentials from XML-file then uploads the message and the image to Twitter. /// </summary> /// <param name="message"></param> private void SendTweet(String message, Metafile image) { SocialMediaUploader.getTwitterCredentialsFromXML(); SocialMediaUploader.sendTweet(message, image); }
public static void Print(this LocalReport report, PageSettings pageSettings) { string deviceInfo = $@"<DeviceInfo> <OutputFormat>EMF</OutputFormat> <PageWidth>{pageSettings.PaperSize.Width * 100}in</PageWidth> <PageHeight>{pageSettings.PaperSize.Height * 100}in</PageHeight> <MarginTop>{pageSettings.Margins.Top * 100}in</MarginTop> <MarginLeft>{pageSettings.Margins.Left * 100}in</MarginLeft> <MarginRight>{pageSettings.Margins.Right * 100}in</MarginRight> <MarginBottom>{pageSettings.Margins.Bottom * 100}in</MarginBottom> </DeviceInfo>"; Warning[] warnings; var streams = new List <Stream>(); var currentPageIndex = 0; report.Render("Image", deviceInfo, (name, fileNameExtension, encoding, mimeType, willSeek) => { var stream = new MemoryStream(); streams.Add(stream); return(stream); }, out warnings); foreach (Stream stream in streams) { stream.Position = 0; } if (streams == null || streams.Count == 0) { throw new Exception("Error: no stream to print."); } var printDocument = new PrintDocument(); printDocument.DefaultPageSettings = pageSettings; if (!printDocument.PrinterSettings.IsValid) { throw new Exception("Error: cannot find the default printer."); } else { printDocument.PrintPage += (sender, e) => { Metafile pageImage = new Metafile(streams[currentPageIndex]); Rectangle adjustedRect = new Rectangle( e.PageBounds.Left - (int)e.PageSettings.HardMarginX, e.PageBounds.Top - (int)e.PageSettings.HardMarginY, e.PageBounds.Width, e.PageBounds.Height); e.Graphics.FillRectangle(Brushes.White, adjustedRect); e.Graphics.DrawImage(pageImage, adjustedRect); currentPageIndex++; e.HasMorePages = (currentPageIndex < streams.Count); e.Graphics.DrawRectangle(Pens.Red, adjustedRect); }; printDocument.EndPrint += (Sender, e) => { if (streams != null) { foreach (Stream stream in streams) { stream.Close(); } streams = null; } }; printDocument.Print(); } }
// Main static void Main(string[] args) { try { // enable HTML5 etc (assuming we're running IE9+) SetFeatureBrowserFeature("FEATURE_BROWSER_EMULATION", 9000); // force software rendering SetFeatureBrowserFeature("FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI", 0); SetFeatureBrowserFeature("FEATURE_GPU_RENDERING", 0); using (var apartment = new MessageLoopApartment()) { // create WebBrowser on a seprate thread with its own message loop var webBrowser = apartment.Invoke(() => new WebBrowser()); // navigate and wait for the result apartment.Invoke(() => { var pageLoadedTcs = new TaskCompletionSource <bool>(); webBrowser.DocumentCompleted += (s, e) => pageLoadedTcs.TrySetResult(true); webBrowser.DocumentText = HTML; return(pageLoadedTcs.Task); }).Wait(); // save the picture apartment.Invoke(() => { webBrowser.Size = IMAGE_SIZE; var rectangle = new Rectangle(0, 0, webBrowser.Width, webBrowser.Height); // get reference DC using (var screenGraphics = webBrowser.CreateGraphics()) { var screenHdc = screenGraphics.GetHdc(); // create a metafile using (var metafile = new Metafile(screenHdc, rectangle, MetafileFrameUnit.Pixel)) { using (var graphics = Graphics.FromImage(metafile)) { var hdc = graphics.GetHdc(); var rect = new Rectangle(0, 0, 320, 50); OleDraw(webBrowser.ActiveXInstance, DVASPECT_CONTENT, hdc, ref rectangle); graphics.ReleaseHdc(hdc); } // save the metafile as bitmap metafile.Save(FILE_NAME, ImageFormat.Png); } screenGraphics.ReleaseHdc(screenHdc); } }); // dispose of webBrowser apartment.Invoke(() => webBrowser.Dispose()); webBrowser = null; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public static bool SaveAndConvert(Image image, Stream stream, ImageFormat format) { if (image == null) { return(false); } if (format == ImageFormat.Jpeg || format == ImageFormat.Gif || format == ImageFormat.Tiff || format == ImageFormat.Bmp || format == ImageFormat.Png || format == ImageFormat.MemoryBmp) { if (image is Bitmap) { if (format == ImageFormat.MemoryBmp) { throw new Exception(Res.Get("Export,Image,ImageParceFormatException")); } image.Save(stream, format); return(true); } //from mf to bitmap using (Metafile metafile = image as Metafile) using (Bitmap bitmap = new Bitmap(image.Width, image.Height)) { bitmap.SetResolution(96F, 96F); using (Graphics g = Graphics.FromImage(bitmap)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.DrawImage(metafile, 0, 0, (float)image.Width, (float)image.Height); g.Dispose(); } bitmap.Save(stream, format); } return(true); } else if (format == ImageFormat.Icon) { return(SaveAsIcon(image, stream, true)); } else if (format == ImageFormat.Wmf || format == ImageFormat.Emf) { if (image is Metafile) { Metafile emf = null; using (Bitmap bmp = new Bitmap(1, 1)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); emf = new Metafile(stream, hdc); g.ReleaseHdc(hdc); } using (Graphics g = Graphics.FromImage(emf)) { g.DrawImage(image, 0, 0); } return(true); } } //throw new Exception(Res.Get("Export,Image,ImageParceFormatException")); // we cant convert image to exif or from bitmap to mf return(false); }
/* TODO(zsv): Need to find an appropriate icon in the general style * for the main toolbar - screenshot capture for windows with charts. */ public void SaveSnapshot(string fileName) { string ext = FileHelper.GetFileExtension(fileName); ExtSize imageSize = GetImageSize(); if (ext == ".svg") { var prevRenderer = fRenderer; SetRenderer(new SVGRenderer(fileName, imageSize.Width, imageSize.Height)); fRenderer.BeginDrawing(); try { using (var gfx = CreateGraphics()) { fRenderer.SetTarget(gfx); RenderImage(RenderTarget.SVG); } } finally { fRenderer.EndDrawing(); SetRenderer(prevRenderer); } return; } if ((ext == ".bmp" || ext == ".jpg") && imageSize.Width >= 65535) { AppHost.StdDialogs.ShowError(LangMan.LS(LSID.LSID_TooMuchWidth)); } else { ImageFormat imFmt = ImageFormat.Png; if (ext == ".bmp") { imFmt = ImageFormat.Bmp; } else if (ext == ".emf") { imFmt = ImageFormat.Emf; } else if (ext == ".png") { imFmt = ImageFormat.Png; } else if (ext == ".gif") { imFmt = ImageFormat.Gif; } else if (ext == ".jpg") { imFmt = ImageFormat.Jpeg; } Image pic; if (Equals(imFmt, ImageFormat.Emf)) { using (var gfx = CreateGraphics()) { pic = new Metafile(fileName, gfx.GetHdc()); } } else { pic = new Bitmap(imageSize.Width, imageSize.Height, PixelFormat.Format24bppRgb); } try { using (Graphics gfx = Graphics.FromImage(pic)) { fRenderer.SetTarget(gfx); RenderImage(RenderTarget.RasterFile); } pic.Save(fileName, imFmt); } finally { pic.Dispose(); } } }
public void Static_GetMetafileHeader_Stream_Null() { Assert.Throws <NullReferenceException> (() => Metafile.GetMetafileHeader((Stream)null)); }
/// <summary> /// Copies the given <see cref="T:System.Drawing.Imaging.MetaFile" /> to the clipboard. /// The given <see cref="T:System.Drawing.Imaging.MetaFile" /> is set to an invalid state inside this function. /// </summary> static public bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile metafile) { return(PutEnhMetafileOnClipboard(hWnd, metafile, true)); }
public void Static_GetMetafileHeader_Filename_Null() { Assert.Throws <ArgumentNullException> (() => Metafile.GetMetafileHeader((string)null)); }
protected virtual void doc_PrintPage(object sender, PrintPageEventArgs e) { //如果允许分页,则打印每一页,否则则打印当前页 if (_baseDoc.PagerSetting.AllowPage) { _baseDoc.PageIndexChanged(_baseDoc.PagerSetting.PagerDesc[_pageIndex].PageIndex, _baseDoc.PagerSetting.PagerDesc[_pageIndex].IsMain, _baseDoc.DataSource); } //创建 metafile _printMetafile = GetPageMetafile(); //_printMetafile.Save(@"D:\printMetafile0.emf"); //调整边距 Rectangle rect = new Rectangle(0, 0, _printMetafile.Width, _printMetafile.Height); double widthZoom = 1; double heightZoom = 1; double widthSize = (e.MarginBounds.Width); double heightSize = (e.MarginBounds.Height); if (widthSize < rect.Width) { widthZoom = widthSize / rect.Width; } //纵轴缩小 if (heightSize < rect.Height) { heightZoom = heightSize / rect.Height; } double zoom = (widthZoom < heightZoom) ? widthZoom : heightZoom; Rectangle zoomRect = new Rectangle(rect.X, rect.Y, (int)(rect.Width * zoom), (int)(rect.Height * zoom)); MemoryStream mStream = new MemoryStream(); Graphics ggggg = _baseDoc.CreateGraphics(); IntPtr ipHdctemp = ggggg.GetHdc(); Metafile mf = new Metafile(mStream, ipHdctemp); ggggg.ReleaseHdc(ipHdctemp); ggggg.Dispose(); Graphics gMf = Graphics.FromImage(mf); gMf.DrawImage(_printMetafile, zoomRect); gMf.Save(); gMf.Dispose(); _printMetafile = mf; //_printMetafile.Save(@"D:\printMetafile1.emf"); metafileDelegate = new Graphics.EnumerateMetafileProc(MetafileCallback); //开始正式打印 PrintPage(_printMetafile, e, zoomRect.Width, zoomRect.Height); metafileDelegate = null; _pageIndex++; if (_pageFromHeight) { Rectangle r = GetPrintRect(); if ((_pageIndex) * _pagePrintHeight < r.Height) { e.HasMorePages = true; } } else { if (_baseDoc.PagerSetting.AllowPage && _pageIndex < _baseDoc.PagerSetting.TotalPageCount) { e.HasMorePages = true; } else { _pageIndex = 0; } } }
public void Static_GetMetafileHeader_IntPtr_Zero() { Assert.Throws <ArgumentException> (() => Metafile.GetMetafileHeader(IntPtr.Zero)); }
/// <summary>转换源文件为目标文件</summary> public override bool Execute(string sourceFile, string destFile, Size size) { var meta = new Metafile(sourceFile); return(base.Execute(meta, sourceFile, destFile, size)); }
public void Metafile_String() { string filename = WmfPlaceable; Metafile mf = new Metafile(filename); Metafile clone = (Metafile)mf.Clone(); }