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

現在、このコードを実行すると、1ページが表示され、70行ほど経過すると、紙切れになります。この文字列を1ページに十分に印刷してから、2ページ目に移動するようにするにはどうすればよいですか?

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 に答える