root/trunk/BazaZamowien/Classes/PrintDGV.cs @ 991

Wersja 710, 19.4 KB (wprowadzona przez dorota, 18 years temu)

baza zamowien i premii 1.0.0.1

Line 
1using System;
2using System.Collections.Generic;
3using System.Windows.Forms;
4using System.Drawing;
5using System.Collections;
6using System.Data;
7using System.Text;
8
9namespace BazaZamowien.Classes
10{
11    /// <summary>
12    /// Klasa drukuj¹ca DataGridy.
13    /// </summary>
14    class PrintDGV
15    {
16        private static StringFormat StrFormat;  // Holds content of a TextBox Cell to write by DrawString
17        private static StringFormat StrFormatComboBox; // Holds content of a Boolean Cell to write by DrawImage
18        private static Button CellButton;       // Holds the Contents of Button Cell
19        private static CheckBox CellCheckBox;   // Holds the Contents of CheckBox Cell
20        private static ComboBox CellComboBox;   // Holds the Contents of ComboBox Cell
21
22        private static int TotalWidth;          // Summation of Columns widths
23        private static int RowPos;              // Position of currently printing row
24        private static bool NewPage;            // Indicates if a new page reached
25        private static int PageNo;              // Number of pages to print
26        private static ArrayList ColumnLefts = new ArrayList();  // Left Coordinate of Columns
27        private static ArrayList ColumnWidths = new ArrayList(); // Width of Columns
28        private static ArrayList ColumnTypes = new ArrayList();  // DataType of Columns
29        private static int CellHeight;          // Height of DataGrid Cell
30        private static int RowsPerPage;         // Number of Rows per Page
31        private static System.Drawing.Printing.PrintDocument printDoc =
32                       new System.Drawing.Printing.PrintDocument();  // PrintDocumnet Object used for printing
33
34        private static string PrintTitle = "";  // Header of pages
35        private static DataGridView dgv;        // Holds DataGridView Object to print its contents
36        private static List<string> SelectedColumns = new List<string>();   // The Columns Selected by user to print.
37        private static List<string> AvailableColumns = new List<string>();  // All Columns avaiable in DataGrid
38        private static bool PrintAllRows = true;   // True = print all rows,  False = print selected rows   
39        private static bool FitToPageWidth = true; // True = Fits selected columns to page width ,  False = Print columns as showed   
40        private static int HeaderHeight = 0;
41
42
43        public static void Print_DataGridView(DataGridView dgv1,int margins)
44        {
45            PrintPreviewDialog ppvw;
46            try
47                {       
48                // Getting DataGridView object to print
49                dgv = dgv1;
50
51                // Getting all Coulmns Names in the DataGridView
52                AvailableColumns.Clear();
53                foreach (DataGridViewColumn c in dgv.Columns)
54                {
55                    if (!c.Visible) continue;
56                    AvailableColumns.Add(c.HeaderText);
57                }
58
59                // Showing the PrintOption Form
60                PrintOptions dlg = new PrintOptions(AvailableColumns);
61                if (dlg.ShowDialog() != DialogResult.OK) return;
62
63                PrintTitle = dlg.PrintTitle;
64                PrintAllRows = dlg.PrintAllRows;
65                FitToPageWidth = dlg.FitToPageWidth;
66                SelectedColumns = dlg.GetSelectedColumns();
67
68                printDoc.DefaultPageSettings.Landscape = dlg.Landscape;
69                printDoc.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(margins, margins, margins, margins);
70
71                RowsPerPage = 0;
72
73                ppvw = new PrintPreviewDialog();
74                ppvw.Document = printDoc;
75
76                // Showing the Print Preview Page
77                printDoc.BeginPrint +=new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
78                printDoc.PrintPage +=new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
79                if (ppvw.ShowDialog() != DialogResult.OK)
80                {
81                    printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
82                    printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
83                    return;
84                }
85
86                // Printing the Documnet
87                printDoc.Print();
88                printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
89                printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
90                }
91                catch (Exception ex)
92                {
93                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                       
94                }
95            finally
96            {
97
98            }
99        }
100
101        private static void PrintDoc_BeginPrint(object sender,
102                    System.Drawing.Printing.PrintEventArgs e)
103        {
104            try
105                {
106                // Formatting the Content of Text Cell to print
107                StrFormat = new StringFormat();
108                StrFormat.Alignment = StringAlignment.Near;
109                StrFormat.LineAlignment = StringAlignment.Center;
110                StrFormat.Trimming = StringTrimming.EllipsisCharacter;
111
112                // Formatting the Content of Combo Cells to print
113                StrFormatComboBox = new StringFormat();
114                StrFormatComboBox.LineAlignment = StringAlignment.Center;
115                StrFormatComboBox.FormatFlags = StringFormatFlags.NoWrap;
116                StrFormatComboBox.Trimming = StringTrimming.EllipsisCharacter;
117
118                ColumnLefts.Clear();
119                ColumnWidths.Clear();
120                ColumnTypes.Clear();
121                CellHeight = 0;
122                RowsPerPage = 0;
123
124                // For various column types
125                CellButton = new Button();
126                CellCheckBox = new CheckBox();
127                CellComboBox = new ComboBox();
128
129                // Calculating Total Widths
130                TotalWidth = 0;
131                foreach (DataGridViewColumn GridCol in dgv.Columns)
132                {
133                    if (!GridCol.Visible) continue;
134                    if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText)) continue;
135                    TotalWidth += GridCol.Width;
136                }
137                PageNo = 1;
138                NewPage = true;
139                RowPos = 0;                     
140                }
141                catch (Exception ex)
142                {
143                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                       
144                }
145        }
146
147        private static void PrintDoc_PrintPage(object sender,
148                    System.Drawing.Printing.PrintPageEventArgs e)
149        {
150            int tmpWidth, i;
151            int tmpTop = e.MarginBounds.Top;
152            int tmpLeft = e.MarginBounds.Left;
153
154            try
155                {               
156                // Before starting first page, it saves Width & Height of Headers and CoulmnType
157                if (PageNo == 1)
158                {
159                    foreach (DataGridViewColumn GridCol in dgv.Columns)
160                    {
161                        if (!GridCol.Visible) continue;
162                        // Skip if the current column not selected
163                        if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText)) continue;
164
165                        // Detemining whether the columns are fitted to page or not.
166                        if (FitToPageWidth)
167                            tmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
168                                       (double)TotalWidth * (double)TotalWidth *
169                                       ((double)e.MarginBounds.Width / (double)TotalWidth))));
170                        else
171                            tmpWidth = GridCol.Width;
172
173                        HeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
174                                    GridCol.InheritedStyle.Font, tmpWidth).Height) + 11;
175                       
176                        // Save width & height of headres and ColumnType
177                        ColumnLefts.Add(tmpLeft);
178                        ColumnWidths.Add(tmpWidth);
179                        ColumnTypes.Add(GridCol.GetType());
180                        tmpLeft += tmpWidth;
181                    }
182                }
183
184                // Printing Current Page, Row by Row
185                while (RowPos <= dgv.Rows.Count - 1)
186                {
187                    DataGridViewRow GridRow = dgv.Rows[RowPos];
188                    if (GridRow.IsNewRow || (!PrintAllRows && !GridRow.Selected))
189                    {
190                        RowPos++;
191                        continue;
192                    }
193
194                    CellHeight = GridRow.Height;
195
196                    if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
197                    {
198                        DrawFooter(e, RowsPerPage);
199                        NewPage = true;
200                        PageNo++;
201                        e.HasMorePages = true;
202                        return;
203                    }
204                    else
205                    {
206                        if (NewPage)
207                        {
208                            // Draw Header
209                            e.Graphics.DrawString(PrintTitle, new Font(dgv.Font, FontStyle.Bold),
210                                    Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
211                            e.Graphics.MeasureString(PrintTitle, new Font(dgv.Font,
212                                    FontStyle.Bold), e.MarginBounds.Width).Height - 13);
213
214                            String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
215
216                            e.Graphics.DrawString(s, new Font(dgv.Font, FontStyle.Bold),
217                                    Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
218                                    e.Graphics.MeasureString(s, new Font(dgv.Font,
219                                    FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
220                                    e.Graphics.MeasureString(PrintTitle, new Font(new Font(dgv.Font,
221                                    FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
222
223                            // Draw Columns
224                            tmpTop = e.MarginBounds.Top;
225                            i = 0;
226                            foreach (DataGridViewColumn GridCol in dgv.Columns)
227                            {
228                                if (!GridCol.Visible) continue;
229                                if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))
230                                    continue;
231
232                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
233                                    new Rectangle((int) ColumnLefts[i], tmpTop,
234                                    (int)ColumnWidths[i], HeaderHeight));
235
236                                e.Graphics.DrawRectangle(Pens.Black,
237                                    new Rectangle((int) ColumnLefts[i], tmpTop,
238                                    (int)ColumnWidths[i], HeaderHeight));
239
240                                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
241                                    new SolidBrush(GridCol.InheritedStyle.ForeColor),
242                                    new RectangleF((int)ColumnLefts[i], tmpTop,
243                                    (int)ColumnWidths[i], HeaderHeight), StrFormat);
244                                i++;
245                            }
246                            NewPage = false;
247                            tmpTop += HeaderHeight;
248                        }
249
250                        // Draw Columns Contents
251                        i = 0;
252                        foreach (DataGridViewCell Cel in GridRow.Cells)
253                        {                           
254
255                            if (!Cel.OwningColumn.Visible) continue;
256                            if (!SelectedColumns.Contains(Cel.OwningColumn.HeaderText))
257                                continue;
258
259                            // For the TextBox Column
260                            if (((Type) ColumnTypes[i]).Name == "DataGridViewTextBoxColumn" ||
261                                ((Type) ColumnTypes[i]).Name == "DataGridViewLinkColumn")
262                            {
263                                e.Graphics.DrawString(Cel.FormattedValue.ToString(), Cel.InheritedStyle.Font,
264                                        new SolidBrush(Cel.InheritedStyle.ForeColor),
265                                        new RectangleF((int)ColumnLefts[i], (float)tmpTop,
266                                        (int)ColumnWidths[i], (float)CellHeight), StrFormat);
267                            }
268                            // For the Button Column
269                            else if (((Type) ColumnTypes[i]).Name == "DataGridViewButtonColumn")
270                            {
271                                CellButton.Text = Cel.Value.ToString();
272                                CellButton.Size = new Size((int)ColumnWidths[i], CellHeight);
273                                Bitmap bmp =new Bitmap(CellButton.Width, CellButton.Height);
274                                CellButton.DrawToBitmap(bmp, new Rectangle(0, 0,
275                                        bmp.Width, bmp.Height));
276                                e.Graphics.DrawImage(bmp, new Point((int)ColumnLefts[i], tmpTop));
277                            }
278                            // For the CheckBox Column
279                            else if (((Type) ColumnTypes[i]).Name == "DataGridViewCheckBoxColumn")
280                            {
281                                CellCheckBox.ThreeState = true;                               
282                                CellCheckBox.Size = new Size(14, 14);
283
284                             //   MessageBox.Show(Cel.Value.ToString());
285
286                                if ((CheckState)Cel.FormattedValue != CheckState.Indeterminate)
287                                {
288                                 //   CellCheckBox.Checked= (bool)Cel.Value;
289                                    CellCheckBox.CheckState = (bool)Cel.Value ? CheckState.Checked : CheckState.Unchecked;
290                                }
291                                else
292                                {
293                                  //  CellCheckBox.Checked = false;
294                                    CellCheckBox.CheckState = CheckState.Indeterminate;
295                                }
296                             //   CellCheckBox.Checked = (bool)Cel.Value;
297                                Bitmap bmp = new Bitmap((int)ColumnWidths[i], CellHeight);
298                                Graphics tmpGraphics = Graphics.FromImage(bmp);
299                                tmpGraphics.FillRectangle(Brushes.White, new Rectangle(0, 0,
300                                        bmp.Width, bmp.Height));
301                                CellCheckBox.DrawToBitmap(bmp,
302                                        new Rectangle((int)((bmp.Width - CellCheckBox.Width) / 2),
303                                        (int)((bmp.Height - CellCheckBox.Height) / 2),
304                                        CellCheckBox.Width, CellCheckBox.Height));
305                                e.Graphics.DrawImage(bmp, new Point((int)ColumnLefts[i], tmpTop));
306                            }
307                            // For the ComboBox Column
308                            else if (((Type) ColumnTypes[i]).Name == "DataGridViewComboBoxColumn")
309                            {
310                                CellComboBox.Size = new Size((int)ColumnWidths[i], CellHeight);
311                                Bitmap bmp = new Bitmap(CellComboBox.Width, CellComboBox.Height);
312                                CellComboBox.DrawToBitmap(bmp, new Rectangle(0, 0,
313                                        bmp.Width, bmp.Height));
314                                e.Graphics.DrawImage(bmp, new Point((int)ColumnLefts[i], tmpTop));
315                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
316                                        new SolidBrush(Cel.InheritedStyle.ForeColor),
317                                        new RectangleF((int)ColumnLefts[i] + 1, tmpTop, (int)ColumnWidths[i]
318                                        - 16, CellHeight), StrFormatComboBox);
319                            }
320                            // For the Image Column
321                            else if (((Type) ColumnTypes[i]).Name == "DataGridViewImageColumn")
322                            {
323                                Rectangle CelSize = new Rectangle((int)ColumnLefts[i],
324                                        tmpTop, (int)ColumnWidths[i], CellHeight);
325                                Size ImgSize = ((Image)(Cel.FormattedValue)).Size;
326                                e.Graphics.DrawImage((Image)Cel.FormattedValue,
327                                        new Rectangle((int)ColumnLefts[i] + (int)((CelSize.Width - ImgSize.Width) / 2),
328                                        tmpTop + (int)((CelSize.Height - ImgSize.Height) / 2),
329                                        ((Image)(Cel.FormattedValue)).Width, ((Image)(Cel.FormattedValue)).Height));
330
331                            }
332
333                            // Drawing Cells Borders
334                            e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],
335                                    tmpTop, (int)ColumnWidths[i], CellHeight));
336
337                            i++;
338
339                        }
340                        tmpTop += CellHeight;
341                    }
342
343                    RowPos++;
344                    // For the first page it calculates Rows per Page
345                    if (PageNo == 1) RowsPerPage++;
346                }
347
348                if (RowsPerPage == 0) return;
349
350                // Write Footer (Page Number)
351                DrawFooter(e, RowsPerPage);
352
353                e.HasMorePages = false;
354                }
355                catch (Exception ex)
356                {
357                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                       
358                }
359        }
360
361        private static void DrawFooter(System.Drawing.Printing.PrintPageEventArgs e,
362                    int RowsPerPage)
363        {
364            double cnt = 0;
365
366            // Detemining rows number to print
367            if (PrintAllRows)
368            {
369                if (dgv.Rows[dgv.Rows.Count - 1].IsNewRow)
370                    cnt = dgv.Rows.Count - 2; // When the DataGridView doesn't allow adding rows
371                else
372                    cnt = dgv.Rows.Count - 1; // When the DataGridView allows adding rows
373            }
374            else
375                cnt = dgv.SelectedRows.Count;
376
377            // Writing the Page Number on the Bottom of Page
378            string PageNum = PageNo.ToString() + " of " +
379                Math.Ceiling((double)(cnt / RowsPerPage)).ToString();
380
381            e.Graphics.DrawString(PageNum, dgv.Font, Brushes.Black,
382                e.MarginBounds.Left + (e.MarginBounds.Width -
383                e.Graphics.MeasureString(PageNum, dgv.Font,
384                e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
385                e.MarginBounds.Height + 31);
386        }
387    }
388}
Notatka: Zobacz TracBrowser aby uzyskać więcej informacji.