InvoiceLayoutPrinter.cs 23 KB

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