PrintDialog page does not work with DataGridView

I was looking for EXTENSIVELY to solve this problem, but could not find anything that could be used with my current code.

I have a form application that queries a SQL Server table and fills rows dataGridViewwith rows. Then I have a button to print dataGridViewto the printer. I went as far as inserting an override of the printPreviewDialogprint button c printDialog, and I also got the "print page range" field, but at the same time the page range still prints all pages a dataGridView. For example, if my dataGridViewwill print 20 pages, and I select pages 2-4 in the range, I still get all 20 pages.

I have seen some examples with DocumentPaginator, but I am not using a document that I am printing directly from dataGridView, and at that moment I was stuck.

Below is all my code for printing dataGridView.

private void printActivityReportToolStripMenuItem_Click(object sender, EventArgs e)
        {



     PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
     objPPdialog.Document = printDocument1;

     ToolStrip ts = new ToolStrip();
     ts.Name = "wrongToolStrip";
     foreach (Control ctl in objPPdialog.Controls)
     {
         if (ctl.Name.Equals("toolStrip1"))
         {
             ts = ctl as ToolStrip;
             break;
         }
     }
     ToolStripButton printButton = new ToolStripButton();
     foreach (ToolStripItem tsi in ts.Items)
     {
         if (tsi.Name.Equals("printToolStripButton"))
         {
             printButton = tsi as ToolStripButton;
         }
     }

     printButton.Click += new EventHandler(this.SelectPrinterAfterPreview);

     ts.Items.Remove(printButton);
     ToolStripButton b = new ToolStripButton();
     b.ImageIndex = printButton.ImageIndex;
     b.Visible = true;
     ts.Items.Insert(0, b);
     b.Click += new EventHandler(this.SelectPrinterAfterPreview);

     printDocument1.DefaultPageSettings.Landscape = true;
     //((ToolStripButton)((ToolStrip)objPPdialog.Controls[1]).Items[0]).
     objPPdialog.ShowDialog();

    }

    private void SelectPrinterAfterPreview(object sender, EventArgs e)
    {
        PrintDialog printDialog = new PrintDialog();
        printDialog.Document = printDocument1;
        printDocument1.DefaultPageSettings.Landscape = true;

        printDialog.AllowSomePages = true;
        printDialog.UseEXDialog = true;
        if (DialogResult.OK == printDialog.ShowDialog())
        {
            printDocument1.DocumentName = "Activity Report";
            printDocument1.Print();
        }
    }

    private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    {


        try
        {
            strFormat = new StringFormat();
            strFormat.Alignment = StringAlignment.Near;
            strFormat.LineAlignment = StringAlignment.Center;
            strFormat.Trimming = StringTrimming.EllipsisCharacter;

            arrColumnLefts.Clear();
            arrColumnWidths.Clear();
            iCellHeight = 0;
            iRow = 0;
            bFirstPage = true;
            bNewPage = true;

            // Calculating Total Widths
            iTotalWidth = 0;
            foreach (DataGridViewColumn dgvGridCol in dataGridView1.Columns)
            {
                iTotalWidth += dgvGridCol.Width;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
    {
        try
        {
            //Set the left margin
            int iLeftMargin = e.MarginBounds.Left;
            //Set the top margin
            int iTopMargin = e.MarginBounds.Top;
            //Whether more pages have to print or not
            bool bMorePagesToPrint = false;
            int iTmpWidth = 0;

            //For the first page to print set the cell width and header height
            if (bFirstPage)
            {
                foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
                {
                    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                        (double)iTotalWidth * (double)iTotalWidth *
                        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    // Save width and height of headers
                    arrColumnLefts.Add(iLeftMargin);
                    arrColumnWidths.Add(iTmpWidth);
                    iLeftMargin += iTmpWidth;
                }
            }
            //Loop till all the grid rows not get printed
            while (iRow <= dataGridView1.Rows.Count - 1)
            {
                DataGridViewRow GridRow = dataGridView1.Rows[iRow];
                //Set the cell height
                iCellHeight = GridRow.Height;
                int iCount = 0;
                //Check whether the current page settings allows more rows to print
                if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    bNewPage = true;
                    bFirstPage = false;
                    bMorePagesToPrint = true;
                    break;
                }
                else
                {
                    if (bNewPage)
                    {
                        //Draw Header
                        e.Graphics.DrawString("Activity Report for "+txtBoxUsername.Text+"",
                            new Font(dataGridView1.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left,
                            e.MarginBounds.Top - e.Graphics.MeasureString("Activity Report for " + txtBoxUsername.Text + "",
                            new Font(dataGridView1.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Height - 13);

                        String strDate = DateTime.Now.ToLongDateString() + " " +
                            DateTime.Now.ToShortTimeString();
                        //Draw Date
                        e.Graphics.DrawString(strDate,
                            new Font(dataGridView1.Font, FontStyle.Bold), Brushes.Black,
                            e.MarginBounds.Left +
                            (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                            new Font(dataGridView1.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Width),
                            e.MarginBounds.Top - e.Graphics.MeasureString("Activity Report for " + txtBoxUsername.Text + "",
                            new Font(new Font(dataGridView1.Font, FontStyle.Bold),
                            FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                        //Draw Columns                 
                        iTopMargin = e.MarginBounds.Top;
                        foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
                        {
                            e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iHeaderHeight));

                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iHeaderHeight));

                            e.Graphics.DrawString(GridCol.HeaderText,
                                GridCol.InheritedStyle.Font,
                                new SolidBrush(GridCol.InheritedStyle.ForeColor),
                                new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            iCount++;
                        }
                        bNewPage = false;
                        iTopMargin += iHeaderHeight;
                    }
                    iCount = 0;
                    //Draw Columns Contents                
                    foreach (DataGridViewCell Cel in GridRow.Cells)
                    {
                        if (Cel.Value != null)
                        {
                            Font font = new Font("Arial", 7);
                            e.Graphics.DrawString(Cel.Value.ToString(),font,new SolidBrush(Cel.InheritedStyle.ForeColor),new RectangleF((int)arrColumnLefts[iCount],(float)iTopMargin,(int)arrColumnWidths[iCount], (float)iCellHeight),strFormat);
                        }
                        //Drawing Cells Borders 
                        e.Graphics.DrawRectangle(Pens.Black,
                            new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iCellHeight));
                        iCount++;
                    }
                }
                iRow++;
                iTopMargin += iCellHeight;
            }
            //If more lines exist, print another page.
            if (bMorePagesToPrint)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
               MessageBoxIcon.Error);
        }
    }
+4
source share
2 answers

You set a rather inflexible restriction by insisting that the solution works with your existing code. This was written in full, without considering starting from a page other than 1. Actually, it is difficult to fix it, you just need to find out which line at the beginning of the data set, based on the number of the initial page.

, , . , PrintDocument, , . , . , . . , PrintDocument. PageFrom PageTo PrintDialog.PrinterSettings.PageFrom/To.

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Imaging;

class PagedPrintDocument : PrintDocument {
    public int PageFrom { get; set; }
    public int PageTo { get; set; }
    public int Page { get; private set; }

    protected override void OnBeginPrint(PrintEventArgs e) {
        Page = 0;
        if (PageTo < PageFrom) e.Cancel = true;
        base.OnBeginPrint(e);
    }

    protected override void OnPrintPage(PrintPageEventArgs e) {
        while (++Page < PageFrom) {
            // Fake the pages that need to be skipped by printing them to a Metafile
            IntPtr hDev = e.Graphics.GetHdc();
            try {
                using (var mf = new Metafile(hDev, e.PageBounds))
                using (var gr = Graphics.FromImage(mf)) {
                    var ppe = new PrintPageEventArgs(gr, e.MarginBounds, e.PageBounds, e.PageSettings);
                    base.OnPrintPage(ppe);
                }
            }
            finally {
                e.Graphics.ReleaseHdc(hDev);
            }

        }

        // Print the real page
        base.OnPrintPage(e);

        // No need to continue past PageTo
        if (PageTo > 0 && Page >= PageTo) e.HasMorePages = false;
    }
}
+3

. printDialog.AllowSomePages = true; . DataGridView.

.

int fromPage=0;
int toPage=0;
int pageCount=0;

PrintDialog.

if (DialogResult.OK == printDialog.ShowDialog())
{
    fromPage = printDialog.PrinterSettings.FromPage;
    toPage = printDialog.PrinterSettings.ToPage;
    printDocument1.DocumentName = "Activity Report";
    printDocument1.Print();
}

PrintPage

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
        pageCount++;
        if(pageCount >= fromPage)
        {
            // print your grid
        }
        if (bMorePagesToPrint && pageCount <= toPage)
            e.HasMorePages = true;
        else
            e.HasMorePages = false;    
}

PrintPreviewDialog, PrinterSettings PrintDocument Document.

PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
fromPage = 2;
toPage = 6;
objPPdialog.Document = printDocument1;
+1

Source: https://habr.com/ru/post/1539631/


All Articles