InvoiceLayoutPrinter.cs 22 KB

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