C# 打印DataGridView 我测试通过

国外的代码,很不错,运行通过。能实现简单的设置进行打印。

 

注意点:

1、需要自己建立 Print Options 

2、要将 OK按钮设置为 dialogeResult = OK

3、行也是要选中才可以打印

4、还有几个方法是要自己写的 比较简单


原作者:http://blog.csdn.net/yjlwl1213/article/details/4376073 

              http://blog.csdn.net/followingturing/article/details/6711278

原原作者:(http://www.codeproject.com/KB/grid/PrintDataGrid_CS.aspx

 

打印设置

打印预览

 


我的print Option 窗口的一些设置(仅参考!):


        List<string> availableColumns;

        public FrmPrintOptions(List<string> AvailableColumns)
        {
            InitializeComponent();
            this.availableColumns = AvailableColumns;
        }

        private void FrmPrintOptions_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < availableColumns.Count -1; i++)
            {
                checkedListBox1.Items.Add(availableColumns[i].ToString ());
            }

        }

        public List<string > GetSelectedColumns()
        {
            List<string> SelectedColumns = new List<string>();

            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                if (!checkedListBox1.GetItemChecked(i)  ) continue;
               SelectedColumns.Add(checkedListBox1.Items[i].ToString ());
            }

            return SelectedColumns;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

解决方案构成
这个打印解决方案由一个打印设置的窗体,及一个打印类组成。
可用于以下场景:
1、显示的数据量较大,但又没有必要打印全部数据的时候
2、希望打印出的列宽能自动适应页面宽度

