InvoiceLayoutPrinter.cs 23 KB

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