///<summary>Draw to the chart's built-in PrintDocument, then set the PrintPreviewController's document to that PrintDocument. ///Besides keeping everything synchronized, this makes it easier to display the print preview and show the printer settings window ///when the user clicks Print.</summary> private void MakePage() { //update private variables FillDimensions(); //check to see if landscape mode was toggled. _chartCur.Printing.PrintDocument.DefaultPageSettings.Landscape = checkLandscape.Checked; //reset the document margins _chartCur.Printing.PrintDocument.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(_marginWidth, _marginWidth, _marginHeight, _marginHeight); //Reset the graphics objects by disposing of them and reinitializing them. if (_bmpSheet != null) { _bmpSheet.Dispose(); } if (_xg != null) { _xg.Dispose(); } if (_g != null) { _g.Dispose(); } _bmpSheet = new Bitmap(_pageWidth, _pageHeight); _g = Graphics.FromImage(_bmpSheet); _xg = XGraphics.FromGraphics(_g, new XSize(_bmpSheet.Width, _bmpSheet.Height)); //draw both the chart and legend to bitmaps using (Bitmap chartbmp = new Bitmap(_chartCur.Width, _chartCur.Height)) using (Bitmap legendbmp = new Bitmap(_legend.Width, _legend.Height)) { _chartCur.DrawToBitmap(chartbmp, new Rectangle(0, 0, _chartCur.Width, _chartCur.Height)); _legend.DrawToBitmap(legendbmp, new Rectangle(0, 0, _legend.Width, _legend.Height)); //draw both bitmaps to another bitmap for the whole sheet. _xg.DrawImage(legendbmp, _xPos + _marginWidth, _yPos + _marginHeight + chartbmp.Height, _legend.Width, _legend.Height); _xg.DrawImage(chartbmp, _xPos + _marginWidth, _yPos + _marginHeight, _chartCur.Width, _chartCur.Height); } printPreviewControl.Document = _chartCur.Printing.PrintDocument; }
bool StoreTempImage(string fileName) { try { float resolution = 300; int horzPixels = (int)(GetShapeWidth().Inch *resolution); int vertPixels = (int)(GetShapeHeight().Inch *resolution); Bitmap bmp = new Bitmap(horzPixels, vertPixels); // Always renders to a Bitmap for embedding in output. XGraphics gfx = XGraphics.FromGraphics(Graphics.FromImage(bmp), new XSize(horzPixels, vertPixels)); //REM: Should not be necessary: gfx.ScaleTransform(resolution / 72); //gfx.PageUnit = XGraphicsUnit.Point; DocumentRenderer renderer = new DocumentRenderer(this.chart.Document); renderer.RenderObject(gfx, 0, 0, GetShapeWidth().Point, this.chart); bmp.SetResolution(resolution, resolution); bmp.Save(fileName, ImageFormat.Png); } catch (Exception) { return(false); } return(true); }
bool StoreTempImage(string fileName) { try { const float resolution = 96; int horzPixels = (int)(GetShapeWidth().Inch *resolution); int vertPixels = (int)(GetShapeHeight().Inch *resolution); Bitmap bmp = new Bitmap(horzPixels, vertPixels); #if true XGraphics gfx = XGraphics.CreateMeasureContext(new XSize(horzPixels, vertPixels), XGraphicsUnit.Point, XPageDirection.Downwards); #else #if GDI XGraphics gfx = XGraphics.FromGraphics(Graphics.FromImage(bmp), new XSize(horzPixels, vertPixels)); #endif #if WPF // TODOWPF XGraphics gfx = null; //XGraphics.FromGraphics(Graphics.FromImage(bmp), new XSize(horzPixels, vertPixels)); #endif #endif //REM: Should not be necessary: gfx.ScaleTransform(resolution / 72); //gfx.PageUnit = XGraphicsUnit.Point; DocumentRenderer renderer = new DocumentRenderer(_chart.Document); renderer.RenderObject(gfx, 0, 0, GetShapeWidth().Point, _chart); bmp.SetResolution(resolution, resolution); bmp.Save(fileName, ImageFormat.Png); } catch (Exception) { return(false); } return(true); }
/// <summary> /// Prepares this instance for rendering. /// </summary> public void PrepareDocument() { PdfFlattenVisitor visitor = new PdfFlattenVisitor(); visitor.Visit(_document); _previousListNumbers = new Dictionary <ListType, int>(3); _previousListNumbers[ListType.NumberList1] = 0; _previousListNumbers[ListType.NumberList2] = 0; _previousListNumbers[ListType.NumberList3] = 0; _formattedDocument = new FormattedDocument(_document, this); //REM: Size should not be necessary in this case. #if true XGraphics gfx = XGraphics.CreateMeasureContext(new XSize(2000, 2000), XGraphicsUnit.Point, XPageDirection.Downwards); #else #if GDI XGraphics gfx = XGraphics.FromGraphics(Graphics.FromHwnd(IntPtr.Zero), new XSize(2000, 2000)); #endif #if WPF XGraphics gfx = XGraphics.FromDrawingContext(null, new XSize(2000, 2000), XGraphicsUnit.Point); #endif #endif // _previousListNumber = int.MinValue; //gfx.MUH = _unicode; //gfx.MFEH = _fontEmbedding; _previousListInfo = null; _formattedDocument.Format(gfx); }
public void PrintLegend(System.Drawing.Graphics g, Leyenda legend) { g.PageUnit = System.Drawing.GraphicsUnit.Point; XGraphics gfx = XGraphics.FromGraphics(g, XSize.FromSize(PageSizeConverter.ToSize(PageSize.A4))); this.CreateLegend(gfx, legend); gfx.Dispose(); }
public void Print(System.Drawing.Graphics g) { g.PageUnit = System.Drawing.GraphicsUnit.Point; XGraphics gfx = XGraphics.FromGraphics(g, XSize.FromSize(PageSizeConverter.ToSize(_layout.Size))); this.Render(gfx); gfx.Dispose(); }
/// <summary> /// Creates a meta file from the current page. /// </summary> private void miMetaFile_Click(object sender, EventArgs e) { int page = this.pagePreview.Page; // Reuse the renderer from the preview DocumentRenderer renderer = this.pagePreview.Renderer; PageInfo info = renderer.FormattedDocument.GetPageInfo(page); // Create an image float dx, dy; if (info.Orientation == PdfSharp.PageOrientation.Portrait) { dx = (float)(info.Width.Inch * 72); dy = (float)(info.Height.Inch * 72); } else { dx = (float)(info.Height.Inch * 72); dy = (float)(info.Width.Inch * 72); } // Create a graphics object as reference Graphics graphicsDisplay = CreateGraphics(); IntPtr hdc = graphicsDisplay.GetHdc(); // There is a little difference between the display resolution (i.g. 96 DPI) and the real physical solution of the display. // This must be taken into account... DeviceInfos devInfo = DeviceInfos.GetInfos(hdc); // Create the metafile Metafile metafile = new Metafile("test.emf", hdc, new RectangleF(0, 0, devInfo.ScaleX * dx, devInfo.ScaleY * dy), MetafileFrameUnit.Point); graphicsDisplay.ReleaseHdc(hdc); graphicsDisplay.Dispose(); // Create a Graphics object for the metafile and scale it for drawing with 72 dpi Graphics graphics = Graphics.FromImage(metafile); graphics.Clear(System.Drawing.Color.White); //graphics.PageUnit = GraphicsUnit.Point; ??? graphics.ScaleTransform(graphics.DpiX / 72, graphics.DpiY / 72); // Check if size is correct graphics.DrawLine(Pens.Red, 0, 0, dx, dy); // Create an XGraphics object and render the page XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point)); renderer.RenderPage(gfx, page); gfx.Dispose(); metafile.Dispose(); Process.Start("test.emf"); }
/// <summary> /// Draws the page on the printer. /// </summary> private void PrintPage(object sender, PrintPageEventArgs ev) { Graphics graphics = ev.Graphics; graphics.PageUnit = GraphicsUnit.Point; XGraphics gfx = XGraphics.FromGraphics(graphics, PageSizeConverter.ToSize(PageSize.A4)); if (this.renderEvent != null) { this.renderEvent(gfx); } ev.HasMorePages = false; }
/// <summary> /// print the page, either to PDF or to the screen /// </summary> /// <param name="ASender"></param> /// <param name="AEv"></param> protected override void PrintPage(Object ASender, PrintPageEventArgs AEv) { // only use the AEv.Graphics if we display on screen if (FEv != AEv) { FEv = AEv; FEv.Graphics.PageUnit = GraphicsUnit.Inch; FEv.Graphics.TranslateTransform(0, 0); FXGraphics = XGraphics.FromGraphics(AEv.Graphics, PageSizeConverter.ToSize(PageSize.A4)); InitFontsAndPens(); } base.PrintPage(ASender, AEv); }
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e) { var page = _printPageCount++; var rawSize = GetSize(e); var unitSize = GetSize(rawSize); var scale = GetScale(unitSize); var actualPaperMargin = GetActual(e); var gfx = XGraphics.FromGraphics(e.Graphics, rawSize, XGraphicsUnit.Point); gfx.ScaleTransform(scale); DoRenderStuff(new MyGraphics(gfx), new XRect(unitSize), false, page, _template.SectionList.Sum(x => x.GetRenderPageCount()), _includeBackgroundObjects, actualPaperMargin); }
private bool SaveAsJPEG(string filePath) { try { int page = preview.Page; // Reuse the renderer from the preview DocumentRenderer renderer = preview.Renderer; PageInfo info = renderer.FormattedDocument.GetPageInfo(page); // Create an image int dx, dy; if (info.Orientation == PdfSharp.PageOrientation.Portrait) { dx = (int)(info.Width.Inch * DPI); dy = (int)(info.Height.Inch * DPI); } else { dx = (int)(info.Height.Inch * DPI); dy = (int)(info.Width.Inch * DPI); } System.Drawing.Image image = new Bitmap(dx, dy, PixelFormat.Format32bppRgb); // Create a Graphics object for the image and scale it for drawing with 72 dpi Graphics graphics = Graphics.FromImage(image); graphics.Clear(System.Drawing.Color.White); float scale = DPI / 72f; graphics.ScaleTransform(scale, scale); // Create an XGraphics object and render the page XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point)); renderer.RenderPage(gfx, page); gfx.Dispose(); image.Save(filePath, ImageFormat.Jpeg); return(true); } catch { return(false); } }
static void CreatePngFromPdf(Document document, PdfDocumentRenderer renderer) { int page = 1; // Reuse the renderer from the preview DocumentRenderer renderer2 = new DocumentRenderer(document); renderer2.PrepareDocument(); PageInfo info = renderer.DocumentRenderer.FormattedDocument.GetPageInfo(page); // Create an image int dpi = 150; int dx, dy; if (info.Orientation == PdfSharp.PageOrientation.Portrait) { dx = (int)(info.Width.Inch * dpi); dy = (int)(info.Height.Inch * dpi); } else { dx = (int)(info.Height.Inch * dpi); dy = (int)(info.Width.Inch * dpi); } //Create image object from the PDF //UGLY HACK: divide width by 3 to create only 1 label Image image = new Bitmap(dx / 3, dy, PixelFormat.Format32bppRgb); // Create a Graphics object for the image and scale it for drawing with 72 dpi Graphics graphics = Graphics.FromImage(image); graphics.Clear(System.Drawing.Color.White); float scale = dpi / 72f; graphics.ScaleTransform(scale, scale); // Create an XGraphics object and render the page XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point)); renderer2.RenderPage(gfx, page); gfx.Dispose(); image.Save("test.png", ImageFormat.Png); }
/// <summary> /// Prepares new bitmap image for drawing. /// </summary> public void BeginImage() { #if GDI int factor = 2; int width = (int)(WidthInPoint * factor); int height = (int)(HeightInPoint * factor); this.image = new Bitmap(width, height); this.image.SetResolution(72 * factor, 72 * factor); this.gdiGfx = Graphics.FromImage(this.image); this.gdiGfx.SmoothingMode = SmoothingMode.HighQuality; // Draw a bounding box Rectangle rect = new Rectangle(0, 0, width - 1, height - 1); this.gdiGfx.FillRectangle(Brushes.WhiteSmoke, rect); //this.gdiGfx.DrawRectangle(new Pen(Brushes.LightGray, factor), rect); this.gdiGfx.ScaleTransform(factor, factor); this.imgGfx = XGraphics.FromGraphics(this.gdiGfx, new XSize(WidthInPoint, HeightInPoint), XGraphicsUnit.Point); #endif #if WPF int factor = 4; int width = (int)(WidthInPoint * factor); int height = (int)(HeightInPoint * factor); this.image = new RenderTargetBitmap(width, height, 72 * factor, 72 * factor, PixelFormats.Default); this.dv = new DrawingVisual(); this.dc = this.dv.RenderOpen(); // Draw a bounding box //Rect rect = new Rect(0, 0, width - 1, height - 1); Rect rect = new Rect(0, 0, WidthInPoint * 4 / 3 - 1, HeightInPoint * 4 / 3 - 1); //this.dc.DrawRectangle(Brushes.WhiteSmoke, new Pen(Brushes.LightGray, 1), rect); this.dc.DrawRectangle(Brushes.WhiteSmoke, null, rect); //double d = 10; //Pen pen = new Pen(Brushes.Red, 5); //this.dc.DrawLine(pen, rect.TopLeft, rect.TopLeft + new Vector(d, d)); //this.dc.DrawLine(pen, rect.TopRight, rect.TopRight + new Vector(-d, d)); //this.dc.DrawLine(pen, rect.BottomLeft, rect.BottomLeft + new Vector(d, -d)); //this.dc.DrawLine(pen, rect.BottomRight, rect.BottomRight + new Vector(-d, -d)); //this.dc.PushTransform(new ScaleTransform(factor, factor)); this.imgGfx = XGraphics.FromDrawingContext(this.dc, new XSize(WidthInPoint, HeightInPoint), XGraphicsUnit.Point); #endif }
/// <summary> /// Creates an image from the current page. /// </summary> private void miBmp_Click(object sender, System.EventArgs e) { int page = this.pagePreview.Page; // Reuse the renderer from the preview DocumentRenderer renderer = this.pagePreview.Renderer; PageInfo info = renderer.FormattedDocument.GetPageInfo(page); // Create an image int dpi = 150; int dx, dy; if (info.Orientation == PdfSharp.PageOrientation.Portrait) { dx = (int)(info.Width.Inch * dpi); dy = (int)(info.Height.Inch * dpi); } else { dx = (int)(info.Height.Inch * dpi); dy = (int)(info.Width.Inch * dpi); } Image image = new Bitmap(dx, dy, PixelFormat.Format32bppRgb); // Create a Graphics object for the image and scale it for drawing with 72 dpi Graphics graphics = Graphics.FromImage(image); graphics.Clear(System.Drawing.Color.White); float scale = dpi / 72f; graphics.ScaleTransform(scale, scale); // Create an XGraphics object and render the page XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point)); renderer.RenderPage(gfx, page); gfx.Dispose(); image.Save("test.png", ImageFormat.Png); Process.Start("mspaint", "test.png"); // Use MSPaint, not Photoshop... }
///<summary>Draw to the chart's built-in PrintDocument, then set the PrintPreviewController's document to that PrintDocument. ///Besides keeping everything synchronized, this makes it easier to display the print preview and show the printer settings window ///when the user clicks Print.</summary> private void MakePage(bool createBitmap) { //check to see if landscape mode was toggled. printDocument1.DefaultPageSettings.Landscape = checkLandscape.Checked; //update private variables FillDimensions(); if (createBitmap) { if (_bmpImage != null) { _bmpImage.Dispose(); } _bmpImage = ConvertToBmp(false); } Graphics g = Graphics.FromImage(_bmpImage); //reset the document margins printDocument1.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(_marginWidth, _marginWidth, _marginHeight, _marginHeight); //Reset the graphics objects by disposing of them and reinitializing them. if (_bmpSheet != null) { _bmpSheet.Dispose(); } if (_xg != null) { _xg.Dispose(); } if (_g != null) { _g.Dispose(); } _bmpSheet = new Bitmap(PageDimensions.Width, PageDimensions.Height); _g = Graphics.FromImage(_bmpSheet); _xg = XGraphics.FromGraphics(_g, new XSize(_bmpSheet.Width, _bmpSheet.Height)); //margins are taken care of because we set them up in DefaultPageSettings. _xg.DrawImage(_bmpImage, _xPos, _yPos, _imageWidth, _imageHeight); printPreviewControl.Document = printDocument1; }
/// <summary> /// Raises the <see cref="E:System.Drawing.Printing.PrintDocument.PrintPage"/> event. It is called before a page prints. /// </summary> /// <param name="e">A <see cref="T:System.Drawing.Printing.PrintPageEventArgs"/> that contains the event data.</param> protected override void OnPrintPage(PrintPageEventArgs e) { base.OnPrintPage(e); if (!e.Cancel) { PageSettings settings = e.PageSettings; try { Graphics graphics = e.Graphics; IntPtr hdc = graphics.GetHdc(); int xOffset = GetDeviceCaps(hdc, PHYSICALOFFSETX); int yOffset = GetDeviceCaps(hdc, PHYSICALOFFSETY); graphics.ReleaseHdc(hdc); graphics.TranslateTransform(-xOffset * 100 / graphics.DpiX, -yOffset * 100 / graphics.DpiY); // Recall: Width and Height are exchanged when settings.Landscape is true. XSize size = new XSize(e.PageSettings.Bounds.Width / 100.0 * 72, e.PageSettings.Bounds.Height / 100.0 * 72); float scale = 100f / 72f; graphics.ScaleTransform(scale, scale); // draw line A4 portrait //graphics.DrawLine(Pens.Red, 0, 0, 21f / 2.54f * 72, 29.7f / 2.54f * 72); #if WPF //#warning TODO WPFPDF // TODO WPFPDF #else XGraphics gfx = XGraphics.FromGraphics(graphics, size); this.renderer.RenderPage(gfx, this.pageNumber); #endif } catch { e.Cancel = true; } this.pageNumber++; this.pageCount--; e.HasMorePages = this.pageCount > 0; } }
protected override void OnPaint(PaintEventArgs e) { if (DesignMode) { e.Graphics.Clear(Settings.Color[Colors.Canvas]); return; } foreach (var element in Project.Current.Elements) { element.Flagged = false; } foreach (var element in Canvas.SelectedElements) { element.Flagged = true; } using (var nativeGraphics = Graphics.FromHdc(e.Graphics.GetHdc())) { using (var graphics = XGraphics.FromGraphics(nativeGraphics, new XSize(Width, Height))) { using (var palette = new Palette()) { var clientArea = new Rectangle(0, 0, Width, Height); ControlPaint.DrawBorder3D(nativeGraphics, clientArea, Border3DStyle.Raised); clientArea.Inflate(-OuterBorderSize, -OuterBorderSize); nativeGraphics.FillRectangle(SystemBrushes.Control, clientArea); clientArea.Inflate(-OuterPadding, -OuterPadding); ControlPaint.DrawBorder3D(nativeGraphics, clientArea, Border3DStyle.SunkenOuter); clientArea.Inflate(-InnerBorderSize, -InnerBorderSize); nativeGraphics.FillRectangle(palette.CanvasBrush, clientArea); clientArea.Inflate(-InnerPadding, -InnerPadding); //nativeGraphics.FillRectangle(Brushes.Cyan, clientArea); var canvasBounds = Canvas != null?Canvas.ComputeCanvasBounds(false) : Rect.Empty; var borderPen = palette.Pen(Settings.Color[Colors.Border], 0); foreach (var element in Project.Current.Elements) { if (element is Room) { var room = (Room)element; var roomBounds = CanvasToClient(room.InnerBounds.ToRectangleF(), canvasBounds, clientArea); graphics.DrawRectangle(borderPen, room.Flagged ? palette.BorderBrush : palette.FillBrush, roomBounds); } } if (Canvas != null) { // draw the viewport area as a selectable "handle" var viewportBounds = CanvasToClient(Canvas.Viewport.ToRectangleF(), canvasBounds, clientArea); viewportBounds.Intersect(clientArea); if (Project.Current.Elements.Count > 0) { var context = new DrawingContext(1f); context.Selected = m_draggingViewport; Drawing.DrawHandle(Canvas, graphics, palette, new Rect(viewportBounds), context, true, false); } } } } } e.Graphics.ReleaseHdc(); base.OnPaint(e); }
private void FileExportImageMenuItem_Click(object sender, EventArgs e) { using (var dialog = new SaveFileDialog()) { dialog.Filter = "PNG Images|*.png|JPEG Images|*.jpg|BMP Images|*.bmp|Enhanced Metafiles (EMF)|*.emf|All Files|*.*||"; dialog.Title = "Export Image"; dialog.InitialDirectory = PathHelper.SafeGetDirectoryName(Settings.LastExportImageFileName); if (dialog.ShowDialog() == DialogResult.OK) { Settings.LastExportImageFileName = dialog.InitialDirectory; var format = ImageFormat.Png; var ext = Path.GetExtension(dialog.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 = m_canvas.ComputeCanvasBounds(true).Size *m_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(m_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))) { m_canvas.Draw(graphics, true, size.X, size.Y); } } var handle = metafile.GetHenhmetafile(); var copy = CopyEnhMetaFile(handle, dialog.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))) { m_canvas.Draw(graphics, true, size.X, size.Y); } } bitmap.Save(dialog.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); } } } }
internal bool RenderPage(Graphics gfx) { //delete m_RenderContext; //m_RenderContext = new HdcRenderContext(wdc.m_hdc); gfx.TranslateTransform(-_posOffset.X, -_posOffset.Y); gfx.SetClip(new Rectangle(_virtualPage.X + 1, _virtualPage.Y + 1, _virtualPage.Width - 1, _virtualPage.Height - 1)); float scaleX = _virtualPage.Width / _pageSize.Width; float scaleY = _virtualPage.Height / _pageSize.Height; //gfx.SetSmoothingMode(SmoothingModeAntiAlias); //PaintBackground(gfx); #if DRAW_BMP Matrix matrix = new Matrix(); matrix.Translate(virtualPage.X, virtualPage.Y); matrix.Translate(-posOffset.X, -this.posOffset.Y); //matrix.Scale(scaleX, scaleY); gfx.Transform = matrix; #if DRAW_X gfx.DrawLine(Pens.Red, 0, 0, pageSize.Width, pageSize.Height); gfx.DrawLine(Pens.Red, 0, pageSize.Height, pageSize.Width, 0); #endif if (renderEvent != null) { Bitmap bmp = new Bitmap(virtualPage.Width, this.virtualPage.Height, gfx); Graphics gfx2 = Graphics.FromImage(bmp); gfx2.Clear(pageColor); gfx2.ScaleTransform(scaleX, scaleY); gfx2.SmoothingMode = SmoothingMode.HighQuality; XGraphics xgfx = XGraphics.FromGraphics(gfx2, new XSize(pageSize.Width, this.pageSize.Height)); try { renderEvent(xgfx); gfx.DrawImage(bmp, 0, 0); } finally { bmp.Dispose(); } } #else Matrix matrix = new Matrix(); matrix.Translate(_virtualPage.X, _virtualPage.Y); matrix.Translate(-_posOffset.X, -_posOffset.Y); matrix.Scale(scaleX, scaleY); gfx.Transform = matrix; #if DRAW_X gfx.DrawLine(Pens.Red, 0, 0, pageSize.Width, pageSize.Height); gfx.DrawLine(Pens.Red, 0, pageSize.Height, pageSize.Width, 0); #endif if (_renderAction != null) { gfx.SmoothingMode = SmoothingMode.HighQuality; XGraphics xgfx = XGraphics.FromGraphics(gfx, new XSize(_pageSize.Width, _pageSize.Height), PageGraphicsUnit); try { _renderAction(xgfx); } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception"); } } #endif // Old C++ stuff, may be useful later... #if false switch (m_mode) { case RenderModeDirect: { delete m_PreviewMetafile; m_PreviewMetafile = NULL; float cxPage = Metric::MillimetersToPoints(m_dimPage.cx / 10.0f); float cyPage = Metric::MillimetersToPoints(m_dimPage.cy / 10.0f); float scaleX = virtualPage.Width / cxPage; float scaleY = virtualPage.Height / cyPage; Graphics gfx(m_RenderContext); gfx.SetSmoothingMode(SmoothingModeAntiAlias); PaintBackground(gfx, &virtualPage); Matrix matrix; matrix.Translate((float)virtualPage.X, (float)virtualPage.Y); matrix.Translate((float)-m_posOffset.x, (float)-m_posOffset.y); matrix.Scale(scaleX, scaleY); m_RenderContext->SetDefaultViewMatrix(&matrix); gfx.ResetTransform(); if (m_PreviewRenderer && m_PreviewRenderer->CanRender()) { m_PreviewRenderer->Render(&gfx, m_Page); } } break; case RenderModeMetafile: { Graphics gfx(m_RenderContext); if (m_PreviewMetafile == NULL) { float cxPage = Metric::MillimetersToPoints(m_dimPage.cx / 10.0f); float cyPage = Metric::MillimetersToPoints(m_dimPage.cy / 10.0f); //float factor = 72.0f / 96.0f; Rect rcLogicalPage(0, 0, (int)cxPage, (int)cyPage); RectF rcFLogicalPage(0, 0, cxPage, cyPage); //DeviceName devname; //DESKTOP::QueryDefaultPrinter(devname); //HACK DRUCKER MUSS DA SEIN! //DeviceMode devmode(devname); //HDC hdc = ::CreateIC(devname.m_szDriver, devname.m_szDevice, devname.m_szOutput, devmode.m_pdm); //HDC hdc = m_Graphics->GetHDC(); //HDC hdc = ::GetDC(NULL); HDC hdc = ::CreateIC("DISPLAY", NULL, NULL, NULL); float dpiX = gfx.GetDpiX(); float dpiY = gfx.GetDpiY(); // Even Petzold would be surprised about that... // Display | LaserJet // DPI 96 : 120 | 300 // physical device size in MM --------------------------------------------- int horzSizeMM = ::GetDeviceCaps(hdc, HORZSIZE); // = 330 : 254 | 198 (not 210) int vertSizeMM = ::GetDeviceCaps(hdc, VERTSIZE); // = 254 : 203 | 288 (hot 297) // device size in pixel int horzSizePixel = ::GetDeviceCaps(hdc, HORZRES); // = 1280 : 1280 | 4676 int vertSizePixel = ::GetDeviceCaps(hdc, VERTRES); // = 1024 : 1024 | 6814 // 'logical' device resolution in DPI int logResX = ::GetDeviceCaps(hdc, LOGPIXELSX); // = 96 : 120 | 600 int logResY = ::GetDeviceCaps(hdc, LOGPIXELSY); // = 96 : 120 | 600 // physical pixel size in .01 MM units // accidentally(?) the result of GetPhysicalDimension! //float X1 = 100.0f * horzSizeMM / horzSizePixel; // = 25.781250 : 19.843750 | 4.2343884 //float Y1 = 100.0f * vertSizeMM / vertSizePixel; // = 24.804688 : 19.824219 | 4.2265925 // now we can get the 'physical' device resolution... float phyResX = horzSizePixel / (horzSizeMM / 25.4f); // = 98.521210 : 128.00000 | 599.85052 float phyResY = vertSizePixel / (vertSizeMM / 25.4f); // = 102.40000 : 128.12611 | 600.95691 // ...and rescale the size of the meta rectangle. float magicX = logResX / phyResX; // = 0.97440946 : 0.93750000 | 1.0002491 float magicY = logResY / phyResY; // = 0.93750000 : 0.93657720 | 0.99840766 // use A4 page in point // adjust size of A4 page so that meta file fits with DrawImage... RectF rcMagic(0, 0, magicX *cxPage, magicY *cyPage); m_PreviewMetafile = new Metafile(hdc, rcMagic, MetafileFrameUnitPoint, EmfTypeEmfPlusOnly, L"some description"); SizeF size; float horzRes, vertRes; float height, width; MetafileHeader metafileHeader; // GetPhysicalDimension returns physical size of a pixel in .01 MM units!! m_PreviewMetafile->GetPhysicalDimension(&size); horzRes = (float)m_PreviewMetafile->GetHorizontalResolution(); vertRes = (float)m_PreviewMetafile->GetVerticalResolution(); height = (float)m_PreviewMetafile->GetHeight(); width = (float)m_PreviewMetafile->GetWidth(); m_PreviewMetafile->GetMetafileHeader(&metafileHeader); Graphics gfxMf(m_PreviewMetafile); dpiX = gfxMf.GetDpiX(); dpiY = gfxMf.GetDpiY(); m_PreviewMetafile->GetPhysicalDimension(&size); horzRes = (float)m_PreviewMetafile->GetHorizontalResolution(); vertRes = (float)m_PreviewMetafile->GetVerticalResolution(); height = (float)m_PreviewMetafile->GetHeight(); width = (float)m_PreviewMetafile->GetWidth(); m_PreviewMetafile->GetMetafileHeader(&metafileHeader); gfxMf.SetPageUnit(UnitPoint); if (m_PreviewRenderer && m_PreviewRenderer->CanRender()) { m_PreviewRenderer->Render(&gfxMf, m_Page); } ::DeleteDC(hdc); } if (m_PreviewMetafile) { gfx.SetSmoothingMode(SmoothingModeAntiAlias); PaintBackground(gfx, &virtualPage); //Matrix matrix(1, 0, 0, 1, (float) - m_posOffset.x, (float) - m_posOffset.y); m_RenderContext->SetDefaultViewMatrix(&matrix); gfx.ResetTransform(); gfx.DrawImage(m_PreviewMetafile, virtualPage); } } break;
protected void ProduceResponse(string title, Render.RenderContext ctx, Size tileSize, int rot = 0, float translateX = 0, float translateY = 0, bool transparent = false) { // New-style Options // TODO: move to ParseOptions (maybe - requires options to be parsed after stylesheet creation?) if (GetBoolOption("sscoords", defaultValue: false)) { ctx.styles.hexCoordinateStyle = Stylesheet.HexCoordinateStyle.Subsector; } if (!GetBoolOption("routes", defaultValue: true)) { ctx.styles.macroRoutes.visible = false; ctx.styles.microRoutes.visible = false; } double devicePixelRatio = GetDoubleOption("dpr", 1); if (Accepts(MediaTypeNames.Application.Pdf)) { using (var document = new PdfDocument()) { document.Version = 14; // 1.4 for opacity document.Info.Title = title; document.Info.Author = "Joshua Bell"; document.Info.Creator = "TravellerMap.com"; document.Info.Subject = DateTime.Now.ToString("F", CultureInfo.InvariantCulture); document.Info.Keywords = "The Traveller game in all forms is owned by Far Future Enterprises. Copyright (C) 1977 - 2013 Far Future Enterprises. Traveller is a registered trademark of Far Future Enterprises."; // TODO: Credits/Copyright // This is close, but doesn't define the namespace correctly: // document.Info.Elements.Add( new KeyValuePair<string, PdfItem>( "/photoshop/Copyright", new PdfString( "HelloWorld" ) ) ); PdfPage page = document.AddPage(); // NOTE: only PageUnit currently supported in XGraphics is Points page.Width = XUnit.FromPoint(tileSize.Width); page.Height = XUnit.FromPoint(tileSize.Height); PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page); RenderToGraphics(ctx, rot, translateX, translateY, gfx); using (var stream = new MemoryStream()) { document.Save(stream, closeStream: false); SetCommonResponseHeaders(); Response.ContentType = MediaTypeNames.Application.Pdf; Response.AddHeader("content-length", stream.Length.ToString()); Response.AddHeader("content-disposition", "inline;filename=\"map.pdf\""); Response.BinaryWrite(stream.ToArray()); Response.Flush(); stream.Close(); } return; } } using (var bitmap = new Bitmap((int)Math.Floor(tileSize.Width * devicePixelRatio), (int)Math.Floor(tileSize.Height * devicePixelRatio), PixelFormat.Format32bppArgb)) { if (transparent) { bitmap.MakeTransparent(); } using (var g = Graphics.FromImage(bitmap)) { g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; using (var graphics = XGraphics.FromGraphics(g, new XSize(tileSize.Width * devicePixelRatio, tileSize.Height * devicePixelRatio))) { if (devicePixelRatio != 0) { graphics.ScaleTransform(devicePixelRatio); } RenderToGraphics(ctx, rot, translateX, translateY, graphics); } } SetCommonResponseHeaders(); BitmapResponse(ctx.styles, bitmap, transparent ? Util.MediaTypeName_Image_Png : null); } }
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); } }
public static void SaveTest() { XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); initialize(); PdfPage page = _document.AddPage(); XGraphics X = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend); page.Size = PageSize.A4; double width = page.Width; double height = page.Height; double top = _margins.Top; double bottom = _margins.Bottom; double left = _margins.Left; double right = _margins.Right * 2; double y = top; double x = left; XFont titleFont = new XFont("Calibri", 14F, XFontStyle.Bold, options); XFont fontW = new XFont("Calibri", 100F, XFontStyle.Regular, options); XFont fontQ = new XFont("Calibri", 12F, XFontStyle.Regular, options); XFont fontA = new XFont("Calibri", 11F, XFontStyle.Regular, options); var img = new Bitmap(1, 1); XGraphics E = XGraphics.FromGraphics(Graphics.FromImage(img), new XSize()); X.DrawStringML(_title, titleFont, XBrushes.Black, x, ref y, width - right); y += titleFont.GetHeight() + 20; X.DrawString("Date: " + _date, fontQ, Brushes.Black, width - right - 40, y); X.DrawString("First Name: ___________________", fontQ, Brushes.Black, x, y); y += fontQ.GetHeight() + 5; X.DrawString("Last Name: ___________________", fontQ, Brushes.Black, x, y); y += fontQ.GetHeight() + 5; X.DrawString("Class: ________", fontQ, Brushes.Black, x, y); y += fontQ.GetHeight() + 5; X.DrawString("Points:________", fontQ, Brushes.Black, x, y); y += fontQ.GetHeight() + 35; X.DrawString("Choose the correct answer. There might be more than one correct answers.", fontQ, Brushes.Black, x, y); y += fontQ.GetHeight() + 20; for (int i = 0; i < _test.Count; i++) { string question = (i + 1) + ". " + _test[i].question; //Ipologismos gia allagi selidas double tempY = y; E.DrawStringML(question, fontQ, Brushes.Black, x, ref tempY, width - right); if (tempY > height - bottom) { watermarkprint(X, page, fontW); page = _document.AddPage(); page.Size = PageSize.A4; X = XGraphics.FromPdfPage(page); y = top; } //Prints Questions X.DrawStringML(question, fontQ, XBrushes.Black, x, ref y, width - right); for (int k = 0; k < _test[i].anwsers.Count; k++) { string answer = _test[i].anwsers[k].text; //ipologismos gia allagi selida tempY = y; E.DrawStringML(answer, fontQ, Brushes.Black, x, ref tempY, width - right); if (tempY > height - bottom) { watermarkprint(X, page, fontW); page = _document.AddPage(); page.Size = PageSize.A4; X = XGraphics.FromPdfPage(page); y = top; } y += 3; //Edw tipwnei apantisi X.DrawRectangle(new Pen(Color.Black), x + 15, y, 20, 20); if (_solved && _test[i].anwsers[k].correct) { var cube = new Bitmap(20, 20); Graphics C = Graphics.FromImage(cube); C.FillRectangle(Brushes.Black, 0, 0, 20, 20); X.DrawImage(cube, x + 15, y, 20, 20); } y += 12; X.DrawStringML(answer, fontA, Brushes.Black, x + 45, ref y, width - right); } y += 30; } watermarkprint(X, page, fontW); _document.Save(_savePath); Process.Start(_savePath); }
/// <summary> /// Get the Certificate to be downloaded using ID /// </summary> /// <param name="id"></param> /// <returns></returns> public FileResult DownloadCertificate(int id) { IDAL dal = (new DALFactory()).GetInstance(); SharePointDAL spDal = new SharePointDAL(); try { string certificateHtml = string.Empty; MemoryStream workStream = new MemoryStream(); string strPDFFileName = string.Format("Certificate.pdf"); UserManager user = (UserManager)System.Web.HttpContext.Current.Session["CurrentUser"]; user = spDal.GetUserByEmail(user.EmailID); List <UserAssessment> userAssessments = dal.GetUserAssessmentsByID(id); foreach (UserAssessment userAssessment in userAssessments) { certificateHtml = "<HTML><HEAD><TITLE>Certificate of Completion</TITLE>" + "<META content='text/html; charset=utf-8' http-equiv=Content-Type> <META name=viewport content='width=device-width, initial-scale=1.0'> <META name=GENERATOR content='MSHTML 11.00.9600.18698'></HEAD>" + "<BODY> <TABLE style='PADDING: 5px; MARGIN: 10px 10%; BACKGROUND-COLOR: #fee2cf'>" + " <TR> <TD style='BORDER: #ff6600 10px solid; PADDING: 10px; margin:10px;'> <TABLE >" + " <TR> <TD style='BORDER: #ff6600 2px solid; BACKGROUND-COLOR: #fff;'> <TABLE>" + " <TR> <TD style=' BACKGROUND-COLOR: #ffffff'> <TABLE>" + " <TR> <TD style='WIDTH: 100%;'>" + " <TABLE style='WIDTH: 100%'>" + "<TR> <TD align=center> <TABLE> <TR> <TD style='FONT-SIZE: 25px; FONT-FAMILY: georgia'>ING Academy</TD></TR></TABLE></TD></TR>" + " <TR> <TD style='FONT-SIZE: 30px; FONT-FAMILY: Tahoma, Geneva, sans-serif; COLOR: #ff6200; TEXT-ALIGN: center; PADDING-TOP: 10px' align=center>Certificate of Completion</TD></TR>" + " <TR> <TD style='FONT-SIZE: 14px; FONT-FAMILY: Tahoma, Geneva, sans-serif; COLOR: #666; TEXT-ALIGN: center; PADDING-TOP: 20px'>This is certify that</TD></TR> " + "<TR> <TD style='FONT-SIZE: 18px; FONT-FAMILY: \"Times New Roman\", Times, serif; FONT-WEIGHT: bold; COLOR: #000; TEXT-ALIGN: center'>" + user.UserName + "</TD></TR>" + " <TR> <TD style='FONT-SIZE: 14px; FONT-FAMILY: Tahoma, Geneva, sans-serif; COLOR: #666; TEXT-ALIGN: center; PADDING-TOP: 10px'>has successfully completed</TD></TR>" + " <TR> <TD style='FONT-SIZE: 16px; FONT-FAMILY: \"Times New Roman\", Times, serif; COLOR: #000; PADDING-BOTTOM: 30px; TEXT-ALIGN: center'>" + userAssessment.TrainingAssessment + "</TD></TR>" + "</TABLE>" + " <TABLE style='WIDTH: 100%'> " + " <TR>" + "<TD style='HEIGHT: 50px; WIDTH: 150px; BACKGROUND-REPEAT: no-repeat; PADDING-LEFT: 10px'>" + " Your Score - " + userAssessment.MarksInPercentage + "%</TD> " + "<TD style='FONT-SIZE: 14px; FONT-FAMILY: Tahoma, Geneva, sans-serif; COLOR: #000; TEXT-ALIGN: right; PADDING-TOP: 0px; PADDING-RIGHT: 10px'>" + userAssessment.CompletedDate + "</TD></TR></TABLE>" + "</TD></TR>" + "</TABLE></TD></TR>" + "</TABLE></TD></TR>" + "</TABLE></TD></TR>" + "</TABLE></BODY></HTML>"; } Bitmap bitmap = new Bitmap(1800, 1800); Graphics g = Graphics.FromImage(bitmap); XGraphics xg = XGraphics.FromGraphics(g, new XSize(bitmap.Width, bitmap.Height)); TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer(); c.SetHtml(certificateHtml); PdfDocument pdf = new PdfDocument(); PdfPage page = new PdfPage(); XImage img = XImage.FromGdiPlusImage(bitmap); page.Size = PdfSharp.PageSize.A4; pdf.Pages.Add(page); XGraphics xgr = XGraphics.FromPdfPage(pdf.Pages[0]); c.PerformLayout(xgr); c.PerformPaint(xgr); xgr.DrawImage(img, 0, 0); pdf.Save(workStream, false); byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return(File(workStream, "application/pdf", strPDFFileName)); } catch (Exception ex) { UserManager users = (UserManager)Session["CurrentUser"]; LogHelper.AddLog(new LogEntity(AppConstant.PartitionError, users.EmailID.ToString(), AppConstant.ApplicationName, "Home,DownloadCertificate", ex.Message, ex.StackTrace)); return(null); } }