winforms HasMorePages不工作,设置该位会导致在同一页上打印所有项目

mxg2im7a  于 2023-10-23  发布在  其他
关注(0)|答案(3)|浏览(133)

当我尝试使用下面的代码打印预览时,它会在先前打印的项目上打印项目。当我将if块放在for循环之外时,它开始生成无限页。

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{    
    SolidBrush brush = new SolidBrush(Color.Black);
    Font font = new Font("Courier New", 12);

    float fontHeight = font.GetHeight();
    int startX = 40;
    int startY = 30;
    int lineperpage = 0;

    for (int i = 0; i < 100; i++)
    {
        e.Graphics.DrawString("Line: " + i, font, brush, startX, startY);
        startY += font.Height;
        lineperpage++;

        if (lineperpage > 50)
        {
            e.HasMorePages = true;
            startY = 30;
            lineperpage = 0;
            startX = 300;
        }
        else
        {
            e.HasMorePages = false;
        }
    } 
}
t5zmwmid

t5zmwmid1#

你必须把你想要打印的 * 数据 * 和一页纸的实际绘图分开。你不能用同样的方法。将HasMorePages设置为true只会向PrintManager发出再次引发PrintPage事件的信号。
在你的例子中,看起来你的i变量就是数据。您需要在PrintPage事件之外跟踪其进度。

int i = 0;  // keep track of data in an instance variable 

// this event is re-entrant. It will be called as long as HasMorePages = true;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{    
    SolidBrush brush = new SolidBrush(Color.Black);
    Font font = new Font("Courier New", 12);

    float fontHeight = font.GetHeight();
    int startX = 40;
    int startY = 30;
    int lineperpage = 0;

    // removed
    //for (int i = 0; i < 100; i++)
    // print a page as long as their is space left AND data available
    while (lineperpage < 50 && i < 100)
    {
        e.Graphics.DrawString("Line: " + i, font, brush, startX, startY);
        startY += font.Height;
        lineperpage++;

        i++;  // next dataitem
    }

    e.HasMorePages = i < 100; // keep printing as long as there is date 
}
owfi6suc

owfi6suc2#

修复在C#中使用HasMorePages打印时的分页问题。关于这段代码的解释:您可以添加许多行或从数据库中读取,以查看打印时分页的结果,例如,我只手动向表中添加了两行,因为行数很少,所以没有分页。手动添加多行或将数据库中的信息插入网格视图。这是一个例子:

int currentPage = 1;
int rowsPerPage = 36; //Number of rows per page
int rowIndex = 0;

void pdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    try
    {
        int x = 5, y = 5; //Drawing start position
        int rowMargin = 0; //Spacing between lines

        dgvHesaab.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        dgvHesaab.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        dgvHesaab.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        dgvHesaab.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; //Text with more lines in a row.
        dgvHesaab.ColumnHeadersHeight = 40; //40=row height. Text with more lines in a row.

        dgvHesaab.RightToLeft = RightToLeft.Yes;

        int rowCount = dgvHesaab.Rows.Count; //Get the number of rows
        int pageCount = Convert.ToInt32(Math.Round(Convert.ToDouble(rowCount) / Convert.ToDouble(rowsPerPage)));

        //Set header content of columns
        for (int j = this.dgvHesaab.Columns.Count - 1; j >= 0; j--)
        {
            Rectangle rect = new Rectangle(x, y, 132, dgvHesaab.Rows[0].Height); //132 = width in row
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.FillRectangle(Brushes.LightGray, rect);
            e.Graphics.DrawRectangle(Pens.Black, rect);
            if (this.dgvHesaab.Columns[j].HeaderText != null)
            {
                e.Graphics.DrawString(this.dgvHesaab.Columns[j].HeaderText, SystemFonts.DefaultFont, Brushes.Black, rect, sf);
            }
            x += rect.Width;
        }

        x = 5;
        y += dgvHesaab.Rows[0].Height + rowMargin;
        //Set the content of the lines
        while (rowIndex < dgvHesaab.Rows.Count)
        {
            DataGridViewRow row = dgvHesaab.Rows[rowIndex];
            if (row.Cells[0].Value != null)
            {
                for (int j = this.dgvHesaab.Columns.Count - 1; j >= 0; j--)
                {
                    DataGridViewCell cell = row.Cells[j];
                    Rectangle rect = new Rectangle(x, y, 132, dgvHesaab.Rows[0].Height); //132 = width in row
                    StringFormat sf = new StringFormat();
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Alignment = StringAlignment.Center;
                    e.Graphics.DrawRectangle(Pens.Black, rect);
                    if (cell.Value != null)
                    {
                        e.Graphics.DrawString(cell.Value.ToString(), new Font("Tahoma", 8, FontStyle.Bold), Brushes.Black, rect, sf);
                    }
                    x += rect.Width;
                }
                x = 5;
                y += dgvHesaab.Rows[0].Height + rowMargin;
            }
            rowIndex++;

            //Print a new page if necessary
            if (rowIndex % rowsPerPage == 0 || rowIndex == dgvHesaab.Rows.Count)
            {
                e.HasMorePages = (currentPage < pageCount);
                currentPage++;
                return;
            }
        }
    }
    catch (Exception)
    {

    }
}

   
private void btnAdd_Click(object sender, EventArgs e)
{
    try
    {
        //Begin , Adding a row to the gridView(dgvHesaab) 
        ///<summary>
        ///For example, the name of our Grid View is dgvHesaab
        ///Retrieving data from a database or manually inserting data for a row. 
        ///</summary>

        //add row 1
        dgvHesaab.Rows.Add(new object[]
        {
            "Row 1 : Item 1",
            "Row 1 : Item 2",
            "Row 1 : Item 3",
            "Row 1 : Item 4",
            "Row 1 : Item 5",
            "Row 1 : Item 6",
        });

        //add row 2
        dgvHesaab.Rows.Add(new object[]
        {
            "Row 2 : Item 1",
            "Row 2 : Item 2",
            "Row 2 : Item 3",
            "Row 2 : Item 4",
            "Row 2 : Item 5",
            "Row 2 : Item 6",
        });
        //End , Adding a row to the gridView(dgvHesaab)  

        dgvHesaab.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        dgvHesaab.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        dgvHesaab.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        dgvHesaab.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; //Text with more lines in a row.
        dgvHesaab.ColumnHeadersHeight = 40; //40=row height. Text with more lines in a row.

        dgvHesaab.RightToLeft = RightToLeft.Yes;

        //Begin Print
        PrintDialog pDialog = new PrintDialog();
        pDialog.AllowCurrentPage = false;
        pDialog.AllowPrintToFile = false;
        pDialog.AllowSelection = false;
        pDialog.AllowSomePages = false;
        pDialog.PrintToFile = false;
        pDialog.ShowHelp = false;
        pDialog.ShowNetwork = false;
        if (pDialog.ShowDialog() == DialogResult.OK)
        {
            System.Drawing.Printing.PrintDocument pdoc = new System.Drawing.Printing.PrintDocument();
            pdoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pdoc_PrintPage);
            pdoc.DocumentName = "Print Title";
            pdoc.PrinterSettings = pDialog.PrinterSettings;
            pdoc.DefaultPageSettings = pDialog.PrinterSettings.DefaultPageSettings;
            pdoc.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(100, 100, 100, 100);
            pdoc.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);
            pdoc.DefaultPageSettings.Landscape = false; //Landscape
            //pdoc.PrinterSettings.Copies = 3;
            PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
            printPreviewDialog1.Document = pdoc;
            pdoc.Print(); //No preview  
            //printPreviewDialog1.ShowDialog(); //printPreview
        }
        //End Print
    }
    catch (Exception)
    {

    }
}
nzkunb0c

nzkunb0c3#

修复在C#中使用HasMorePages打印时的分页问题。关于这段代码的解释:您可以添加许多行或从数据库中读取,以查看打印时分页的结果,例如,我只手动向表中添加了两行,因为行数很少,所以没有分页。手动添加多行或将数据库中的信息插入网格视图。这是一个例子:

int currentPage = 1;
int rowsPerPage = 36; //Number of rows per page
int rowIndex = 0;

void pdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    try
    {
        int x = 5, y = 5; //Drawing start position
        int rowMargin = 0; //Spacing between lines

        dgvHesaab.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        dgvHesaab.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        dgvHesaab.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        dgvHesaab.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; //Text with more lines in a row.
        dgvHesaab.ColumnHeadersHeight = 40; //40=row height. Text with more lines in a row.

        dgvHesaab.RightToLeft = RightToLeft.Yes;

        int rowCount = dgvHesaab.Rows.Count; //Get the number of rows
        int pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(rowCount) / Convert.ToDouble(rowsPerPage)));

        //Set header content of columns
        for (int j = this.dgvHesaab.Columns.Count - 1; j >= 0; j--)
        {
            Rectangle rect = new Rectangle(x, y, 132, dgvHesaab.Rows[0].Height); //132 = width in row
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.FillRectangle(Brushes.LightGray, rect);
            e.Graphics.DrawRectangle(Pens.Black, rect);
            if (this.dgvHesaab.Columns[j].HeaderText != null)
            {
                e.Graphics.DrawString(this.dgvHesaab.Columns[j].HeaderText, SystemFonts.DefaultFont, Brushes.Black, rect, sf);
            }
            x += rect.Width;
        }

        x = 5;
        y += dgvHesaab.Rows[0].Height + rowMargin;
        //Set the content of the lines
        while (rowIndex < dgvHesaab.Rows.Count)
        {
            DataGridViewRow row = dgvHesaab.Rows[rowIndex];
            if (row.Cells[0].Value != null)
            {
                for (int j = this.dgvHesaab.Columns.Count - 1; j >= 0; j--)
                {
                    DataGridViewCell cell = row.Cells[j];
                    Rectangle rect = new Rectangle(x, y, 132, dgvHesaab.Rows[0].Height); //132 = width in row
                    StringFormat sf = new StringFormat();
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Alignment = StringAlignment.Center;
                    e.Graphics.DrawRectangle(Pens.Black, rect);
                    if (cell.Value != null)
                    {
                        e.Graphics.DrawString(cell.Value.ToString(), new Font("Tahoma", 8, FontStyle.Bold), Brushes.Black, rect, sf);
                    }
                    x += rect.Width;
                }
                x = 5;
                y += dgvHesaab.Rows[0].Height + rowMargin;
            }
            rowIndex++;

            //Print a new page if necessary
            if (rowIndex % rowsPerPage == 0 || rowIndex == dgvHesaab.Rows.Count)
            {
                e.HasMorePages = (currentPage < pageCount);
                currentPage++;
                return;
            }
        }
    }
    catch (Exception)
    {

    }
}

   
private void btnAdd_Click(object sender, EventArgs e)
{
    try
    {
        //Begin , Adding a row to the gridView(dgvHesaab) 
        ///<summary>
        ///For example, the name of our Grid View is dgvHesaab
        ///Retrieving data from a database or manually inserting data for a row. 
        ///</summary>

        //add row 1
        dgvHesaab.Rows.Add(new object[]
        {
            "Row 1 : Item 1",
            "Row 1 : Item 2",
            "Row 1 : Item 3",
            "Row 1 : Item 4",
            "Row 1 : Item 5",
            "Row 1 : Item 6",
        });

        //add row 2
        dgvHesaab.Rows.Add(new object[]
        {
            "Row 2 : Item 1",
            "Row 2 : Item 2",
            "Row 2 : Item 3",
            "Row 2 : Item 4",
            "Row 2 : Item 5",
            "Row 2 : Item 6",
        });
        //End , Adding a row to the gridView(dgvHesaab)  

        dgvHesaab.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        dgvHesaab.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        dgvHesaab.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        dgvHesaab.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; //Text with more lines in a row.
        dgvHesaab.ColumnHeadersHeight = 40; //40=row height. Text with more lines in a row.

        dgvHesaab.RightToLeft = RightToLeft.Yes;

        //Begin Print
        PrintDialog pDialog = new PrintDialog();
        pDialog.AllowCurrentPage = false;
        pDialog.AllowPrintToFile = false;
        pDialog.AllowSelection = false;
        pDialog.AllowSomePages = false;
        pDialog.PrintToFile = false;
        pDialog.ShowHelp = false;
        pDialog.ShowNetwork = false;
        if (pDialog.ShowDialog() == DialogResult.OK)
        {
            System.Drawing.Printing.PrintDocument pdoc = new System.Drawing.Printing.PrintDocument();
            pdoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pdoc_PrintPage);
            pdoc.DocumentName = "Print Title";
            pdoc.PrinterSettings = pDialog.PrinterSettings;
            pdoc.DefaultPageSettings = pDialog.PrinterSettings.DefaultPageSettings;
            pdoc.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(100, 100, 100, 100);
            pdoc.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);
            pdoc.DefaultPageSettings.Landscape = false; //Landscape
            //pdoc.PrinterSettings.Copies = 3;
            PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
            printPreviewDialog1.Document = pdoc;
            pdoc.Print(); //No preview  
            //printPreviewDialog1.ShowDialog(); //printPreview
        }
        //End Print
    }
    catch (Exception)
    {

    }
}

相关问题