Graphics.DrawString打印页面上的中心文本

时间:2015-07-04 14:28:04

标签: c# .net winforms

我使用以下内容从我的C#WPF应用程序中打印出一些文本:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        PrintDocument printDocument = new PrintDocument();
        printDocument.PrinterSettings.PrinterName = "\\\\servername\\printername";

        printDocument.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
        if (printDocument.PrinterSettings.IsValid)
        {
            printDocument.Print();
        }
    }

    // The PrintPage event is raised for each page to be printed. 
    private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        string stringToPrint = "SOME TEXT TO PRINT";

        // Create font and brush.
        Font drawFont = new Font("Arial", 16);
        SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Black);

        System.Drawing.Point pos = new System.Drawing.Point(100, 100);

        ev.Graphics.DrawString(stringToPrint, drawFont, drawBrush, pos);

        ev.HasMorePages = false;
    }

以上示例使用的是固定位置,但我需要打印出几行不同长度的文本,我希望将它们全部放在页面上(x位置)。

我该怎么做?

1 个答案:

答案 0 :(得分:3)

Graphics.DrawString的重载使用StringFormat参数,您可以使用该参数设置矩形中文本的水平和垂直对齐方式。我过去曾经使用过这样的东西。

string stringToPrint = "SOME TEXT TO PRINT";
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;

// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Black);

//Starting point of left margin,Width of page, Height of Text
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 100, 100, 50); 

ev.Graphics.DrawString(stringToPrint, drawFont, drawBrush, rect, sf);

ev.HasMorePages = false;
相关问题