winforms 多页打印的事件处理

q5iwbnjs  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(151)

文本文档有更多的页面。他们需要处理打印更多页面的事件。但是我的代码是为**Copy From Screen()**方法编写的。

代码:

public partial class print : Form 
    {   
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(bmp, 0, 0);
        }  
        private void printbtn_Click(object sender, EventArgs e)
        {
            printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("210 X 297", 820, 800);
            printPreviewDialog1.Document = printDocument1;

        Graphics g = this.CreateGraphics();
        bmp = new Bitmap(this.Size.Width, this.Size.Height, g);
        Graphics g1 = Graphics.FromImage(bmp);   
        g1.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size);
        printPreviewDialog1.ShowDialog();
    }
}
2mbi3lxu

2mbi3lxu1#

您可以将页面拆分为多个页面,并跟踪已打印的内容以及是否还有要打印的页面。下面是一个简单的示例,它将在一页上打印一个任意的文本列表(每页10行)。它将一直打印10行页面,直到没有要打印的行为止。

private List<string> lines = new();
private int lineIndex;

private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
    lineIndex = 0;
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    for (var i = 0; i < 10 && lineIndex < lines.Count; i++, lineIndex++)
    {
        e.Graphics.DrawString(lines[lineIndex], Font, Brushes.Black, 0, i * 15);
    }

    e.HasMorePages = lineIndex < lines.Count;
}

代码在每次打印开始时将行索引重置为零。然后在当前页上打印最多10行,当且仅当还有行要打印时才打印另一页。这是一个简单的原理,您需要针对数据以适当的方式实现它。
另一个变体是使用BeginPrint事件来处理数据并将其拆分为页面,然后针对每个PrintPage事件打印其中一个页面,例如

// All the lines to be printed.
private List<string> lines = new();

// The groups of lines to be printed on each page.
private List<string[]> pages;

// The index of the page being printed.
private int pageIndex;

private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
    // Print 10 lines per page.
    const int pageLineCount = 10;

    pages = new List<string[]>();

    // Take groups of up to 10 lines from the line liust and add them to the page list.
    for (var pageStartLineIndex = 0; pageStartLineIndex < lines.Count; pageStartLineIndex += pageLineCount)
    {
        pages.Add(lines.Skip(pageStartLineIndex).Take(pageLineCount).ToArray());
    }

    // Start printing at the first page.
    pageIndex = 0;
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    // Get the current page and increment the page index.
    var page = pages[pageIndex++];

    // Print the current page.
    for (var i = 0; i < page.Length; i++)
    {
        e.Graphics.DrawString(page[i], Font, Brushes.Black, 0, i * 15);
    }

    // Continue printing if and only if there are more pages to print.
    e.HasMorePages = pageIndex < pages.Count;
}

相关问题