InvoiceLayoutPrinter.cs 22 KB

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