110,538
社区成员
发帖
与我相关
我的任务
分享
private static Bitmap mBitmap = null;
private static System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument();
public static void PrintPanel(Panel p)
{
PrintPreviewDialog ppvw;
Graphics mygraphics = p.CreateGraphics();
Size s = p.Size;
mBitmap = new Bitmap(s.Width, s.Height, mygraphics);
Graphics memoryGraphics = Graphics.FromImage(mBitmap);
IntPtr dc1 = mygraphics.GetHdc();
IntPtr dc2 = memoryGraphics.GetHdc();
BitBlt(dc2, 0, 0, p.ClientRectangle.Width, p.ClientRectangle.Height, dc1, 0, 0, 13369376);
mygraphics.ReleaseHdc(dc1);
memoryGraphics.ReleaseHdc(dc2);
ppvw = new PrintPreviewDialog();
ppvw.Width = 800;
ppvw.Height = 600;
ppvw.Document = printDoc;
printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
if (ppvw.ShowDialog() != DialogResult.OK)
{
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
return;
}
printDoc.Print();
}
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern long BitBlt(IntPtr HDest, int nXDest, int nYDest, int nWidth, int hHeight, IntPtr HSrc, int nXSrc, int nYSrc, int DwRop);
private static void PrintDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(mBitmap, 0, 0);
}
Bitmap bitM = new Bitmap(this.panel1.Width, this.panel1.Height); //定义Bitmap对象实例
Graphics g = Graphics.FromImage(bitM); //定义Graphics对象实例
g.Clear(panel1.BackColor);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
Point panPos = panel1.Parent.PointToScreen(panel1.Location);
Point textPos = n[i].Parent.PointToScreen(n[i].Location);
int x, y, w, h;
x = textPos.X - panPos.X;
y = textPos.Y - panPos.Y;
w = textPos.X;
h = textPos.Y;
g.DrawString(n[i].Text, new Font("宋体", 10, FontStyle.Regular), new SolidBrush(n[i].ForeColor), x, y);
}
this.panel1.BackgroundImage = bitM;
Panel parentPanel; //要打印内容所在Panel
printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
//遍历Panel中所有Label和PictureBox
//
foreach (Control c in parentPanel.Controls)
{
if(c.getType() == typeof(Label))
{
e.Graphics.DrawString(c.Text, c.Font,
new SolidBrush(c.ForeColor), c.Location);
}
else if(c.getType() == typeof(PictureBox))
{
e.Graphics.DrawImage((PictureBox)c.Image, c.Location.X,
c.Location.y, c.Width, c.Height);
}
}
}