1

我正在尝试使用 C# Winforms 应用程序打印一些东西。我似乎无法理解多页是如何工作的。假设我的构造函数中有以下代码:

private string _stringToPrint;
_stringToPrint = "";
for (int i = 0; i < 120; i++)
{
    _stringToPrint = _stringToPrint + "Line " + i.ToString() + Environment.NewLine;
}

然后我的按钮点击事件上有这个代码:

private void MnuFilePrintClick(object sender, EventArgs e)
{
    var pd = new PrintDocument();
    pd.PrintPage += pd_PrintPage;

    var z = new PrintPreviewDialog { Document = pd };

    z.ShowDialog(this);
}

void pd_PrintPage(object sender, PrintPageEventArgs e)
{
    Graphics g = e.Graphics;
    var font = new Font("Arial", 10f, FontStyle.Regular);

    g.DrawString(_stringToPrint, font, Brushes.Black, new PointF(10f, 10f));
}

现在,当我运行这段代码时,它给了我一页,大约 70 行之后,它就从纸上跑掉了。我将如何打印这个字符串,以便它打印足够的一页,然后运行到第二页,等等......?

4

1 回答 1

2

您可以有一个计数器并设置每页所需的行数,如下所示:

private string[] _stringToPrint = new string[100]; // 100 is the amount of lines
private int counter = 0;
private int amtleft = _stringToPrint.Length;
private int amtperpage = 40; // The amount of lines per page
for (int i = 0; i < 120; i++)
{
    _stringToPrint[i] ="Line " + i.ToString();
}

然后在pd_PrintPage

void pd_PrintPage(object sender, PrintPageEventArgs e)
{
    int currentamt = (amtleft > 40)?40:amtleft;
    Graphics g = e.Graphics;
    var font = new Font("Arial", 10f, FontStyle.Regular);
    for(int x = counter; x < (currentamt+counter); x++)
    {
        g.DrawString(_stringToPrint[x], font, Brushes.Black, new PointF(10f, (float)x*10));
        // x*10 is just so the lines are printed downwards and not on top of each other
        // For example Line 2 would be printed below Line 1 etc
    }
    counter+=currentamt;
    amtleft-=currentamt;
    if(amtleft<0)
        e.HasMorePages = true;
    else
        e.HasMorePages = false;
    // If e.HasMorePages is set to true and the 'PrintPage' has finished, it will print another page, else it wont
}

我有过不好的经历,e.HasMorePages所以这可能行不通。

让我知道这是否有效,我希望它有所帮助!

于 2012-07-04T22:19:08.047 回答