c#打印datagridview,很好

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

 

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

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

 

打印设置

打印预览

 

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

  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. // Save width & height of headres and ColumnType
  153. ColumnLefts.Add(tmpLeft);
  154. ColumnWidths.Add(tmpWidth);
  155. ColumnTypes.Add(GridCol.GetType());
  156. tmpLeft += tmpWidth;
  157. }
  158. }
  159. // Printing Current Page, Row by Row
  160. while (RowPos <= dgv.Rows.Count - 1)
  161. {
  162. DataGridViewRow GridRow = dgv.Rows[RowPos];
  163. if (GridRow.IsNewRow || (!PrintAllRows && !GridRow.Selected))
  164. {
  165. RowPos++;
  166. continue;
  167. }
  168. CellHeight = GridRow.Height;
  169. if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
  170. {
  171. DrawFooter(e, RowsPerPage);
  172. NewPage = true;
  173. PageNo++;
  174. e.HasMorePages = true;
  175. return;
  176. }
  177. else
  178. {
  179. if (NewPage)
  180. {
  181. // Draw Header
  182. e.Graphics.DrawString(PrintTitle, new Font(dgv.Font, FontStyle.Bold),
  183. Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
  184. e.Graphics.MeasureString(PrintTitle, new Font(dgv.Font,
  185. FontStyle.Bold), e.MarginBounds.Width).Height - 13);
  186. String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
  187. e.Graphics.DrawString(s, new Font(dgv.Font, FontStyle.Bold),
  188. Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
  189. e.Graphics.MeasureString(s, new Font(dgv.Font,
  190. FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
  191. e.Graphics.MeasureString(PrintTitle, new Font( new Font(dgv.Font,
  192. FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
  193. // Draw Columns
  194. tmpTop = e.MarginBounds.Top;
  195. i = 0;
  196. foreach (DataGridViewColumn GridCol in dgv.Columns)
  197. {
  198. if (!GridCol.Visible) continue;
  199. if (!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))
  200. continue;
  201. e.Graphics.FillRectangle( new SolidBrush(Color.LightGray),
  202. new Rectangle(( int) ColumnLefts[i], tmpTop,
  203. ( int)ColumnWidths[i], HeaderHeight));
  204. e.Graphics.DrawRectangle(Pens.Black,
  205. new Rectangle(( int) ColumnLefts[i], tmpTop,
  206. ( int)ColumnWidths[i], HeaderHeight));
  207. e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
  208. new SolidBrush(GridCol.InheritedStyle.ForeColor),
  209. new RectangleF(( int)ColumnLefts[i], tmpTop,
  210. ( int)ColumnWidths[i], HeaderHeight), StrFormat);
  211. i++;
  212. }
  213. NewPage = false;
  214. tmpTop += HeaderHeight;
  215. }
  216. // Draw Columns Contents
  217. i = 0;
  218. foreach (DataGridViewCell Cel in GridRow.Cells)
  219. {
  220. if (!Cel.OwningColumn.Visible) continue;
  221. if (!SelectedColumns.Contains(Cel.OwningColumn.HeaderText))
  222. continue;
  223. // For the TextBox Column
  224. if (((Type) ColumnTypes[i]).Name == "DataGridViewTextBoxColumn" ||
  225. ((Type) ColumnTypes[i]).Name == "DataGridViewLinkColumn")
  226. {
  227. e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
  228. new SolidBrush(Cel.InheritedStyle.ForeColor),
  229. new RectangleF(( int)ColumnLefts[i], ( float)tmpTop,
  230. ( int)ColumnWidths[i], ( float)CellHeight), StrFormat);
  231. }
  232. // For the Button Column
  233. else if (((Type) ColumnTypes[i]).Name == "DataGridViewButtonColumn")
  234. {
  235. CellButton.Text = Cel.Value.ToString();
  236. CellButton.Size = new Size(( int)ColumnWidths[i], CellHeight);
  237. Bitmap bmp = new Bitmap(CellButton.Width, CellButton.Height);
  238. CellButton.DrawToBitmap(bmp, new Rectangle( 0, 0,
  239. bmp.Width, bmp.Height));
  240. e.Graphics.DrawImage(bmp, new Point(( int)ColumnLefts[i], tmpTop));
  241. }
  242. // For the CheckBox Column
  243. else if (((Type) ColumnTypes[i]).Name == "DataGridViewCheckBoxColumn")
  244. {
  245. CellCheckBox.Size = new Size( 14, 14);
  246. CellCheckBox.Checked = ( bool)Cel.Value;
  247. Bitmap bmp = new Bitmap(( int)ColumnWidths[i], CellHeight);
  248. Graphics tmpGraphics = Graphics.FromImage(bmp);
  249. tmpGraphics.FillRectangle(Brushes.White, new Rectangle( 0, 0,
  250. bmp.Width, bmp.Height));
  251. CellCheckBox.DrawToBitmap(bmp,
  252. new Rectangle(( int)((bmp.Width - CellCheckBox.Width) / 2),
  253. ( int)((bmp.Height - CellCheckBox.Height) / 2),
  254. CellCheckBox.Width, CellCheckBox.Height));
  255. e.Graphics.DrawImage(bmp, new Point(( int)ColumnLefts[i], tmpTop));
  256. }
  257. // For the ComboBox Column
  258. else if (((Type) ColumnTypes[i]).Name == "DataGridViewComboBoxColumn")
  259. {
  260. CellComboBox.Size = new Size(( int)ColumnWidths[i], CellHeight);
  261. Bitmap bmp = new Bitmap(CellComboBox.Width, CellComboBox.Height);
  262. CellComboBox.DrawToBitmap(bmp, new Rectangle( 0, 0,
  263. bmp.Width, bmp.Height));
  264. e.Graphics.DrawImage(bmp, new Point(( int)ColumnLefts[i], tmpTop));
  265. e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
  266. new SolidBrush(Cel.InheritedStyle.ForeColor),
  267. new RectangleF(( int)ColumnLefts[i] + 1, tmpTop, ( int)ColumnWidths[i]
  268. - 16, CellHeight), StrFormatComboBox);
  269. }
  270. // For the Image Column
  271. else if (((Type) ColumnTypes[i]).Name == "DataGridViewImageColumn")
  272. {
  273. Rectangle CelSize = new Rectangle(( int)ColumnLefts[i],
  274. tmpTop, ( int)ColumnWidths[i], CellHeight);
  275. Size ImgSize = ((Image)(Cel.FormattedValue)).Size;
  276. e.Graphics.DrawImage((Image)Cel.FormattedValue,
  277. new Rectangle(( int)ColumnLefts[i] + ( int)((CelSize.Width - ImgSize.Width) / 2),
  278. tmpTop + ( int)((CelSize.Height - ImgSize.Height) / 2),
  279. ((Image)(Cel.FormattedValue)).Width, ((Image)(Cel.FormattedValue)).Height));
  280. }
  281. // Drawing Cells Borders
  282. e.Graphics.DrawRectangle(Pens.Black, new Rectangle(( int)ColumnLefts[i],
  283. tmpTop, ( int)ColumnWidths[i], CellHeight));
  284. i++;
  285. }
  286. tmpTop += CellHeight;
  287. }
  288. RowPos++;
  289. // For the first page it calculates Rows per Page
  290. if (PageNo == 1) RowsPerPage++;
  291. }
  292. if (RowsPerPage == 0) return;
  293. // Write Footer (Page Number)
  294. DrawFooter(e, RowsPerPage);
  295. e.HasMorePages = false;
  296. }
  297. catch (Exception ex)
  298. {
  299. MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  300. }
  301. }
  302. private static void DrawFooter(System.Drawing.Printing.PrintPageEventArgs e,
  303. int RowsPerPage)
  304. {
  305. double cnt = 0;
  306. // Detemining rows number to print
  307. if (PrintAllRows)
  308. {
  309. if (dgv.Rows[dgv.Rows.Count - 1].IsNewRow)
  310. cnt = dgv.Rows.Count - 2; // When the DataGridView doesn't allow adding rows
  311. else
  312. cnt = dgv.Rows.Count - 1; // When the DataGridView allows adding rows
  313. }
  314. else
  315. cnt = dgv.SelectedRows.Count;
  316. // Writing the Page Number on the Bottom of Page
  317. string PageNum = " 第 " + PageNo.ToString()
  318. + " 页,共 " + Math.Ceiling(( double)(cnt / RowsPerPage)).ToString()
  319. + " 页";
  320. e.Graphics.DrawString(PageNum, dgv.Font, Brushes.Black,
  321. e.MarginBounds.Left + (e.MarginBounds.Width -
  322. e.Graphics.MeasureString(PageNum, dgv.Font,
  323. e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
  324. e.MarginBounds.Height + 31);
  325. }
  326. }
  327. }


 

示例代码:testPrint

猜你喜欢

转载自blog.csdn.net/mixiu888/article/details/80916150
今日推荐