I Have windows form but i want to print panel in windows form to hidden print button and it's my code :
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);
int x = e.MarginBounds.X;
int y = e.MarginBounds.Y;
int width = image.Width;
int height = image.Height;
if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
}
public void StartPrint(Stream streamToPrint, string streamType)
{
this.printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
this.streamToPrint = streamToPrint;
this.streamType = streamType;
System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
PrintDialog1.AllowSomePages = true;
PrintDialog1.ShowHelp = true;
PrintDialog1.Document = printDoc;
DialogResult result = PrintDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDoc.Print();
//docToPrint.Print();
}
}
private void button_Print_Certificate_Click(object sender, EventArgs e)
{
Graphics g1 = this.CreateGraphics();
Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(#"D:\PrintPage.jpg", ImageFormat.Jpeg);
FileStream fileStream = new FileStream(#"D:\PrintPage.jpg", FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
fileStream.Close();
if (System.IO.File.Exists(#"D:\PrintPage.jpg"))
{
System.IO.File.Delete(#"D:\PrintPage.jpg");
}
}
In order to print a particular control, you'll want to use that control as the source of your BitBlt operation.
So instead of this.CreateGraphics(), call panel.CreateGraphics(). Similarly, use panel.ClientRectangle to get the width and height of the image.
But take a look at https://stackoverflow.com/a/597088/103167 which gives you an easier way.
Related
Does anyone know how I can save my panel as pdf?
Now I have this code but this saves the whole form and I only need Panel1.
This code returns a pdf of the whole form but that is not necessary.
I checked already on the internet but couldn't find anything...
I also searched in the code to see if I could find something pointing to the form but I can't find anything there either.
Can someone help me save my panel and not my entire winform?
private System.IO.Stream streamToPrint;
string streamType;
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool BitBlt
(
IntPtr hdcDest, // handle to destination DC
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);
int x = e.MarginBounds.X;
int y = e.MarginBounds.Y;
int width = image.Width;
int height = image.Height;
if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
}
public void StartPrint(Stream streamToPrint, string streamType)
{
this.printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
this.streamToPrint = streamToPrint;
this.streamType = streamType;
System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
PrintDialog1.AllowSomePages = true;
PrintDialog1.ShowHelp = true;
PrintDialog1.Document = printDocument1;
DialogResult result = PrintDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDocument1.Print();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
String filename = System.IO.Path.GetTempFileName();
Graphics g1 = this.CreateGraphics();
Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(filename, ImageFormat.Png);
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
fileStream.Close();
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
}
# Raf.
For printing panel as pdf, you can refer to the following code.
public partial class Form1 : Form
{
Bitmap MemoryImage;
private PrintDocument printDocument1 = new PrintDocument();
private PrintPreviewDialog previewdlg = new PrintPreviewDialog();
public Form1()
{
InitializeComponent();
printDocument1.PrintPage += new PrintPageEventHandler(printdoc1_PrintPage);
}
public void GetPrintArea(Panel pnl)
{
MemoryImage = new Bitmap(pnl.Width, pnl.Height);
pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, pnl.Width, pnl.Height));
}
protected override void OnPaint(PaintEventArgs e)
{
if (MemoryImage != null)
{
e.Graphics.DrawImage(MemoryImage, 0, 0);
base.OnPaint(e);
}
}
void printdoc1_PrintPage(object sender, PrintPageEventArgs e)
{
Rectangle pagearea = e.PageBounds;
e.Graphics.DrawImage(MemoryImage, (pagearea.Width / 2) - (this.panel1.Width / 2), this.panel1.Location.Y);
}
public void Print(Panel pnl)
{
Panel pannel = pnl;
GetPrintArea(pnl);
previewdlg.Document = printDocument1;
previewdlg.ShowDialog();
}
private void button1_Click_1(object sender, EventArgs e)
{
Print(this.panel1);
}
}
The result is shown in the picture:
I am trying to Print the complete form but It print document is not covering full width. I have tried different ways, But didn't get the desired result.
I have taken help from this link
https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-print-a-windows-form
This is the half print which I am getting
Here is the complete form which I want to print
Please tell me how I can get complete form printed.
Thanks in advance
I am not sure about the link you are following, I was getting same error even after trying multiple codes while I was trying to print whole form once. Then I found below code somewhere on internet, which prints whole form.
private System.IO.Stream streamToPrint;
string streamType;
PrintDocument printDoc = new PrintDocument();
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool BitBlt
(
IntPtr hdcDest, // handle to destination DC
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);
int x = e.MarginBounds.X;
int y = e.MarginBounds.Y;
int width = image.Width;
int height = image.Height;
if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
}
private void btnPrintDoc_Click(object sender, EventArgs e)
{
Graphics g1 = this.CreateGraphics();
System.Drawing.Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(#"D:\PrintPage.jpg", ImageFormat.Jpeg);
FileStream fileStream = new FileStream(#"D:\PrintPage.jpg", FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
fileStream.Close();
}
public void StartPrint(Stream streamToPrint, string streamType)
{
this.printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
this.streamToPrint = streamToPrint;
this.streamType = streamType;
System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
PrintDialog1.AllowSomePages = true;
PrintDialog1.ShowHelp = true;
PrintDialog1.Document = printDoc;
DialogResult result = PrintDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDoc.Print();
//docToPrint.Print();
}
}
If you want to fix size When Form starts you can try this, my friend. Or When you click the print button, some controls are added to your form you can only just call the SizeFix function end of your print button click event function instead of creating load event.
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(SizeFix);
}
public void SizeFix(object o, EventArgs e)
{
int widthMax = this.Width;
foreach (var item in this.Controls)
{
int tempWitdh = (item as Control).Location.X + (item as Control).Width;
if (tempWitdh > widthMax)
{
widthMax = tempWitdh;
}
}
this.Width = widthMax; // You can add 10 width more
}
public Bitmap GrabScreenshot()
{
Bitmap bmp = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
System.Drawing.Imaging.BitmapData data = bmp.LockBits(this.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
CsGL.OpenGL.GL.glReadPixels(0, 0, 800, 600, CsGL.OpenGL.GL.GL_3D, CsGL.OpenGL.GL.GL_8X_BIT_ATI, data.Scan0);
CsGL.OpenGL.GL.glFinish();
bmp.UnlockBits(data);
bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
return bmp;
}
private void button1_Click(object sender, EventArgs e)
{
GrabScreenshot();
Bitmap bmp = GrabScreenshot();
bmp.Save("C:\\temp\\test.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
}
To capture a full screenshot use this:
public static Bitmap CaptureScreen()
{
Rectangle bounds = SystemInformation.VirtualScreen;
Bitmap Target = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppRgb);
using (Graphics g = Graphics.FromImage(Target))
{
g.CopyFromScreen(0, 0, 0, 0, bounds.Size);
}
return Target;
}
If you need a specific screen then use this option:
private enum CaptureType
{
AllScreens,
PrimaryScreen,
VirtualScreen,
WorkingArea
}
private static Bitmap[] Capture(CaptureType typeOfCapture)
{
Bitmap[] images = null;
Bitmap memoryImage;
int count = 1;
Screen[] screens = Screen.AllScreens;
Rectangle SourceRectangle;
switch (typeOfCapture)
{
case CaptureType.PrimaryScreen:
SourceRectangle = Screen.PrimaryScreen.Bounds;
break;
case CaptureType.VirtualScreen:
SourceRectangle = SystemInformation.VirtualScreen;
break;
case CaptureType.WorkingArea:
SourceRectangle = Screen.PrimaryScreen.WorkingArea;
break;
case CaptureType.AllScreens:
count = screens.Length;
typeOfCapture = CaptureType.WorkingArea;
SourceRectangle = screens[0].WorkingArea;
break;
default:
SourceRectangle = SystemInformation.VirtualScreen;
break;
}
// allocate a member for saving the captured image(s)
images = new Bitmap[count];
// cycle across all desired screens
for (int index = 0; index < count; index++)
{
if (index > 0)
{
SourceRectangle = screens[index].WorkingArea;
}
// redefine the size on multiple screens
memoryImage = new Bitmap(SourceRectangle.Width, SourceRectangle.Height, PixelFormat.Format32bppArgb);
using (Graphics memoryGrahics = Graphics.FromImage(memoryImage))
{
memoryGrahics.CopyFromScreen(SourceRectangle.X, SourceRectangle.Y, 0, 0, SourceRectangle.Size, CopyPixelOperation.SourceCopy);
}
images[index] = memoryImage;
}
return images;
}
I have an application A that is made in WPF and WinForms.I have written another Application in WinForms for Capturing Screen. The problem I'm facing is that The dialog boxes that come up in Application A do not captured in the screen. The whole screen gets captured including the area behind the dialog box but the dialog box doesn't get captured.
public void CaptureScreen(string filepath)
{
string[] words = filepath.Split('\\');
string newFilePath = " ";
foreach (string word in words)
{
if (!(word.Contains(".bmp")))
{
newFilePath = newFilePath + word + "//";
}
else
{
newFilePath = newFilePath + word;
}
}
this.WindowState = FormWindowState.Minimized;
Screen[] screens;
screens = Screen.AllScreens;
int noofscreens = screens.Length, maxwidth = 0, maxheight = 0;
for (int i = 0; i < noofscreens; i++)
{
if (maxwidth < (screens[i].Bounds.X + screens[i].Bounds.Width)) maxwidth = screens[i].Bounds.X + screens[i].Bounds.Width;
if (maxheight < (screens[i].Bounds.Y + screens[i].Bounds.Height)) maxheight = screens[i].Bounds.Y + screens[i].Bounds.Height;
}
var width = maxwidth;
var height = maxheight;
Point sourcePoint = Point.Empty;
Point destinationPoint = Point.Empty;
Rectangle rect = new Rectangle(0, 0, width, height);
Bitmap bitmap = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(bitmap);
// g.CopyFromScreen(sourcePoint, destinationPoint, rect.Size);
g.CopyFromScreen(new Point(rect.Left, rect.Top), Point.Empty, rect.Size);
bitmap.Save(filepath, ImageFormat.Bmp);
//Console.WriteLine("(width, height) = ({0}, {1})", maxx - minx, maxy - miny);
}
}
}
Bitmap bmpScreenshot = new Bitmap(Screen.AllScreens[1].Bounds.Width, Screen.AllScreens[1].Bounds.Height, PixelFormat.Format32bppArgb);
Graphics.FromImage(bmpScreenshot).CopyFromScreen(
Screen.AllScreens[1].Bounds.X,
Screen.AllScreens[1].Bounds.Y,
0,
0,
Screen.AllScreens[1].Bounds.Size,
CopyPixelOperation.SourceCopy);
this.picExtendedModitorScreen.Image = bmpScreenshot;
this.picExtendedModitorScreen.Refresh();
Put this code in timer tick event.
I have put extended screen 1 in the code you can change it to any other.
I have created a method which move the PictureBox when I Drag and Drop. But when I'm dragging the PictureBox, the image has the real size of image and I wanna that the image has the size of PictureBox
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
picBox = (PictureBox)sender;
var dragImage = (Bitmap)picBox.Image;
IntPtr icon = dragImage.GetHicon();
Cursor.Current = new Cursor(icon);
DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
DestroyIcon(icon);
}
}
protected override void OnGiveFeedback(GiveFeedbackEventArgs e)
{
e.UseDefaultCursors = false;
}
protected override void OnDragEnter(DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Bitmap))) e.Effect = DragDropEffects.Copy;
}
protected override void OnDragDrop(DragEventArgs e)
{
picBox.Location = this.PointToClient(new Point(e.X - picBox.Width / 2, e.Y - picBox.Height / 2));
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static bool DestroyIcon(IntPtr handle);
Use
var dragImage = new Bitmap((Bitmap)picBox.Image, picBox.Size);
instead of
var dragImage = (Bitmap)picBox.Image;
(and maybe call Dispose on the temporary image later, but the GC will deal with it if you don't)
This is because the image in your picture box is the full size image. The picture box just scales it for display purposes but the Image property has the original-sized image.
So, in your MouseDown event handler you want to resize the image before using it.
Rather than:
var dragImage = (Bitmap)picBox.Image;
Try:
var dragImage = ResizeImage(picBox.Image, new Size(picBox.Width, PicBox.Height));
Use something like this method to resize the image for you:
public static Image ResizeImage(Image image, Size size,
bool preserveAspectRatio = true)
{
int newWidth;
int newHeight;
if (preserveAspectRatio)
{
int originalWidth = image.Width;
int originalHeight = image.Height;
float percentWidth = (float)size.Width / (float)originalWidth;
float percentHeight = (float)size.Height / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
newWidth = (int)(originalWidth * percent);
newHeight = (int)(originalHeight * percent);
}
else
{
newWidth = size.Width;
newHeight = size.Height;
}
Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
*Image resize code from here: http://www.codeproject.com/Articles/191424/Resizing-an-Image-On-The-Fly-using-NET