我正在尝试将字符串放在打印文档的中心。
我已经对图像执行了以下操作,它可以工作,但对于字符串似乎不起作用。
这是我用来使图像居中的代码
e.Graphics.DrawImage(logo, (e.MarginBounds.Width / 2) - (logo.Width / 2), height);
我试图居中的文本是从 TabControl 中的选项卡提供的
using (var sf = new StringFormat())
{
height = logo.Height + 15;
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
e.Graphics.DrawString(tabData.Text, new Font(this.Font.Name, 10),
new SolidBrush(tabData.ForeColor),
(e.MarginBounds.Width / 2) - (txtData.Width / 2), height, sf);
}
我也在下面尝试过并使用 string_size.Width /2 代替 txtData.Width
SizeF string_size = e.Graphics.MeasureString(tabData.Text, tabData.Font);
EDIT
以下内容对我有用。您可能需要使用PageBounds
如果你的边距不均匀。
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
int w = e.MarginBounds.Width / 2;
int x = e.MarginBounds.Left;
int y = e.MarginBounds.Top;
Font printFont = new Font("Arial", 10);
Bitmap logo = System.Drawing.SystemIcons.WinLogo.ToBitmap();
int height = 100 + y;
string tabDataText = "Hello World";
var tabDataForeColor = Color.Blue;
var txtDataWidth = e.Graphics.MeasureString(tabDataText, printFont).Width;
e.Graphics.DrawImage(logo,
e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (logo.Width / 2),
e.MarginBounds.Top + (e.MarginBounds.Height / 2) - (logo.Height));
using (var sf = new StringFormat())
{
height += logo.Height + 15;
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
e.Graphics.DrawString(tabDataText, new Font(this.Font.Name, 10),
new SolidBrush(tabDataForeColor),
e.MarginBounds.Left + (e.MarginBounds.Width / 2),
e.MarginBounds.Top + (e.MarginBounds.Height / 2) + (logo.Height / 2) + 15,
sf);
}
e.HasMorePages = false;
}
编辑回复
Output using your new code. Are you saying this is what you want?
![](https://i.stack.imgur.com/6icVp.png)
Or are you wanting this?
![](https://i.stack.imgur.com/Qz5sQ.png)
页边距是位于页面内部的一个矩形。这些边距可能是不对称的,因此如果您想要绝对中心,您应该参考PageBounds
.
此外,您的文本是居中对齐的,以便使绘制文本的参考点位于字符串的中间,而不是像左上角那样logo
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)