Graphics.DrawString以printdocument宽度为中心

我试图将一个字符串放在printdocument上。 我用图像完成了以下操作并且它可以工作,但似乎对字符串不起作用。

这是我用来居中图像的代码

e.Graphics.DrawImage(logo, (e.MarginBounds.Width / 2) - (logo.Width / 2), height); 

我试图居中的文本是从TabControl中的Tab提供的

  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); 

编辑

目前的完整代码

  float height = 0; tabData.Text = "Date Range: 02/02/2010 - 08/09/2013"; //set just for testing using (var logo = Properties.Resources.title) { e.Graphics.DrawImage(logo, e.PageBounds.Left + (e.MarginBounds.Width / 2) - (logo.Width / 2), height); height = logo.Height + 15; } using (var sf = new StringFormat()) { sf.LineAlignment = StringAlignment.Center; sf.Alignment = StringAlignment.Center; e.Graphics.DrawString(tabData.Text, new Font(this.Font.Name, 10), new SolidBrush(tabData.ForeColor), e.PageBounds.Left + (e.PageBounds.Width / 2), height, sf); } 

不明白为什么我必须使用PageBounds和MarginBounds的混合来使Image居中,然后使用与MarginBounds或两个PageBounds同中的文本

以下适用于我。 如果边距不均匀,则可能需要使用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; } 

编辑响应

使用新代码输出。 你是说这是你想要的吗?

或者你想要这个?

边距是位于页面内的矩形。 这些边距可能是不对称的,所以如果你想要绝对中心,你应该引用PageBounds

此外,您的文本居中对齐,以便在文本字符串的中间绘制文本的参考点,而不是像logo一样绘制左上角。