InvoiceLayoutPrinter.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. 
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Drawing.Printing;
  8. using System.IO;
  9. using System.Runtime.Serialization.Formatters.Binary;
  10. using System.Security.Cryptography;
  11. using Curtain.Log;
  12. namespace Dongke.WinForm.Controls.InvoiceLayout
  13. {
  14. public class InvoiceLayoutPrinter
  15. {
  16. #region 常量
  17. #region 保存、读取相关
  18. // TODO 加密保存 解密读取
  19. private static byte[] KEY = new byte[] { 106, 240, 243, 74, 29, 163, 145, 29, 39, 65, 118, 96, 247, 237, 40, 121, 116, 10, 14, 50, 139, 117, 244, 163, 193, 190, 184, 66, 8, 185, 78, 73 };
  20. private static byte[] IV = new byte[] { 26, 122, 25, 28, 97, 211, 152, 32, 223, 110, 120, 242, 170, 35, 96, 93 };
  21. //private static ICryptoTransform _decryptor = null;
  22. #endregion 保存、读取相关
  23. #endregion
  24. #region 成员变量
  25. private PropertyOfLayoutBox Property = null;
  26. private GridItem OneGridItem = null;
  27. private List<LayoutItem> LayoutItems = null;
  28. private int PageWidthPixel = 0;
  29. private int PageHeightPixel = 0;
  30. private RectangleF BackImgRectangleF = RectangleF.Empty;
  31. private float _allOffsetX = 0;
  32. private float _allOffsetY = 0;
  33. private int _printPageNum = 1; // 打印页的当前页码
  34. private int _printTotalPageNum = 1; // 总页数
  35. private DataRow _printData = null;
  36. private DataTable _printGridData = null;
  37. private PrintDocument _printDocument = null; //new PrintDocument();
  38. #endregion
  39. #region 构造函数
  40. static InvoiceLayoutPrinter()
  41. {
  42. //Rijndael age = Rijndael.Create();
  43. //_decryptor = age.CreateDecryptor(KEY, IV);
  44. }
  45. private InvoiceLayoutPrinter()
  46. {
  47. //_printDocument.DocumentName = "LayoutDocument";
  48. //_printDocument.BeginPrint += new PrintEventHandler(this.printDocument_BeginPrint);
  49. //_printDocument.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
  50. }
  51. #endregion
  52. private void printDocument_BeginPrint(object sender, PrintEventArgs e)
  53. {
  54. }
  55. private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
  56. {
  57. try
  58. {
  59. e.Graphics.PageUnit = GraphicsUnit.Millimeter;
  60. e.HasMorePages = DrawPage(e.Graphics);
  61. }
  62. catch (Exception ex)
  63. {
  64. Logger.Error(ex);
  65. }
  66. }
  67. public static List<Image> Print(byte[] layout, DataRow data, DataTable detail)
  68. {
  69. if (layout == null || layout.Length == 0)
  70. {
  71. throw new System.ArgumentNullException("layout");
  72. }
  73. if (data == null)
  74. {
  75. throw new System.ArgumentNullException("data");
  76. }
  77. //if (detail == null || detail.Rows.Count == 0)
  78. //{
  79. // throw new System.ArgumentNullException("detail");
  80. //}
  81. try
  82. {
  83. InvoiceLayoutPrinter printer = new InvoiceLayoutPrinter();
  84. printer.LayoutItems = new List<LayoutItem>();
  85. printer.ReadLayout(layout);
  86. printer._printData = data;
  87. printer._printGridData = detail;
  88. //return printer.DrawImages().ToArray();
  89. return printer.DrawImages();
  90. }
  91. catch (Exception ex)
  92. {
  93. throw ex;
  94. }
  95. }
  96. public static void Print(string printerName, short copies, byte[] layout, DataRow data, DataTable detail)
  97. {
  98. if (layout == null || layout.Length == 0)
  99. {
  100. throw new System.ArgumentNullException("layout");
  101. }
  102. if (data == null)
  103. {
  104. throw new System.ArgumentNullException("data");
  105. }
  106. //if (detail == null || detail.Rows.Count == 0)
  107. //{
  108. // throw new System.ArgumentNullException("detail");
  109. //}
  110. try
  111. {
  112. InvoiceLayoutPrinter printer = new InvoiceLayoutPrinter();
  113. printer.LayoutItems = new List<LayoutItem>();
  114. printer.ReadLayout(layout);
  115. printer._printData = data;
  116. printer._printGridData = detail;
  117. using (printer._printDocument = new PrintDocument())
  118. {
  119. printer._printDocument.DocumentName = "LayoutDocument";
  120. printer._printDocument.BeginPrint += new PrintEventHandler(printer.printDocument_BeginPrint);
  121. printer._printDocument.PrintPage += new PrintPageEventHandler(printer.PrintDocument_PrintPage);
  122. printer._printDocument.PrinterSettings.PrinterName = printerName;
  123. printer._printDocument.PrinterSettings.Copies = copies;
  124. //Logger.Debug("打印开始3");
  125. printer._printDocument.Print();
  126. //Logger.Debug("打印开始4");
  127. //return printer.DrawImages().ToArray();
  128. //return printer.DrawImages();
  129. }
  130. }
  131. catch (Exception ex)
  132. {
  133. throw ex;
  134. }
  135. }
  136. #region 票据打印
  137. private void ReadLayout(byte[] layout)
  138. {
  139. try
  140. {
  141. using (MemoryStream stream = new MemoryStream(layout))
  142. {
  143. stream.Position = 0;
  144. // 反序列化
  145. BinaryFormatter formatter = new BinaryFormatter();
  146. // TODO 解密读取
  147. //if (CryptoStream)
  148. if (true)
  149. {
  150. //using (CryptoStream cStream = new CryptoStream(stream, _decryptor, CryptoStreamMode.Read))
  151. Rijndael age = Rijndael.Create();
  152. using (CryptoStream cStream = new CryptoStream(stream, age.CreateDecryptor(KEY, IV), CryptoStreamMode.Read))
  153. {
  154. this.Property = (PropertyOfLayoutBox)formatter.Deserialize(cStream);
  155. }
  156. }
  157. else
  158. {
  159. this.Property = (PropertyOfLayoutBox)formatter.Deserialize(stream);
  160. }
  161. //_lastItemRF = propertyOflayoutBox.LastItemRF;
  162. //_newItemID = propertyOflayoutBox.NewItemID;
  163. //_paperHeight = propertyOflayoutBox.PaperHeight;
  164. //_paperWidth = propertyOflayoutBox.PaperWidth;
  165. //if (_zoomType != ZoomType.Whole)
  166. //{
  167. // ChangePaperSize();
  168. //}
  169. //else
  170. //{
  171. // InitializeZoom();
  172. //}
  173. //paperArea.BackgroundImage = propertyOflayoutBox.BackgroundImage;
  174. //_backgroundImageName = propertyOflayoutBox.BackgroundImageName;
  175. //_isPrintBackground = propertyOflayoutBox.PrintBackground;
  176. //_isPrintAreaVisible = propertyOflayoutBox.PrintAreaVisible;
  177. ArrayList items = this.Property.Items;
  178. if (items != null && 0 < items.Count)
  179. {
  180. foreach (LayoutItem item in items)
  181. {
  182. //item.Init(this, false);
  183. //item.Init();
  184. this.LayoutItems.Add(item);
  185. if (item.ItemType == ItemType.Grid)
  186. {
  187. this.OneGridItem = item as GridItem;
  188. if (this.OneGridItem.HeadRowsHeight == 0)
  189. {
  190. this.OneGridItem.HeadRowsHeight = this.OneGridItem.RowsHeight;
  191. }
  192. }
  193. }
  194. }
  195. //paperArea.Select();
  196. //RefreshItemsBound();
  197. ////paperArea.Refresh();
  198. //return true;
  199. }
  200. }
  201. catch (Exception ex)
  202. {
  203. throw ex;
  204. }
  205. }
  206. private List<Image> DrawImages()
  207. {
  208. this.PageWidthPixel = LayoutCommon.MillimeterToPixel(this.Property.PaperWidth);
  209. this.PageHeightPixel = LayoutCommon.MillimeterToPixel(this.Property.PaperHeight);
  210. this._printPageNum = 1;
  211. this._printTotalPageNum = 1;
  212. //if (this.OneGridItem != null)
  213. //{
  214. // foreach (LayoutItem item in this.LayoutItems)
  215. // {
  216. // if (item.ItemType == ItemType.Grid)
  217. // {
  218. // GridItem gItem = (item as GridItem);
  219. // gItem.PrintGridSource = this._printGridData;
  220. // _printTotalPageNum = Math.Max(_printTotalPageNum, gItem.PrintTotalPageNum);
  221. // }
  222. // }
  223. //}
  224. List<Image> images = new List<Image>();
  225. //Bitmap pageImage = null;
  226. //Graphics pageGraphics = null;
  227. bool hasNextPage = true;
  228. while (hasNextPage)
  229. {
  230. Bitmap pageImage = new Bitmap(this.PageWidthPixel, this.PageHeightPixel);
  231. pageImage.SetResolution(LayoutCommon.DPI, LayoutCommon.DPI);
  232. using (Graphics pageGraphics = Graphics.FromImage(pageImage))
  233. {
  234. // TODO 白色背景
  235. pageGraphics.Clear(Color.White);
  236. //pageGraphics.FillRectangle(Brushes.White, pageGraphics.ClipBounds);
  237. pageGraphics.PageUnit = GraphicsUnit.Millimeter;
  238. hasNextPage = DrawPage(pageGraphics);
  239. images.Add(pageImage);
  240. }
  241. }
  242. return images;
  243. }
  244. private bool DrawPage(Graphics graphics)
  245. {
  246. //try
  247. {
  248. // 背景打印
  249. if (this.Property.PrintBackground)
  250. {
  251. PrintBackgroundImage(graphics);
  252. }
  253. // Item打印
  254. foreach (LayoutItem layoutItem in this.LayoutItems)
  255. {
  256. switch (layoutItem.ItemType)
  257. {
  258. case ItemType.Text:
  259. DrawTextItem(graphics, (TextItem)layoutItem);
  260. break;
  261. case ItemType.Image:
  262. DrawImageItem(graphics, (ImageItem)layoutItem);
  263. break;
  264. case ItemType.Rectangle:
  265. DrawRectangleItem(graphics, (RectangleItem)layoutItem);
  266. break;
  267. case ItemType.Ellipse:
  268. DrawEllipseItem(graphics, (EllipseItem)layoutItem);
  269. break;
  270. //case ItemType.Line:
  271. // DrawLineItem(graphics, (LineItem)layoutItem);
  272. // break;
  273. case ItemType.Grid:
  274. DrawGridItem(graphics, (GridItem)layoutItem);
  275. break;
  276. case ItemType.PageNum:
  277. DrawPageNumItem(graphics, (PageNumItem)layoutItem);
  278. break;
  279. case ItemType.TotalText:
  280. DrawTotalTextItem(graphics, (TotalTextItem)layoutItem);
  281. break;
  282. default:
  283. //throw new NotImplementedException();
  284. break;
  285. }
  286. }
  287. // 表格Item是否有下一页
  288. if (_printPageNum < _printTotalPageNum)
  289. {
  290. _printPageNum++;
  291. //e.HasMorePages = true;
  292. return true;
  293. }
  294. return false;
  295. }
  296. //catch (Exception ex)
  297. //{
  298. // throw ex;
  299. //}
  300. }
  301. #region 绘制
  302. /// <summary>
  303. /// 打印背景图片
  304. /// </summary>
  305. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  306. private void PrintBackgroundImage(Graphics graphics)
  307. {
  308. if (this.Property.BackgroundImage != null)
  309. {
  310. if (this.BackImgRectangleF.IsEmpty)
  311. {
  312. // 背景图片的高宽比例
  313. float imgWHRate = (float)this.Property.BackgroundImage.Width / (float)this.Property.BackgroundImage.Height;
  314. // 打印纸张的高宽比例
  315. float paperWHRate = this.Property.PaperWidth / this.Property.PaperHeight;
  316. // 缩放背景图片,但保持图片高宽比例
  317. if (imgWHRate > paperWHRate)
  318. {
  319. BackImgRectangleF.Width = this.Property.PaperWidth;
  320. BackImgRectangleF.Height = this.Property.PaperWidth / imgWHRate;
  321. BackImgRectangleF.X = 0;
  322. BackImgRectangleF.Y = (this.Property.PaperHeight - BackImgRectangleF.Height) / 2 + 0;
  323. }
  324. else
  325. {
  326. BackImgRectangleF.Width = this.Property.PaperHeight * imgWHRate;
  327. BackImgRectangleF.Height = this.Property.PaperHeight;
  328. BackImgRectangleF.X = (this.Property.PaperWidth - BackImgRectangleF.Width) / 2 + 0;
  329. BackImgRectangleF.Y = 0;
  330. }
  331. }
  332. // 在指定的范围绘制背景图片
  333. graphics.DrawImage(this.Property.BackgroundImage, BackImgRectangleF);
  334. }
  335. }
  336. /// <summary>
  337. /// 打印文本Item
  338. /// </summary>
  339. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  340. /// <param name="textItem">文本Item</param>
  341. private void DrawTextItem(Graphics graphics, TextItem textItem)
  342. {
  343. // 文本Item打印范围
  344. RectangleF rectangleFM = new RectangleF(
  345. _allOffsetX + textItem.Left,
  346. _allOffsetY + textItem.Top,
  347. textItem.Width,
  348. textItem.Height);
  349. RectangleF rectangleF = rectangleFM;
  350. rectangleF.Inflate(0 - LayoutConsts.TEXT_MARGIN, 0 - LayoutConsts.TEXT_MARGIN);
  351. rectangleFM.Height -= LayoutConsts.TEXT_MARGIN;
  352. object value = null;
  353. if (this._printData.Table.Columns.Contains(textItem.DataMember))
  354. {
  355. value = this._printData[textItem.DataMember];
  356. }
  357. textItem.PrintTextItem(value, graphics, rectangleFM, rectangleF);
  358. }
  359. /// <summary>
  360. /// 打印图片Item
  361. /// </summary>
  362. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  363. /// <param name="imageItem">图片Item</param>
  364. private void DrawImageItem(Graphics graphics, ImageItem imageItem)
  365. {
  366. // 图片Item打印范围
  367. RectangleF rectangleF = new RectangleF(
  368. _allOffsetX + imageItem.Left,
  369. _allOffsetY + imageItem.Top,
  370. imageItem.Width,
  371. imageItem.Height);
  372. // 在指定的范围绘制图片Item
  373. LayoutUtility.DrawImage(graphics, rectangleF, imageItem.Image);
  374. }
  375. /// <summary>
  376. /// 打印矩形Item
  377. /// </summary>
  378. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  379. /// <param name="rectangleItem">矩形Item</param>
  380. private void DrawRectangleItem(Graphics graphics, RectangleItem rectangleItem)
  381. {
  382. // 矩形Item打印范围
  383. RectangleF rectangleF = new RectangleF(
  384. _allOffsetX + rectangleItem.Left,
  385. _allOffsetY + rectangleItem.Top,
  386. rectangleItem.Width,
  387. rectangleItem.Height);
  388. float lineWidthDraw = rectangleItem.LineWidth;
  389. // 在指定的范围绘制矩形Item
  390. LayoutUtility.DrawRectangle(graphics, rectangleF, rectangleItem.LineColor,
  391. rectangleItem.FillColor, lineWidthDraw, rectangleItem.Transparent);
  392. }
  393. /// <summary>
  394. /// 打印椭圆Item
  395. /// </summary>
  396. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  397. /// <param name="ellipseItem">椭圆Item</param>
  398. private void DrawEllipseItem(Graphics graphics, EllipseItem ellipseItem)
  399. {
  400. // 椭圆Item打印范围
  401. RectangleF rectangleF = new RectangleF(
  402. _allOffsetX + ellipseItem.Left,
  403. _allOffsetY + ellipseItem.Top,
  404. ellipseItem.Width,
  405. ellipseItem.Height);
  406. float lineWidthDraw = ellipseItem.LineWidth;
  407. // 在指定的范围绘制椭圆Item
  408. LayoutUtility.DrawEllipse(graphics, rectangleF, ellipseItem.LineColor,
  409. ellipseItem.FillColor, lineWidthDraw, ellipseItem.Transparent);
  410. }
  411. /// <summary>
  412. /// 打印表格Item
  413. /// </summary>
  414. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  415. /// <param name="gridItem">表格Item</param>
  416. private void DrawGridItem(Graphics graphics, GridItem gridItem)
  417. {
  418. // 表格Item打印范围
  419. RectangleF rectangleF = new RectangleF(
  420. _allOffsetX + gridItem.Left,
  421. _allOffsetY + gridItem.Top,
  422. gridItem.Width,
  423. gridItem.Height);
  424. // 在指定的范围绘制表格Item
  425. //gridItem.DrawGridItem(graphics, rectangleF, 1, _printPageNum);
  426. gridItem.PrintGridItem(graphics, rectangleF, _printPageNum);
  427. }
  428. /// <summary>
  429. /// 打印页码Item
  430. /// </summary>
  431. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  432. /// <param name="pageNumItem">页码Item</param>
  433. private void DrawPageNumItem(Graphics graphics, PageNumItem pageNumItem)
  434. {
  435. // 文本Item打印范围
  436. RectangleF rectangleFM = new RectangleF(
  437. _allOffsetX + pageNumItem.Left,
  438. _allOffsetY + pageNumItem.Top,
  439. pageNumItem.Width,
  440. pageNumItem.Height);
  441. RectangleF rectangleF = rectangleFM;
  442. rectangleF.Inflate(0 - LayoutConsts.TEXT_MARGIN, 0 - LayoutConsts.TEXT_MARGIN);
  443. rectangleFM.Height -= LayoutConsts.TEXT_MARGIN;
  444. // 在指定的范围绘制文本Item
  445. LayoutUtility.DrawText(graphics,
  446. rectangleFM,
  447. rectangleF,
  448. pageNumItem.GetPrintText(this._printPageNum, this._printTotalPageNum),
  449. pageNumItem.Font,
  450. pageNumItem.TextColor,
  451. 0,
  452. 0,
  453. 0,
  454. pageNumItem.TextAlign,
  455. pageNumItem.TextAlignVertical,
  456. false,
  457. false,
  458. false);
  459. }
  460. /// <summary>
  461. /// 打印合计Item
  462. /// </summary>
  463. /// <param name="graphics">用于绘制的System.Drawing.Graphics</param>
  464. /// <param name="totalTextItem">合计Item</param>
  465. private void DrawTotalTextItem(Graphics graphics, TotalTextItem totalTextItem)
  466. {
  467. // 文本Item打印范围
  468. RectangleF rectangleFM = new RectangleF(
  469. _allOffsetX + totalTextItem.Left,
  470. _allOffsetY + totalTextItem.Top,
  471. totalTextItem.Width,
  472. totalTextItem.Height);
  473. RectangleF rectangleF = rectangleFM;
  474. rectangleF.Inflate(0 - LayoutConsts.TEXT_MARGIN, 0 - LayoutConsts.TEXT_MARGIN);
  475. rectangleFM.Height -= LayoutConsts.TEXT_MARGIN;
  476. if (_printPageNum != _printTotalPageNum && totalTextItem.NotTotalValue != "[#合计值#]")
  477. {
  478. LayoutUtility.DrawText(graphics,
  479. rectangleFM,
  480. rectangleF,
  481. totalTextItem.NotTotalValue,
  482. totalTextItem.NotTotalFont,
  483. totalTextItem.NotTotalColor,
  484. totalTextItem.LineSpace,
  485. totalTextItem.CharacterSpace,
  486. totalTextItem.CharacterCount,
  487. totalTextItem.NotTotalAlign,
  488. totalTextItem.NotTotalAlignVertical,
  489. totalTextItem.Wrap,
  490. totalTextItem.Clip,
  491. false);
  492. return;
  493. }
  494. // 在指定的范围绘制文本Item
  495. object value = null;
  496. if (this._printData.Table.Columns.Contains(totalTextItem.DataMember))
  497. {
  498. value = this._printData[totalTextItem.DataMember];
  499. }
  500. value = totalTextItem.ResetTextValue(value, true);
  501. LayoutUtility.DrawText(graphics,
  502. rectangleFM,
  503. rectangleF,
  504. (value == null? "": value.ToString()),
  505. totalTextItem.Font,
  506. totalTextItem.TextColor,
  507. totalTextItem.LineSpace,
  508. totalTextItem.CharacterSpace,
  509. totalTextItem.CharacterCount,
  510. totalTextItem.TextAlign,
  511. totalTextItem.NotTotalAlignVertical,
  512. totalTextItem.Wrap,
  513. totalTextItem.Clip,
  514. false);
  515. }
  516. #endregion
  517. #endregion
  518. }
  519. }