[csharp]  view plain copy
  1. /* *************************************************** 
  2.  * DataGridView打印类 
  3.  * 原作者:Afrasiab Cheraghi.  
  4.  *  
  5.  * **************************************************/  
  6. using System;  
  7. using System.Collections.Generic;  
  8. using System.Windows.Forms;  
  9. using System.Drawing;  
  10. using System.Collections;  
  11. using System.Data;  
  12. using System.Text;  
  13. namespace testPrint  
  14. {  
  15.     class PrintDGV  
  16.     {  
  17.         private static StringFormat StrFormat;  // Holds content of a TextBox Cell to write by DrawString  
  18.         private static StringFormat StrFormatComboBox; // Holds content of a Boolean Cell to write by DrawImage  
  19.         private static Button CellButton;       // Holds the Contents of Button Cell  
  20.         private static CheckBox CellCheckBox;   // Holds the Contents of CheckBox Cell   
  21.         private static ComboBox CellComboBox;   // Holds the Contents of ComboBox Cell  
  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.         private static string PrintTi<mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js"></mce:script><mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js"></mce:script>tle = "";  // Header of pages  
  34.         private static DataGridView dgv;        // Holds DataGridView Object to print its contents  
  35.         private static List<string> SelectedColumns = new List<string>();   // The Columns Selected by user to print.  
  36.         private static List<string> AvailableColumns = new List<string>();  // All Columns avaiable in DataGrid   
  37.         private static bool PrintAllRows = true;   // True = print all rows,  False = print selected rows      
  38.         private static bool FitToPageWidth = true// True = Fits selected columns to page width ,  False = Print columns as showed      
  39.         private static int HeaderHeight = 0;  
  40.         public static void Print_DataGridView(DataGridView dgv1)  
  41.         {  
  42.             PrintPreviewDialog ppvw;  
  43.             try   
  44.             {      
  45.                 // Getting DataGridView object to print  
  46.                 dgv = dgv1;  
  47.                 // Getting all Coulmns Names in the DataGridView  
  48.                 AvailableColumns.Clear();  
  49.                 foreach (DataGridViewColumn c in dgv.Columns)  
  50.                 {  
  51.                     if (!c.Visible) continue;  
  52.                     AvailableColumns.Add(c.HeaderText);  
  53.                 }  
  54.                 // Showing the PrintOption Form  
  55.                 PrintOptions dlg = new PrintOptions(AvailableColumns);  
  56.                 if (dlg.ShowDialog() != DialogResult.OK) return;  
  57.                 PrintTitle = dlg.PrintTitle;  
  58.                 PrintAllRows = dlg.PrintAllRows;  
  59.                 FitToPageWidth = dlg.FitToPageWidth;  
  60.                 SelectedColumns = dlg.GetSelectedColumns();  
  61.                 RowsPerPage = 0;  
  62.                 ppvw = new PrintPreviewDialog();  
  63.                 ppvw.Document = printDoc;  
  64.                 // Showing the Print Preview Page  
  65.                 printDoc.BeginPrint +=new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);  
  66.                 printDoc.PrintPage +=new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);  
  67.                 if (ppvw.ShowDialog() != DialogResult.OK)  
  68.                 {  
  69.                     printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);  
  70.                     printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);  
  71.                     return;  
  72.                 }  
  73.                 // Printing the Documnet  
  74.                 printDoc.Print();  
  75.                 printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);  
  76.                 printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);  
  77.             }  
  78.             catch (Exception ex)  
  79.             {  
  80.                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                  
  81.             }  
  82.             finally  
  83.             {  
  84.             }  
  85.         }  
  86.         private static void PrintDoc_BeginPrint(object sender,   
  87.                     System.Drawing.Printing.PrintEventArgs e)   
  88.         {  
  89.             try  
  90.             {  
  91.                 // Formatting the Content of Text Cell to print  
  92.                 StrFormat = new StringFormat();  
  93.                 StrFormat.Alignment = StringAlignment.Near;  
  94.                 StrFormat.LineAlignment = StringAlignment.Center;  
  95.                 StrFormat.Trimming = StringTrimming.EllipsisCharacter;  
  96.                 // Formatting the Content of Combo Cells to print  
  97.                 StrFormatComboBox = new StringFormat();  
  98.                 StrFormatComboBox.LineAlignment = StringAlignment.Center;  
  99.                 StrFormatComboBox.FormatFlags = StringFormatFlags.NoWrap;  
  100.                 StrFormatComboBox.Trimming = StringTrimming.EllipsisCharacter;  
  101.                 ColumnLefts.Clear();  
  102.                 ColumnWidths.Clear();  
  103.                 ColumnTypes.Clear();  
  104.                 CellHeight = 0;  
  105.                 RowsPerPage = 0;  
  106.                 // For various column types  
  107.                 CellButton = new Button();  
  108.                 CellCheckBox = new CheckBox();  
  109.                 CellComboBox = new ComboBox();  
  110.                 // Calculating Total Widths  
  111.                 TotalWidth = 0;  
  112.                 foreach (DataGridViewColumn GridCol in dgv.Columns)  
  113.                 {  
  114.                     if (!GridCol.Visible) continue;  
  115.                     if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText)) continue;  
  116.                     TotalWidth += GridCol.Width;  
  117.                 }  
  118.                 PageNo = 1;  
  119.                 NewPage = true;  
  120.                 RowPos = 0;                  
  121.             }  
  122.             catch (Exception ex)  
  123.             {  
  124.                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                  
  125.             }  
  126.         }  
  127.         private static void PrintDoc_PrintPage(object sender,   
  128.                     System.Drawing.Printing.PrintPageEventArgs e)   
  129.         {  
  130.             int tmpWidth, i;  
  131.             int tmpTop = e.MarginBounds.Top;  
  132.             int tmpLeft = e.MarginBounds.Left;  
  133.             try   
  134.             {              
  135.                 // Before starting first page, it saves Width & Height of Headers and CoulmnType  
  136.                 if (PageNo == 1)   
  137.                 {  
  138.                     foreach (DataGridViewColumn GridCol in dgv.Columns)  
  139.                     {  
  140.                         if (!GridCol.Visible) continue;  
  141.                         // Skip if the current column not selected  
  142.                         if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText)) continue;  
  143.                         // Detemining whether the columns are fitted to page or not.  
  144.                         if (FitToPageWidth)   
  145.                             tmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /   
  146.                                        (double)TotalWidth * (double)TotalWidth *   
  147.                                        ((double)e.MarginBounds.Width / (double)TotalWidth))));  
  148.                         else  
  149.                             tmpWidth = GridCol.Width;  
  150.                         HeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,  
  151.                                     GridCol.InheritedStyle.Font, tmpWidth).Height) + 11;  
  152.                           
  153.                         // Save width & height of headres and ColumnType  
  154.                         ColumnLefts.Add(tmpLeft);  
  155.                         ColumnWidths.Add(tmpWidth);  
  156.                         ColumnTypes.Add(GridCol.GetType());  
  157.                         tmpLeft += tmpWidth;  
  158.                     }  
  159.                 }  
  160.                 // Printing Current Page, Row by Row  
  161.                 while (RowPos <= dgv.Rows.Count - 1)  
  162.                 {  
  163.                     DataGridViewRow GridRow = dgv.Rows[RowPos];  
  164.                     if (GridRow.IsNewRow || (!PrintAllRows && !GridRow.Selected))  
  165.                     {  
  166.                         RowPos++;  
  167.                         continue;  
  168.                     }  
  169.                     CellHeight = GridRow.Height;  
  170.                     if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)  
  171.                     {  
  172.                         DrawFooter(e, RowsPerPage);  
  173.                         NewPage = true;  
  174.                         PageNo++;  
  175.                         e.HasMorePages = true;  
  176.                         return;  
  177.                     }  
  178.                     else  
  179.                     {  
  180.                         if (NewPage)  
  181.                         {  
  182.                             // Draw Header  
  183.                             e.Graphics.DrawString(PrintTitle, new Font(dgv.Font, FontStyle.Bold),   
  184.                                     Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -  
  185.                             e.Graphics.MeasureString(PrintTitle, new Font(dgv.Font,   
  186.                                     FontStyle.Bold), e.MarginBounds.Width).Height - 13);  
  187.                             String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();  
  188.                             e.Graphics.DrawString(s, new Font(dgv.Font, FontStyle.Bold),   
  189.                                     Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -   
  190.                                     e.Graphics.MeasureString(s, new Font(dgv.Font,   
  191.                                     FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -   
  192.                                     e.Graphics.MeasureString(PrintTitle, new Font(new Font(dgv.Font,   
  193.                                     FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);  
  194.                             // Draw Columns  
  195.                             tmpTop = e.MarginBounds.Top;  
  196.                             i = 0;  
  197.                             foreach (DataGridViewColumn GridCol in dgv.Columns)  
  198.                             {  
  199.                                 if (!GridCol.Visible) continue;  
  200.                                 if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))   
  201.                                     continue;  
  202.                                 e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),   
  203.                                     new Rectangle((int) ColumnLefts[i], tmpTop,  
  204.                                     (int)ColumnWidths[i], HeaderHeight));  
  205.                                 e.Graphics.DrawRectangle(Pens.Black,   
  206.                                     new Rectangle((int) ColumnLefts[i], tmpTop,  
  207.                                     (int)ColumnWidths[i], HeaderHeight));  
  208.                                 e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,   
  209.                                     new SolidBrush(GridCol.InheritedStyle.ForeColor),  
  210.                                     new RectangleF((int)ColumnLefts[i], tmpTop,   
  211.                                     (int)ColumnWidths[i], HeaderHeight), StrFormat);  
  212.                                 i++;  
  213.                             }  
  214.                             NewPage = false;  
  215.                             tmpTop += HeaderHeight;  
  216.                         }  
  217.                         // Draw Columns Contents  
  218.                         i = 0;  
  219.                         foreach (DataGridViewCell Cel in GridRow.Cells)  
  220.                         {  
  221.                             if (!Cel.OwningColumn.Visible) continue;  
  222.                             if (!SelectedColumns.Contains(Cel.OwningColumn.HeaderText))  
  223.                                 continue;  
  224.                             // For the TextBox Column  
  225.                             if (((Type) ColumnTypes[i]).Name == "DataGridViewTextBoxColumn" ||   
  226.                                 ((Type) ColumnTypes[i]).Name == "DataGridViewLinkColumn")  
  227.                             {  
  228.                                 e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,   
  229.                                         new SolidBrush(Cel.InheritedStyle.ForeColor),  
  230.                                         new RectangleF((int)ColumnLefts[i], (float)tmpTop,  
  231.                                         (int)ColumnWidths[i], (float)CellHeight), StrFormat);  
  232.                             }  
  233.                             // For the Button Column  
  234.                             else if (((Type) ColumnTypes[i]).Name == "DataGridViewButtonColumn")  
  235.                             {  
  236.                                 CellButton.Text = Cel.Value.ToString();  
  237.                                 CellButton.Size = new Size((int)ColumnWidths[i], CellHeight);  
  238.                                 Bitmap bmp =new Bitmap(CellButton.Width, CellButton.Height);  
  239.                                 CellButton.DrawToBitmap(bmp, new Rectangle(0, 0,   
  240.                                         bmp.Width, bmp.Height));  
  241.                                 e.Graphics.DrawImage(bmp, new Point((int)ColumnLefts[i], tmpTop));  
  242.                             }  
  243.                             // For the CheckBox Column  
  244.                             else if (((Type) ColumnTypes[i]).Name == "DataGridViewCheckBoxColumn")  
  245.                             {  
  246.                                 CellCheckBox.Size = new Size(14, 14);  
  247.                                 CellCheckBox.Checked = (bool)Cel.Value;  
  248.                                 Bitmap bmp = new Bitmap((int)ColumnWidths[i], CellHeight);  
  249.                                 Graphics tmpGraphics = Graphics.FromImage(bmp);  
  250.                                 tmpGraphics.FillRectangle(Brushes.White, new Rectangle(0, 0,   
  251.                                         bmp.Width, bmp.Height));  
  252.                                 CellCheckBox.DrawToBitmap(bmp,   
  253.                                         new Rectangle((int)((bmp.Width - CellCheckBox.Width) / 2),   
  254.                                         (int)((bmp.Height - CellCheckBox.Height) / 2),   
  255.                                         CellCheckBox.Width, CellCheckBox.Height));  
  256.                                 e.Graphics.DrawImage(bmp, new Point((int)ColumnLefts[i], tmpTop));  
  257.                             }  
  258.                             // For the ComboBox Column  
  259.                             else if (((Type) ColumnTypes[i]).Name == "DataGridViewComboBoxColumn")  
  260.                             {  
  261.                                 CellComboBox.Size = new Size((int)ColumnWidths[i], CellHeight);  
  262.                                 Bitmap bmp = new Bitmap(CellComboBox.Width, CellComboBox.Height);  
  263.                                 CellComboBox.DrawToBitmap(bmp, new Rectangle(0, 0,   
  264.                                         bmp.Width, bmp.Height));  
  265.                                 e.Graphics.DrawImage(bmp, new Point((int)ColumnLefts[i], tmpTop));  
  266.                                 e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,   
  267.                                         new SolidBrush(Cel.InheritedStyle.ForeColor),   
  268.                                         new RectangleF((int)ColumnLefts[i] + 1, tmpTop, (int)ColumnWidths[i]  
  269.                                         - 16, CellHeight), StrFormatComboBox);  
  270.                             }  
  271.                             // For the Image Column  
  272.                             else if (((Type) ColumnTypes[i]).Name == "DataGridViewImageColumn")  
  273.                             {  
  274.                                 Rectangle CelSize = new Rectangle((int)ColumnLefts[i],   
  275.                                         tmpTop, (int)ColumnWidths[i], CellHeight);  
  276.                                 Size ImgSize = ((Image)(Cel.FormattedValue)).Size;  
  277.                                 e.Graphics.DrawImage((Image)Cel.FormattedValue,   
  278.                                         new Rectangle((int)ColumnLefts[i] + (int)((CelSize.Width - ImgSize.Width) / 2),   
  279.                                         tmpTop + (int)((CelSize.Height - ImgSize.Height) / 2),   
  280.                                         ((Image)(Cel.FormattedValue)).Width, ((Image)(Cel.FormattedValue)).Height));  
  281.                             }  
  282.                             // Drawing Cells Borders   
  283.                             e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],   
  284.                                     tmpTop, (int)ColumnWidths[i], CellHeight));  
  285.                             i++;  
  286.                         }  
  287.                         tmpTop += CellHeight;  
  288.                     }  
  289.                     RowPos++;  
  290.                     // For the first page it calculates Rows per Page  
  291.                     if (PageNo == 1) RowsPerPage++;  
  292.                 }  
  293.                 if (RowsPerPage == 0) return;  
  294.                 // Write Footer (Page Number)  
  295.                 DrawFooter(e, RowsPerPage);  
  296.                 e.HasMorePages = false;  
  297.             }  
  298.             catch (Exception ex)  
  299.             {  
  300.                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                  
  301.             }  
  302.         }  
  303.         private static void DrawFooter(System.Drawing.Printing.PrintPageEventArgs e,   
  304.                     int RowsPerPage)  
  305.         {  
  306.             double cnt = 0;   
  307.             // Detemining rows number to print  
  308.             if (PrintAllRows)  
  309.             {  
  310.                 if (dgv.Rows[dgv.Rows.Count - 1].IsNewRow)   
  311.                     cnt = dgv.Rows.Count - 2; // When the DataGridView doesn't allow adding rows  
  312.                 else  
  313.                     cnt = dgv.Rows.Count - 1; // When the DataGridView allows adding rows  
  314.             }  
  315.             else  
  316.                 cnt = dgv.SelectedRows.Count;  
  317.             // Writing the Page Number on the Bottom of Page  
  318.             string PageNum = " 第 " + PageNo.ToString()  
  319.                            + " 页,共 " + Math.Ceiling((double)(cnt / RowsPerPage)).ToString()  
  320.                            + " 页";  
  321.             e.Graphics.DrawString(PageNum, dgv.Font, Brushes.Black,   
  322.                 e.MarginBounds.Left + (e.MarginBounds.Width -   
  323.                 e.Graphics.MeasureString(PageNum, dgv.Font,   
  324.                 e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +   
  325.                 e.MarginBounds.Height + 31);  
  326.         }  
  327.     }  


  328. Print
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值