PrintDGV.cs 21 KB

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