Graphics.DrawString center in printdocument width

你。 提交于 2019-12-02 06:03:12

The following works for me. You may need to use PageBounds if your margins are not uniform.

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

Edit Response

Output using your new code. Are you saying this is what you want?

Or are you wanting this?

The margin is a rectangle that sits inside the page. It is possible that those margins are asymmetrical so if you want the absolute center you should reference PageBounds.

Additionally, your text is center aligned so that makes the reference point of drawing the text in the middle of the String instead of top left like the logo.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!