秀纳

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
  1using System;
  2using System.Text;
  3using System.Collections;
  4using System.Collections.Generic;
  5using System.Drawing;
  6using System.Drawing.Printing;
  7using System.Data;
  8using System.Windows.Forms;
  9
 10class GridPrinter
 11{
 12    // the grid to print
 13    private DataGridView dataGridView;
 14
 15    // the PrintDocument
 16    private PrintDocument printDocument;
 17
 18    // center printout?
 19    private bool centerOnPage;
 20
 21    // has a title?
 22    private bool hasTitle;
 23
 24    // title
 25    private string title;
 26
 27    // font
 28    private Font titleFont;
 29
 30    // title color
 31    private Color titleColor;
 32
 33    // use paging?
 34    private bool paging;
 35
 36    // row printing
 37    static int currentRow; 
 38
 39    // page printing
 40    static int pageNumber;
 41
 42    // page width
 43    private int pageWidth;
 44    
 45    // page height
 46    private int pageHeight;
 47
 48    // left margin
 49    private int leftMargin;
 50
 51    // top margin
 52    private int topMargin;
 53
 54    // right margin
 55    private int rightMargin;
 56
 57    // bottom margin
 58    private int bottomMargin;
 59
 60    // y location placeholder
 61    private float currentY; 
 62
 63    // grid sizes
 64    private float rowHeaderHeight;
 65    private List<float> rowsHeight;
 66    private List<float> columnsWidth;
 67    private float dataGridViewWidth;
 68        
 69    // column stop points
 70    private List<int[]> mColumnPoints;
 71    private List<float> mColumnPointsWidth;
 72    private int mColumnPoint;
 73
 74    public GridPrinter(DataGridView objDataGridView, PrintDocument objPrintDocument, bool bCenterOnPage, bool bHasTitle, string sTitle, Font objTitleFont, Color objTitleColor, bool bPaging)
 75    {
 76        dataGridView = objDataGridView;
 77        printDocument = objPrintDocument;
 78        centerOnPage = bCenterOnPage;
 79        hasTitle = bHasTitle;
 80        title = sTitle;
 81        titleFont = objTitleFont;
 82        titleColor = objTitleColor;
 83        paging = bPaging;
 84
 85        pageNumber = 0;
 86
 87        rowsHeight = new List<float>();
 88        columnsWidth = new List<float>();
 89
 90        mColumnPoints = new List<int[]>();
 91        mColumnPointsWidth = new List<float>();
 92
 93        if (!printDocument.DefaultPageSettings.Landscape)
 94        {
 95            pageWidth = printDocument.DefaultPageSettings.PaperSize.Width;
 96            pageHeight = printDocument.DefaultPageSettings.PaperSize.Height;
 97        }

 98        else
 99        {
100            pageHeight = printDocument.DefaultPageSettings.PaperSize.Width;
101            pageWidth = printDocument.DefaultPageSettings.PaperSize.Height;
102        }

103
104        leftMargin = printDocument.DefaultPageSettings.Margins.Left;
105        topMargin = printDocument.DefaultPageSettings.Margins.Top;
106        rightMargin = printDocument.DefaultPageSettings.Margins.Right;
107        bottomMargin = printDocument.DefaultPageSettings.Margins.Bottom;
108
109        currentRow = 0;
110    }

111
112    // calculate printing metrics
113    private void Calculate(Graphics g)
114    {
115        if (pageNumber == 0)
116        {
117            SizeF tmpSize = new SizeF();
118            Font tmpFont;
119            float tmpWidth;
120
121            dataGridViewWidth = 0;
122            for (int i = 0; i < dataGridView.Columns.Count; i++)
123            {
124                tmpFont = dataGridView.ColumnHeadersDefaultCellStyle.Font;
125                if (tmpFont == null
126                    tmpFont = dataGridView.DefaultCellStyle.Font;
127
128                tmpSize = g.MeasureString(dataGridView.Columns[i].HeaderText, tmpFont);
129                tmpWidth = tmpSize.Width;
130                rowHeaderHeight = tmpSize.Height;
131
132                for (int j = 0; j < dataGridView.Rows.Count; j++)
133                {
134                    tmpFont = dataGridView.Rows[j].DefaultCellStyle.Font;
135                    if (tmpFont == null
136                        tmpFont = dataGridView.DefaultCellStyle.Font;
137
138                    tmpSize = g.MeasureString("Anything", tmpFont);
139                    rowsHeight.Add(tmpSize.Height);
140
141                    tmpSize = g.MeasureString(dataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
142                    if (tmpSize.Width > tmpWidth)
143                        tmpWidth = tmpSize.Width;
144                }

145                if (dataGridView.Columns[i].Visible)
146                    dataGridViewWidth += tmpWidth;
147                columnsWidth.Add(tmpWidth);
148            }

149
150            int k;
151
152            int mStartPoint = 0;
153            for (k = 0; k < dataGridView.Columns.Count; k++)
154                if (dataGridView.Columns[k].Visible)
155                {
156                    mStartPoint = k;
157                    break;
158                }

159
160            int mEndPoint = dataGridView.Columns.Count;
161            for (k = dataGridView.Columns.Count - 1; k >= 0; k--)
162                if (dataGridView.Columns[k].Visible)
163                {
164                    mEndPoint = k + 1;
165                    break;
166                }

167
168            float mTempWidth = dataGridViewWidth;
169            float mTempPrintArea = (float)pageWidth - (float)leftMargin - (float)rightMargin;
170            
171            if (dataGridViewWidth > mTempPrintArea)
172            {
173                mTempWidth = 0.0F;
174                for (k = 0; k < dataGridView.Columns.Count; k++)
175                {
176                    if (dataGridView.Columns[k].Visible)
177                    {
178                        mTempWidth += columnsWidth[k];
179                        if (mTempWidth > mTempPrintArea)
180                        {
181                            mTempWidth -= columnsWidth[k];
182                            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
183                            mColumnPointsWidth.Add(mTempWidth);
184                            mStartPoint = k;
185                            mTempWidth = columnsWidth[k];
186                        }

187                    }

188                    mEndPoint = k + 1;
189                }

190            }

191
192            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
193            mColumnPointsWidth.Add(mTempWidth);
194            mColumnPoint = 0;
195        }

196    }

197
198    // header printing
199    private void DrawHeader(Graphics g)
200    {
201        currentY = (float)topMargin;
202
203        if (paging)
204        {
205            pageNumber++;
206            string PageString = "Page " + pageNumber.ToString();
207
208            StringFormat PageStringFormat = new StringFormat();
209            PageStringFormat.Trimming = StringTrimming.Word;
210            PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
211            PageStringFormat.Alignment = StringAlignment.Far;
212
213            Font PageStringFont = new Font("Arial"8, FontStyle.Regular, GraphicsUnit.Point);
214
215            RectangleF PageStringRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - (float)rightMargin - (float)leftMargin, g.MeasureString(PageString, PageStringFont).Height);
216
217            g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);
218
219            currentY += g.MeasureString(PageString, PageStringFont).Height;
220        }

221
222        if (hasTitle)
223        {
224            StringFormat TitleFormat = new StringFormat();
225            TitleFormat.Trimming = StringTrimming.Word;
226            TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
227            if (centerOnPage)
228                TitleFormat.Alignment = StringAlignment.Center;
229            else
230                TitleFormat.Alignment = StringAlignment.Near;
231
232            RectangleF TitleRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - (float)rightMargin - (float)leftMargin, g.MeasureString(title, titleFont).Height);
233
234            g.DrawString(title, titleFont, new SolidBrush(titleColor), TitleRectangle, TitleFormat);
235
236            currentY += g.MeasureString(title, titleFont).Height;
237        }

238
239        float CurrentX = (float)leftMargin;
240        if (centerOnPage)            
241            CurrentX += (((float)pageWidth - (float)rightMargin - (float)leftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
242
243        Color HeaderForeColor = dataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
244        if (HeaderForeColor.IsEmpty) 
245            HeaderForeColor = dataGridView.DefaultCellStyle.ForeColor;
246        SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);
247
248        Color HeaderBackColor = dataGridView.ColumnHeadersDefaultCellStyle.BackColor;
249        if (HeaderBackColor.IsEmpty) 
250            HeaderBackColor = dataGridView.DefaultCellStyle.BackColor;
251        SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);
252
253        Pen TheLinePen = new Pen(dataGridView.GridColor, 1);
254
255        Font HeaderFont = dataGridView.ColumnHeadersDefaultCellStyle.Font;
256        if (HeaderFont == null
257            HeaderFont = dataGridView.DefaultCellStyle.Font;
258
259        RectangleF HeaderBounds = new RectangleF(CurrentX, currentY, mColumnPointsWidth[mColumnPoint], rowHeaderHeight);
260        g.FillRectangle(HeaderBackBrush, HeaderBounds);
261
262        StringFormat CellFormat = new StringFormat();
263        CellFormat.Trimming = StringTrimming.Word;
264        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
265
266        RectangleF CellBounds;
267        float ColumnWidth;        
268        for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
269        {
270            if (!dataGridView.Columns[i].Visible) continue
271
272            ColumnWidth = columnsWidth[i];
273
274            if (dataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
275                CellFormat.Alignment = StringAlignment.Far;
276            else if (dataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
277                CellFormat.Alignment = StringAlignment.Center;
278            else
279                CellFormat.Alignment = StringAlignment.Near;
280
281            CellBounds = new RectangleF(CurrentX, currentY, ColumnWidth, rowHeaderHeight);
282
283            g.DrawString(dataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);
284
285            if (dataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) 
286                g.DrawRectangle(TheLinePen, CurrentX, currentY, ColumnWidth, rowHeaderHeight);
287
288            CurrentX += ColumnWidth;
289        }

290
291        currentY += rowHeaderHeight;
292    }

293
294    // common row printing function
295    private bool DrawRows(Graphics g)
296    {
297        Pen TheLinePen = new Pen(dataGridView.GridColor, 1);
298
299        Font RowFont;
300        Color RowForeColor;
301        Color RowBackColor;
302        SolidBrush RowForeBrush;
303        SolidBrush RowBackBrush;
304        SolidBrush RowAlternatingBackBrush;
305
306        StringFormat CellFormat = new StringFormat();
307        CellFormat.Trimming = StringTrimming.Word;
308        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
309
310        RectangleF RowBounds;
311        float CurrentX;
312        float ColumnWidth;
313        while (currentRow < dataGridView.Rows.Count)
314        {
315            if (dataGridView.Rows[currentRow].Visible) 
316            {
317                RowFont = dataGridView.Rows[currentRow].DefaultCellStyle.Font;
318                if (RowFont == null
319                    RowFont = dataGridView.DefaultCellStyle.Font;
320
321                RowForeColor = dataGridView.Rows[currentRow].DefaultCellStyle.ForeColor;
322                if (RowForeColor.IsEmpty) 
323                    RowForeColor = dataGridView.DefaultCellStyle.ForeColor;
324                RowForeBrush = new SolidBrush(RowForeColor);
325
326                RowBackColor = dataGridView.Rows[currentRow].DefaultCellStyle.BackColor;
327                if (RowBackColor.IsEmpty) 
328                {
329                    RowBackBrush = new SolidBrush(dataGridView.DefaultCellStyle.BackColor);
330                    RowAlternatingBackBrush = new SolidBrush(dataGridView.AlternatingRowsDefaultCellStyle.BackColor);
331                }

332                else 
333                {
334                    RowBackBrush = new SolidBrush(RowBackColor);
335                    RowAlternatingBackBrush = new SolidBrush(RowBackColor);
336                }

337
338                CurrentX = (float)leftMargin;
339                if (centerOnPage)                    
340                    CurrentX += (((float)pageWidth - (float)rightMargin - (float)leftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
341
342                RowBounds = new RectangleF(CurrentX, currentY, mColumnPointsWidth[mColumnPoint], rowsHeight[currentRow]);
343
344                if (currentRow % 2 == 0)
345                    g.FillRectangle(RowBackBrush, RowBounds);
346                else
347                    g.FillRectangle(RowAlternatingBackBrush, RowBounds);
348
349                for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
350                {
351                    if (!dataGridView.Columns[CurrentCell].Visible) continue
352
353                    if (dataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
354                        CellFormat.Alignment = StringAlignment.Far;
355                    else if (dataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
356                        CellFormat.Alignment = StringAlignment.Center;
357                    else
358                        CellFormat.Alignment = StringAlignment.Near;
359                    
360                    ColumnWidth = columnsWidth[CurrentCell];
361                    RectangleF CellBounds = new RectangleF(CurrentX, currentY, ColumnWidth, rowsHeight[currentRow]);
362
363                    g.DrawString(dataGridView.Rows[currentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);
364                    
365                    if (dataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None) 
366                        g.DrawRectangle(TheLinePen, CurrentX, currentY, ColumnWidth, rowsHeight[currentRow]);
367
368                    CurrentX += ColumnWidth;
369                }

370                currentY += rowsHeight[currentRow];
371
372                if ((int)currentY > (pageHeight - topMargin - bottomMargin))
373                {
374                    currentRow++;
375                    return true;
376                }

377            }

378            currentRow++;
379        }

380
381        currentRow = 0;
382        mColumnPoint++
383
384        if (mColumnPoint == mColumnPoints.Count) 
385        {
386            mColumnPoint = 0;
387            return false;
388        }

389        else
390            return true;
391    }

392
393    // the main grid printing method
394    public bool DrawDataGridView(Graphics g)
395    {
396        try
397        {
398            Calculate(g);
399            DrawHeader(g);
400            bool bContinue = DrawRows(g);
401            return bContinue;
402        }

403        catch (Exception ex)
404        {
405            MessageBox.Show("ERROR: " + ex.Message.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
406            return false;
407        }

408    }

409}

410
下载源代码
posted on 2006-10-17 20:50  秀纳  阅读(1084)  评论(2)    收藏  举报