正在设计打印报表,想实现的效果是:在窗体设计时放入label和textbox,两者都显示边框,窗体显示的实际情况用DrawImage截图传递到printdocument,同时使用DrawString复刻label和textbox并传递到printdocument,也就是说要在窗体拖放label和textbox后的实际显示是怎样,DrawString之后就显示怎样(大小,颜色,边框等等一样),以方便设计报表的里的文字格式。这是因为用DrawImage后打印实在太不清晰了,用DrawString最好。但是我做出来的效果不能完全重叠一起,且文字对齐(stringformat)不知道怎样使两者一致辞。图片和我的代码如下:
打印窗体设计截图:
打印预览截图:
Private Sub pd_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pd.PrintPage
Dim pen As New Pen(Color.Black, 1)
Dim bmp As Bitmap = New Bitmap(pd.DefaultPageSettings.PaperSize.Width, pd.DefaultPageSettings.PaperSize.Height)
For Each c In pr.panel.Controls
If TypeOf c Is Label Or TypeOf c Is TextBox Or TypeOf c Is ComboBox Or TypeOf c Is DateTimePicker Then
c.DrawToBitmap(bmp, New Rectangle(c.Location.X, c.Location.Y, c.Location.X + c.Width, c.Location.Y + c.Height))
End If
Next
e.Graphics.DrawImage(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height))
For Each c In pr.panel.Controls
If TypeOf c Is Label Or TypeOf c Is TextBox Then
e.Graphics.DrawString(c.Text, c.Font, New SolidBrush(c.ForeColor), c.Location)
e.Graphics.DrawRectangle(pen, New Rectangle(c.Location.X, c.Location.Y, c.Width, c.Height))
End If
Next
End Sub
------解决思路----------------------
控件里的文字间距啊等等都可能和你drawstring的不一样。个人觉得不用纠结是不是重合,位置ok就可以了。
private void DrawTextBox(TextBox t, Graphics g)
{
Rectangle r = GetControlRect(t);
if (t.BackColor != Color.White)
g.FillRectangle(new SolidBrush(t.BackColor), r);
if (t.BorderStyle != BorderStyle.None)
g.DrawRectangle(_pen, r);
string s = GetControlText(t);
SizeF sf = g.MeasureString(s, t.Font, (SizeF)r.Size);
RectangleF rbox;
if (t.TextAlign == HorizontalAlignment.Center)
rbox = new RectangleF(r.X + (r.Width - sf.Width) / 2, r.Y + (r.Height - sf.Height) / 2, sf.Width, sf.Height);
else
rbox = (RectangleF)r;
g.DrawString(s, t.Font, new SolidBrush(t.ForeColor), rbox);
}