/******************************************************************************* * Copyright(c) 2012 dongke All rights reserved. / Confidential * 类的信息: * 1.程序名称:LayoutBox.cs * 2.功能描述:票据主控件 * 编辑履历: * 作者 日期 版本 修改内容 * 欧阳涛 2012/09/11 1.00 新建 *******************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Windows.Forms; namespace Dongke.WinForm.Controls.InvoiceLayout { /// /// 票据模板控件 /// public partial class LayoutBox : UserControl { #region 常量 internal const string ITEMNAME_FIX = "Free"; #region 保存、读取相关 // TODO 加密保存 解密读取 private static readonly 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 }; private static readonly byte[] IV = new byte[] { 26, 122, 25, 28, 97, 211, 152, 32, 223, 110, 120, 242, 170, 35, 96, 93 }; #endregion 保存、读取相关 #endregion 常量 #region 成员变量 #region Layout相关 private bool _isDirty; // Layout是否变更 private short _updateCount; // 更新数量 private int _newItemID; // 生成新的ItemID private LayoutBoxDataBinding _dataBinding; // 数据源绑定 private object _dataSource; // 数据源 private string _dataMember; // 数据源名 private LayoutBoxPrintDataBinding _printDataBinding; // 打印的数据源绑定 private object _printDataSource; // 打印的数据源 private string _printDataMember; // 打印的数据源名 /* Item的显示循序 * Items PaperArea.Controls * Item的显示循序 Index Index * 最前面 count-1 0 * ↓ ↑ ↓ * ↓ ↑ ↓ * ↓ ↑ ↓ * 最背面 0 count-1 */ private Comparison _comparisonItems; // 排序Item private List _items; // LayoutBox中的Item集合 private List _selectedItems; // 选择状态的Item集合 private LayoutMode _layoutMode; // Layout编辑模式 private ZoomType _zoomType; // Layout缩放模式 private int _zoom; // Layout缩放比例 private float _paperHeight; // Layout的纸张的高 private float _paperWidth; // Layout的纸张的宽 private DataFormats.Format _clipboardFormat; // 剪贴板数据格式 private string _backgroundImageName; // 背景图片名 #endregion Layout相关 #region Item选择 private bool _isMouseDownInPaperArea; // 鼠标按下 private bool _isMouseMoveInPaperArea; // 鼠标移动 private Rectangle _mouseRect; // 鼠标框选范围 #endregion Item选择 #region Item移动 private int _startX; // 鼠标按下位置X private int _startY; // 鼠标按下位置Y private int _mouseMoveX; // 鼠标移动位置X private int _mouseMoveY; // 鼠标移动位置Y private bool _isMouseDown; // 鼠标按下 private bool _isMouseMove; // 鼠标移动 private Rectangle[] _downRectangles; // 鼠标按下Item范围 private Rectangle[] _moveRectangles; // 鼠标移动Item范围 private bool _isShiftDown = false; // Shift按下 private bool _isCtrlDown = false; // Ctrl按下 #endregion Item移动 #region 打印相关 private bool _isPrintAreaVisible; // 是否标识打印范围 private bool _isPrintBackground; // 是否打印背景 private bool _landscape; // true:横向打印;false:纵向打印 private float _printOffsetX; // 打印横向偏移 private float _printOffsetY; // 打印纵向偏移 //private PrintPreviewDialogEx printPreviewDialogEx; private int _numberOfCopies = 1; // 打印份数 private int _allocationSkipCount = 0; // 分配打印开头跳过的位置数 private int _allocationNumX = 1; // 分配打印横方向的分配数 private int _allocationNumY = 1; // 分配打印纵方向的分配数 private float _allocationVerticalSpace; // 分配打印横方向的间隔 private float _allocationHorizontalSpace; // 分配打印纵方向的间隔 private float _marginLeft; // 分配打印左侧余白 private float _marginRight; // 分配打印右侧余白 private float _marginTop; // 分配打印上侧余白 private float _marginBottom; // 分配打印下侧余白 private PrintType _printType; // 打印类别 private int _printDataPosition = -1; // 打印数据源位置 private int _printDataTotal = 0; // 打印数据总数 private int _printDataCopies = -1; // 打印数据份数 private int _allocationNum = 0; // 分配打印每页的分配数 private PrintAction _printAction; // 打印种类 private RectangleF _rectangleFGreed; // 打印范围 private float _allOffsetX; // 打印横向偏移 private float _allOffsetY; // 打印纵向偏移 private float _printerOffsetX; // 打印横向偏移 private float _printerOffsetY; // 打印纵向偏移 #endregion 打印相关 #region Item相关 private int _maxItemLeft = 0; // 位置X上限(Pixel) private int _maxItemTop = 0; // 位置Y上限(Pixel) private int _maxItemWidth = 0; // 尺寸宽上限(Pixel) private int _maxItemHeight = 0; // 尺寸高上限(Pixel) private int _minItemWidth = 0; // 尺寸幅下限(Pixel) private int _minItemHeight = 0; // 尺寸高下限(Pixel) private int _pasteCount = 0; private RectangleF _lastItemRF = RectangleF.Empty; #endregion Item相关 #region GridItem相关 private int _currentPageNum = 1; // 当前页码 private int _printPageNum = 1; // 打印页的当前页码 private int _totalPageNum = 1; // 总页数 private DataSet _gridDataSet = null; // GridItem利用的数据源 #endregion GridItem相关 #endregion 成员变量 #region 构造函数 /// /// 构造函数 /// public LayoutBox() : this(InvoiceLayout.LayoutMode.Preview) { } /// /// 构造函数 /// public LayoutBox(LayoutMode layoutMode = InvoiceLayout.LayoutMode.Preview) { this._layoutMode = layoutMode; InitializeComponent(); InitializeLayoutBox(); //printPreviewDialogEx = new PrintPreviewDialogEx(); //this.printPreviewDialogEx.AutoScrollMargin = new System.Drawing.Size(0, 0); //this.printPreviewDialogEx.AutoScrollMinSize = new System.Drawing.Size(0, 0); //this.printPreviewDialogEx.ClientSize = new System.Drawing.Size(400, 300); //this.printPreviewDialogEx.Document = this.printDocument; //this.printPreviewDialogEx.Enabled = true; //this.printPreviewDialogEx.Name = "printPreviewDialogEx"; //this.printPreviewDialogEx.Visible = false; } #endregion 构造函数 #region 属性 #region Layout /// /// Item选择状态变化中 /// public bool ItemSelectionChanging { get; private set; } /// /// 一个GridItem /// public GridItem OneGridItem { get; private set; } /// /// 打印纸张 /// [Browsable(false)] public Control PaperArea { get { return paperArea; } } /// /// 打印纸张图形范围 /// [Browsable(false)] internal Microsoft.VisualBasic.PowerPacks.ShapeContainer ItemShapeContainer { get { return paperArea.ShapeContainer; } } /// /// Item图形集合 /// [Browsable(false)] internal Microsoft.VisualBasic.PowerPacks.ShapeCollection ItemShapes { get { return paperArea.ShapeContainer.Shapes; } } /// /// 获得新的ItemID /// [Browsable(false)] internal int NewItemID { get { lock (this) { return _newItemID++; } } } /// /// 获取或设置数据源 /// [Browsable(true)] [Description(" 获取或设置数据源"), Category("LayoutBox")] [DefaultValue((string)null), RefreshProperties(RefreshProperties.Repaint), AttributeProvider(typeof(IListSource))] public object DataSource { get { return _dataSource; } set { if (value != _dataSource) { _dataSource = value; if (_layoutMode == LayoutMode.Preview) { SetDataSource(); } } } } /// /// 获取或设置被用作模块的基表中的数据源名称 /// [Description("获取或设置被用作模块的基表中的数据源名称"), Category("LayoutBox")] [DefaultValue("")] public string DataMember { get { return _dataMember; } set { if (string.IsNullOrEmpty(value)) { value = string.Empty; } if (!value.Equals(_dataMember)) { _dataMember = value; if (_layoutMode == LayoutMode.Preview) { SetDataMember(); } } } } /// /// 获取数据绑定源,从外部刷新数据源 /// [Browsable(false)] [Description("获取数据绑定源,从外部刷新数据源"), Category("LayoutBox")] [DefaultValue((string)null)] public BindingSource BindingSource { get { if (_layoutMode == LayoutMode.Preview) { if (_dataBinding != null) { return _dataBinding.BindingSource; } } return null; } } /// /// 获取LayoutBox的全部Item集合 /// [Description("获取LayoutBox的全部Item集合"), Category("LayoutBox")] [Browsable(false)] public List Items { get { return _items; } } /// /// 获取LayoutBox的全部Item集合 /// [Description("获取剪贴板的内容"), Category("LayoutBox")] public DataFormats.Format ClipboardFormat { get { return GetCipboardFormat(); //return _clipboardFormat; } } /// /// 获取LayoutBox的选择状态的Item集合 /// [Description("获取LayoutBox的选择状态的Item集合"), Category("LayoutBox")] [Browsable(false)] public List SelectedItems { get { return _selectedItems; } } /// /// 获取或设置LayoutBox的编辑模式 /// [Description("获取或设置LayoutBox的编辑模式"), Category("LayoutBox")] [DefaultValue(LayoutMode.Preview)] public LayoutMode LayoutMode { get { return _layoutMode; } set { if (_layoutMode != value) { if (_layoutMode == LayoutMode.Edit) { ClearSelection(); } _layoutMode = value; if (_layoutMode == LayoutMode.Edit) { //// TODO //if (this._clipboardFormat == null) //{ // _clipboardFormat = // DataFormats.GetFormat(typeof(LayoutItem).FullName // + "{" // + Guid.NewGuid().ToString().ToUpper() // + "}"); //} tsmiAllSelect.Enabled = true; tsmiBackgroundImage.Enabled = true; tsmiPaperSize.Enabled = true; paperArea.Click += new System.EventHandler(this.paperArea_Click); paperArea.MouseDown += new System.Windows.Forms.MouseEventHandler(this.paperArea_MouseDown); paperArea.MouseMove += new System.Windows.Forms.MouseEventHandler(this.paperArea_MouseMove); paperArea.MouseUp += new System.Windows.Forms.MouseEventHandler(this.paperArea_MouseUp); // TODO Item范围内移动 paperArea.ShapeContainer.KeyDown += new KeyEventHandler(RectTracker_KeyDown); paperArea.ShapeContainer.KeyUp += new KeyEventHandler(RectTracker_KeyUp); paperArea.ShapeContainer.MouseDown += new MouseEventHandler(RectTracker_MouseDown); paperArea.ShapeContainer.MouseMove += new MouseEventHandler(RectTracker_MouseMove); paperArea.ShapeContainer.MouseUp += new MouseEventHandler(RectTracker_MouseUp); paperArea.ShapeContainer.LostFocus += new EventHandler(RectTracker_LostFocus); } else { tsmiAllSelect.Enabled = false; tsmiBackgroundImage.Enabled = false; tsmiPaperSize.Enabled = false; paperArea.Click -= new System.EventHandler(this.paperArea_Click); paperArea.MouseDown -= new System.Windows.Forms.MouseEventHandler(this.paperArea_MouseDown); paperArea.MouseMove -= new System.Windows.Forms.MouseEventHandler(this.paperArea_MouseMove); paperArea.MouseUp -= new System.Windows.Forms.MouseEventHandler(this.paperArea_MouseUp); // TODO Item范围内移动 paperArea.ShapeContainer.KeyDown -= new KeyEventHandler(RectTracker_KeyDown); paperArea.ShapeContainer.KeyUp -= new KeyEventHandler(RectTracker_KeyUp); paperArea.ShapeContainer.MouseDown -= new MouseEventHandler(RectTracker_MouseDown); paperArea.ShapeContainer.MouseMove -= new MouseEventHandler(RectTracker_MouseMove); paperArea.ShapeContainer.MouseUp -= new MouseEventHandler(RectTracker_MouseUp); paperArea.ShapeContainer.LostFocus -= new EventHandler(RectTracker_LostFocus); if (_layoutMode == LayoutMode.Preview) { SetDataSource(); SetDataMember(); SetPrintDataSource(); SetPrintDataMember(); } } } } } /// /// 获取或设置LayoutBox的缩放模式 /// [Description("获取或设置LayoutBox的缩放模式"), Category("LayoutBox")] [DefaultValue(ZoomType.Specify)] public ZoomType ZoomType { get { return _zoomType; } set { if (_zoomType != value) { _zoomType = value; if (value != ZoomType.Whole) { paperBox.AutoScroll = true; // 改变纸张大小 ChangePaperSize(); // 设置全部Item的比例 ZoomAllItems(); } else { paperBox.AutoScroll = false; // 全部Item显示 InitializeZoom(); } if (ZoomChanged != null) { ZoomChanged(this, EventArgs.Empty); } } } } /// /// 获取或设置LayoutBox的缩放比例(%) /// [Description("获取或设置LayoutBox的缩放比例"), Category("LayoutBox")] [DefaultValue(100)] public int Zoom { get { return _zoom; } set { if (0 <= value && _zoom != value) { _zoom = value; if (_zoomType == ZoomType.Specify) { // 改变纸张大小 ChangePaperSize(); // 设置全部Item的比例 ZoomAllItems(); if (ZoomChanged != null) { ZoomChanged(this, EventArgs.Empty); } } else { ZoomType = ZoomType.Specify; } } } } /// /// 获取或设置纸张的高(mm) /// [Description("获取或设置纸张的高"), Category("LayoutBox")] [DefaultValue(297f)] public float PaperHeight { get { return _paperHeight; } set { if (_layoutMode != LayoutMode.Edit) { return; } SetPaperAreaSize(_paperWidth, value); } } /// /// 获取或设置纸张的宽(mm) /// [Description("获取或设置纸张的宽"), Category("LayoutBox")] [DefaultValue(210f)] public float PaperWidth { get { return _paperWidth; } set { if (_layoutMode != LayoutMode.Edit) { return; } SetPaperAreaSize(value, _paperHeight); } } /// /// 获取纸张的背景图片名 /// [Description("获取或设置纸张的背景图片"), Category("LayoutBox")] [DefaultValue("")] public string BackgroundImageName { get { return _backgroundImageName; } } /// /// 获取或设置纸张的背景图片 /// [Description("获取或设置纸张的背景图片"), Category("LayoutBox")] [DefaultValue((string)null)] public override Image BackgroundImage { get { return paperArea.BackgroundImage; } set { paperArea.BackgroundImage = value; _backgroundImageName = string.Empty; } } /// /// 获取LayoutBox的布局是否已经改变 /// //[Description("获取LayoutBox的布局是否已经改变"), Category("LayoutBox")] [Browsable(false)] public bool Dirty { get { return _isDirty; } internal set { SetDitry(value); } } /// /// 获取或设置是否加密保存、读取流 /// [Description("获取或设置是否加密保存、读取流"), Category("LayoutBox")] [DefaultValue(true)] public bool CryptoStream = true; #endregion Layout #region 打印相关 /// /// 获取或设置打印数据源 /// [Browsable(true)] [Description("获取或设置打印数据源"), Category("打印相关")] [DefaultValue((string)null), RefreshProperties(RefreshProperties.Repaint), AttributeProvider(typeof(IListSource))] public object PrintDataSource { get { return _printDataSource; } set { if (value != _printDataSource) { _printDataSource = value; if (_layoutMode == LayoutMode.Preview) { SetPrintDataSource(); } } } } /// /// 获取或设置打印数据源 /// [Description("获取或设置打印数据源"), Category("打印相关")] [DefaultValue("")] public string PrintDataMember { get { return _printDataMember; } set { if (string.IsNullOrEmpty(value)) { value = string.Empty; } if (!value.Equals(_printDataMember)) { _printDataMember = value; if (_layoutMode == LayoutMode.Preview) { SetPrintDataMember(); } } } } /// /// 获取或设置是否用绿色虚线标识出打印区域 /// [Description("获取或设置是否用绿色虚线标识出打印区域"), Category("打印相关")] [DefaultValue(true)] public bool PrintAreaVisible { get { return _isPrintAreaVisible; } set { if (_isPrintAreaVisible != value) { _isPrintAreaVisible = value; _isDirty = true; } } } /// /// 获取或设置一个值,该值指示是否打印背景 /// [Description("获取或设置一个值,该值指示是否打印背景"), Category("打印相关")] [DefaultValue(false)] public bool PrintBackground { get { return _isPrintBackground; } set { if (_isPrintBackground != value) { _isPrintBackground = value; _isDirty = true; } } } /// /// 获取或设置一个值,该值指示是否在横向或纵向的纸张打印页面 /// [Description("获取或设置一个值,该值指示是否在横向或纵向的纸张时打印页面\r\n打印横向的页面为true;否则为false。默认是由打印机决定。"), Category("打印相关")] [DefaultValue(false)] public bool Landscape { get { return _landscape; } set { printDocument.DefaultPageSettings.Landscape = value; _landscape = value; } } /// /// 获取或设置打印纸张的大小 /// [Description("获取或设置打印纸张的大小"), Category("LayoutBox")] [AmbientValue(typeof(Size), "0, 0")] [Browsable(false)] [DefaultValue((string)null)] public PaperSize PaperSize { get { return printDocument.PrinterSettings.DefaultPageSettings.PaperSize; } set { printDocument.PrinterSettings.DefaultPageSettings.PaperSize = value; } } /// /// Defines a reusable object that sends output to a printer, when printing from a Windows Forms application /// [Description("Defines a reusable object that sends output to a printer, when printing from a Windows Forms application"), Category("打印相关")] [Browsable(false)] public PrintDocument PrintDocument { get { return printDocument; } } /// /// 获取或设置打印机的配置信息 /// [Description("获取或设置打印机的配置信息"), Category("打印相关")] [Browsable(false)] [DefaultValue((string)null)] public PrinterSettings PrinterSettings { get { return printDocument.PrinterSettings; } set { printDocument.PrinterSettings = value; _landscape = printDocument.PrinterSettings.DefaultPageSettings.Landscape; } } /// /// 获取或设置水平方向打印偏移(mm) /// [Description("获取或设置水平方向打印偏移"), Category("打印相关")] [DefaultValue(0f)] public float PrintOffsetX { get { return _printOffsetX; } set { _printOffsetX = value; } } /// /// 获取或设置垂直方向打印偏移(mm) /// [Description("获取或设置垂直方向打印偏移"), Category("打印相关")] [DefaultValue(0f)] public float PrintOffsetY { get { return _printOffsetY; } set { _printOffsetY = value; } } /// /// 获取或设置分配打印时,水平方向的分配数 /// [Description("获取或设置分配打印时,水平方向的分配数"), Category("打印相关")] [DefaultValue(1)] public int AllocationNumX { get { return _allocationNumX; } set { if (0 < value) { _allocationNumX = value; } else { _allocationNumX = 1; } } } /// /// 获取或设置分配打印时,垂直方向的分配数 /// [Description("获取或设置分配打印时,垂直方向的分配数"), Category("打印相关")] [DefaultValue(1)] public int AllocationNumY { get { return _allocationNumY; } set { if (0 < value) { _allocationNumY = value; } else { _allocationNumY = 1; } } } /// /// 获取或设置分配打印时,左侧余白(mm) /// [Description("获取或设置分配打印时,左侧余白(mm)"), Category("打印相关")] [DefaultValue(0f)] public float MarginLeft { get { return _marginLeft; } set { _marginLeft = value; } } /// /// 获取或设置分配打印时,右侧余白(mm) /// [Description("获取或设置分配打印时,右侧余白(mm)"), Category("打印相关")] [DefaultValue(0f)] public float MarginRight { get { return _marginRight; } set { _marginRight = value; } } /// /// 获取或设置分配打印时,上侧余白(mm) /// [Description("获取或设置分配打印时,上侧余白(mm)"), Category("打印相关")] [DefaultValue(0f)] public float MarginTop { get { return _marginTop; } set { _marginTop = value; } } /// /// 获取或设置分配打印时,下侧余白(mm) /// [Description("获取或设置分配打印时,下侧余白(mm)"), Category("打印相关")] [DefaultValue(0f)] public float MarginBottom { get { return _marginBottom; } set { _marginBottom = value; } } /// /// 获取或设置分配打印时,上下间隔(mm) /// [Description("获取或设置分配打印时,上下间隔(mm)"), Category("打印相关")] [DefaultValue(0f)] public float AllocationVirticalSpace { get { return _allocationVerticalSpace; } set { if (value < 0) { _allocationVerticalSpace = 0; } else { _allocationVerticalSpace = value; } } } /// /// 获取或设置分配打印时,左右间隔(mm) /// [Description("获取或设置分配打印时,左右间隔(mm)"), Category("打印相关")] [DefaultValue(0f)] public float AllocationHorizontalSpace { get { return _allocationHorizontalSpace; } set { if (value < 0) { _allocationHorizontalSpace = 0; } else { _allocationHorizontalSpace = value; } } } /// /// 获取或设置打印份数 /// [Description("获取或设置打印份数"), Category("打印相关")] [DefaultValue(1)] public int NumberOfCopies { get { return _numberOfCopies; } set { if (0 < value) { _numberOfCopies = value; } else { _numberOfCopies = 1; } } } /// /// 获取或设置分配打印时,开头跳过的位置数 /// [Description("获取或设置分配打印时,开头跳过的位置数"), Category("打印相关")] [DefaultValue(0)] public int AllocationSkipCount { get { return _allocationSkipCount; } set { if (0 < value) { _allocationSkipCount = value; } else { _allocationSkipCount = 0; } } } #endregion 打印相关 #region Item相关 /// /// 位置X上限(Pixel) /// [Browsable(false)] internal int MaxItemLeft { get { return _maxItemLeft; } } /// /// 位置Y上限(Pixel) /// [Browsable(false)] internal int MaxItemTop { get { return _maxItemTop; } } /// /// 尺寸宽上限(Pixel) /// [Browsable(false)] internal int MaxItemWidth { get { return _maxItemWidth; } } /// /// 尺寸高上限(Pixel) /// [Browsable(false)] internal int MaxItemHeight { get { return _maxItemHeight; } } /// ///尺寸宽下限(Pixel) /// [Browsable(false)] internal int MinItemWidth { get { return _minItemWidth; } } /// /// 尺寸高下限(Pixel) /// [Browsable(false)] internal int MinItemHeight { get { return _minItemHeight; } } #endregion Item相关 #endregion 属性 #region public函数 #region 保存、读取相关 /// /// 从模版中读取Layout /// /// 布局模版 /// 读取成功true;读取失败false public bool ReadLayout(byte[] bytes) { MemoryStream memoryStream = null; if (bytes != null && 0 < bytes.Length) { memoryStream = new MemoryStream(bytes); memoryStream.Position = 0; } return ReadLayout(memoryStream); } /// /// 保存Layout到布局模版 /// /// 布局模版 public byte[] WriteLayout() { MemoryStream memoryStream = new MemoryStream(); if (WriteLayout(memoryStream)) { return memoryStream.ToArray(); } return null; } /// /// 从模版中读取Layout /// /// 布局模版 /// 读取成功true;读取失败false public bool ReadLayout(Stream stream) { // TODO 异常分析 int err_level = 0; try { if (stream == null) { // 清除Layout布局 ClearLayoutBox(); //paperArea.Refresh(); return true; } err_level = 1; // TODO if (_clipboardFormat != null) { this.ClearClipboard(); //if (Clipboard.ContainsData(_clipboardFormat.Name)) //{ // CopyToClipboard(_clipboardFormat.Name, null); //} //_clipboardFormat = // DataFormats.GetFormat(typeof(LayoutItem).FullName // + "{" // + Guid.NewGuid().ToString().ToUpper() // + "}"); } err_level = 2; _lastItemRF = RectangleF.Empty; _mouseRect = Rectangle.Empty; SetDitry(false); _selectedItems.Clear(); err_level = 3; foreach (LayoutItem item in _items) { if (item.Frame != null) { item.Frame.Dispose(); item.Frame = null; } item.Selected = false; item.Dispose(); } _items.Clear(); err_level = 4; // 反序列化 BinaryFormatter formatter = new BinaryFormatter(); PropertyOfLayoutBox propertyOflayoutBox = null; // TODO 解密读取 if (CryptoStream) { Rijndael age = Rijndael.Create(); CryptoStream cStream = new CryptoStream(stream, age.CreateDecryptor(KEY, IV), CryptoStreamMode.Read); propertyOflayoutBox = (PropertyOfLayoutBox)formatter.Deserialize(cStream); } else { propertyOflayoutBox = (PropertyOfLayoutBox)formatter.Deserialize(stream); } err_level = 5; _lastItemRF = propertyOflayoutBox.LastItemRF; _newItemID = propertyOflayoutBox.NewItemID; _paperHeight = propertyOflayoutBox.PaperHeight; _paperWidth = propertyOflayoutBox.PaperWidth; if (_zoomType != ZoomType.Whole) { ChangePaperSize(); } else { InitializeZoom(); } err_level = 6; paperArea.BackgroundImage = propertyOflayoutBox.BackgroundImage; _backgroundImageName = propertyOflayoutBox.BackgroundImageName; _isPrintBackground = propertyOflayoutBox.PrintBackground; _isPrintAreaVisible = propertyOflayoutBox.PrintAreaVisible; ArrayList items = propertyOflayoutBox.Items; if (items != null && 0 < items.Count) { foreach (LayoutItem item in items) { item.Init(this, false); if (item.ItemType == ItemType.Grid) { this.OneGridItem = item as GridItem; } } } err_level = 7; paperArea.Select(); RefreshItemsBound(); //paperArea.Refresh(); return true; } catch (Exception ex) { Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, "PrintBarcode --- " + err_level, ex.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); throw ex; } } /// /// 保存Layout到布局模版 /// /// 布局模版 /// 保存成功true;保存失败false public bool WriteLayout(Stream stream) { PropertyOfLayoutBox propertyOflayoutBox = new PropertyOfLayoutBox(); propertyOflayoutBox.LastItemRF = _lastItemRF; propertyOflayoutBox.NewItemID = _newItemID; propertyOflayoutBox.PaperHeight = _paperHeight; propertyOflayoutBox.PaperWidth = _paperWidth; propertyOflayoutBox.BackgroundImage = paperArea.BackgroundImage; propertyOflayoutBox.BackgroundImageName = _backgroundImageName; propertyOflayoutBox.PrintBackground = _isPrintBackground; propertyOflayoutBox.PrintAreaVisible = _isPrintAreaVisible; propertyOflayoutBox.Items = new ArrayList(_items); // 序列化 BinaryFormatter formatter = new BinaryFormatter(); // TODO 加密保存 if (CryptoStream) { Rijndael age = Rijndael.Create(); CryptoStream cStream = new CryptoStream(stream, age.CreateEncryptor(KEY, IV), CryptoStreamMode.Write); formatter.Serialize(cStream, propertyOflayoutBox); cStream.FlushFinalBlock(); } else { formatter.Serialize(stream, propertyOflayoutBox); } return true; } /// /// 根据指定的ItemType,创建一个新Item对象 /// /// ItemType的枚举值,表示创建的项目类型 /// 是否显示属性设置对话框 /// 创建的新Item对象 public LayoutItem NewItem(ItemType itemType, bool isShowDialog) { if (_layoutMode != LayoutMode.Edit) { return null; } LayoutItem item = null; switch (itemType) { case ItemType.Text: item = NewTextItem(isShowDialog); break; case ItemType.Image: item = NewImageItem(isShowDialog); break; case ItemType.Rectangle: item = NewRectangleItem(isShowDialog); break; case ItemType.Ellipse: item = NewEllipseItem(isShowDialog); break; case ItemType.Grid: if (OneGridItem != null) { return null; } item = NewGridItem(isShowDialog); OneGridItem = item as GridItem; break; case ItemType.PageNum: item = NewPageNumItem(isShowDialog); break; case ItemType.TotalText: item = NewTotalTextItem(isShowDialog); break; case ItemType.Barcode: item = NewBarcodeItem(isShowDialog); break; case ItemType.QRcode: item = NewQRcodeItem(isShowDialog); break; default: return null; } if (item != null) { _lastItemRF.X = item.Left; _lastItemRF.Y = item.Top; if (_lastItemRF.Width < item.Width) { _lastItemRF.Width = item.Width; } _lastItemRF.Height = item.Height; _isDirty = true; SetItemChangedArgs(item, ItemChangeType.Added); } return item; } #endregion 保存、读取相关 #region Item操作相关 /// /// 根据ItemID,获取Item /// /// ItemID /// Item public LayoutItem GetItem(int itemID) { foreach (LayoutItem item in _items) { if (item.ID == itemID) { return item; } } return null; } /// /// 根据指定的ItemType,获取Item /// /// ItemType /// Item public LayoutItem[] GetItems(ItemType itemType) { //var q = from item in _items where item.ItemType ==itemType select item; Predicate isPrime = delegate(LayoutItem item) { return (item.ItemType == itemType) ? true : false; }; return _items.FindAll(isPrime).ToArray(); } /// /// 改变指定Item的选择状态 /// /// Item在Item集合中的索引 /// Item的选择状态,选中为true;未选中为true public void SelectItem(int index, bool value) { if (_layoutMode != LayoutMode.Edit) { return; } if (index < 0 || index >= Items.Count) { return; } LayoutItem item = _items[index]; SelectItemMultiple(item, value); } /// /// 改变指定Item的选择状态 /// /// Item在Item集合中的索引 /// Item的选择状态,选中为true;未选中为true public void SelectItems(int[] indexes, bool value) { if (_layoutMode != LayoutMode.Edit) { return; } List items = new List(); foreach (int index in indexes) { if (index < 0 || Items.Count <= index) { continue; } items.Add(Items[index]); } if (0 < items.Count) { SelectItemsSingle(items.ToArray(), value); } } /// /// 改变指定Item的选择状态 /// /// Item /// Item的选择状态,选中为true;未选中为true public void SelectItemSingle(LayoutItem item, bool value) { if (_layoutMode != LayoutMode.Edit || item == null) { return; } bool isChanging = false; ItemSelectionChanging = true; if (value) { if (0 < _selectedItems.Count) { LayoutItem[] selectedItems = _selectedItems.ToArray(); foreach (LayoutItem selectedItem in selectedItems) { if (item == null || item.ID == selectedItem.ID) { continue; } isChanging = true; selectedItem.Selected = false; _selectedItems.Remove(selectedItem); if (selectedItem.Frame != null) { selectedItem.Frame.Dispose(); selectedItem.Frame = null; } SetItemSelectionChangedArgs(selectedItem, false); } } } if (value != item.Selected) { if (value) { item.Frame = new ItemFrame(item); item.Selected = true; _selectedItems.Add(item); _selectedItems.Sort(_comparisonItems); paperArea.Controls.Add(item.Frame); item.Frame.BringToFront(); } else { item.Selected = false; _selectedItems.Remove(item); if (item.Frame != null) { item.Frame.Dispose(); item.Frame = null; } } isChanging = true; SetItemSelectionChangedArgs(item, value); } ItemSelectionChanging = false; if (isChanging) { if (UserSelectionChanged != null) { UserSelectionChanged(this, EventArgs.Empty); } } } /// /// 改变指定Item的选择状态 /// /// Item /// Item的选择状态,选中为true;未选中为true public void SelectItemsSingle(LayoutItem[] items, bool value) { if (_layoutMode != LayoutMode.Edit) { return; } if (items == null || items.Length <= 0) { return; } bool isChanging = false; ItemSelectionChanging = true; if (value) { if (0 < _selectedItems.Count) { LayoutItem[] selecteditems = _selectedItems.ToArray(); foreach (LayoutItem selecteditem in selecteditems) { if (selecteditem == null) { continue; } foreach (LayoutItem item in items) { if (item == null || item.ID == selecteditem.ID) { continue; } isChanging = true; selecteditem.Selected = false; _selectedItems.Remove(selecteditem); if (selecteditem.Frame != null) { selecteditem.Frame.Dispose(); selecteditem.Frame = null; } SetItemSelectionChangedArgs(selecteditem, false); } } } } foreach (LayoutItem item in items) { SelectItemMultiple(item, value, ref isChanging); } ItemSelectionChanging = false; if (isChanging) { if (UserSelectionChanged != null) { UserSelectionChanged(this, EventArgs.Empty); } } } /// /// 改变指定Item的选择状态 /// /// Item /// Item的选择状态,选中为true;未选中为true public void SelectItemMultiple(LayoutItem item, bool value) { bool isChanging = false; ItemSelectionChanging = true; SelectItemMultiple(item, value, ref isChanging); ItemSelectionChanging = false; if (isChanging) { if (UserSelectionChanged != null) { UserSelectionChanged(this, EventArgs.Empty); } } } /// /// 改变指定Item的选择状态 /// /// Item /// Item的选择状态,选中为true;未选中为true /// 是否改变 private void SelectItemMultiple(LayoutItem item, bool value, ref bool isChanging) { if (_layoutMode != LayoutMode.Edit || item == null) { return; } if (value != item.Selected) { if (value) { item.Frame = new ItemFrame(item); item.Selected = true; _selectedItems.Add(item); _selectedItems.Sort(_comparisonItems); paperArea.Controls.Add(item.Frame); item.Frame.BringToFront(); } else { item.Selected = false; _selectedItems.Remove(item); if (item.Frame != null) { item.Frame.Dispose(); item.Frame = null; } } isChanging = true; SetItemSelectionChangedArgs(item, value); } } /// /// 改变指定Item的选择状态 /// /// Item /// Item的选择状态,选中为true;未选中为true public void SelectItemsMultiple(LayoutItem[] items, bool value) { if (_layoutMode != LayoutMode.Edit) { return; } if (items == null || items.Length <= 0) { return; } bool isChanging = false; ItemSelectionChanging = true; foreach (LayoutItem item in items) { SelectItemMultiple(item, value, ref isChanging); } ItemSelectionChanging = false; if (isChanging) { if (UserSelectionChanged != null) { UserSelectionChanged(this, EventArgs.Empty); } } } /// /// 取消所有选择的项目 /// public void ClearSelection() { if (_layoutMode != LayoutMode.Edit) { return; } bool isChanging = false; ItemSelectionChanging = true; if (0 < _selectedItems.Count) { LayoutItem[] selectedItems = _selectedItems.ToArray(); foreach (LayoutItem selectedItem in selectedItems) { if (selectedItem == null) { continue; } isChanging = true; selectedItem.Selected = false; _selectedItems.Remove(selectedItem); if (selectedItem.Frame != null) { selectedItem.Frame.Dispose(); selectedItem.Frame = null; } SetItemSelectionChangedArgs(selectedItem, false); } } ItemSelectionChanging = false; if (isChanging) { if (UserSelectionChanged != null) { UserSelectionChanged(this, EventArgs.Empty); } } } /// /// 剪切选中的Item到剪切板 /// public void CutItem() { if (_layoutMode != LayoutMode.Edit) { return; } _pasteCount = 0; if (0 < _selectedItems.Count) { CopyToClipboard(new ArrayList(_selectedItems)); DeleteItem(); _isDirty = true; } } /// /// 粘贴Item到LayoutBox /// public void PasteItem() { if (_layoutMode != LayoutMode.Edit) { return; } object objectItems = GetFromClipboard(); if (objectItems == null) { _pasteCount = 0; return; } ArrayList items = objectItems as ArrayList; if (items == null || items.Count <= 0) { _pasteCount = 0; return; } List layoutItems = new List(); _pasteCount++; foreach (LayoutItem item in items) { if (item == null || item is GridItem) { continue; } int id = item.ID; TextItem textItem = null; string dataMember = null; string defaultItemName = null; string textItemName = null; if (item.ItemType == ItemType.Text || item.ItemType == ItemType.TotalText) { textItem = item as TextItem; if (textItem != null) { dataMember = textItem.DataMember; defaultItemName = textItem.DefaultItemName; textItemName = textItem.TextItemName; } } item.Init(this, true); if (textItem != null) { textItem.DataMember = dataMember; textItem.DefaultItemName = defaultItemName; textItem.TextItemName = textItemName; } //int top = item.ShapeBounds.Top + (item.ShapeBounds.Height + 2) * _pasteCount; // 下移60mm //int top = item.ShapeBounds.Top + 227; ////item.ResetItemLocation(item.ShapeBounds.Left, top); //设置图形像素坐标时刷新毫米坐标 //item.MoveItem(item.ShapeBounds.Left, top); // 下移5mm item.Top += 5; _isDirty = true; layoutItems.Add(item); if (this.UserAddedItem != null) { ItemChangedEventArgs e = new ItemChangedEventArgs(); e.Item = item; e.ChangedType = ItemChangeType.Added; e.ItemID = item.ID; this.UserAddedItem(this, e); } SetItemChangedArgs(item, ItemChangeType.Added); } // 粘贴的新Item为选择状态 if (1 == layoutItems.Count) { SelectItemSingle(layoutItems[0], true); } else if (1 < layoutItems.Count) { ClearSelection(); SelectItemsMultiple(layoutItems.ToArray(), true); } } /// /// 复制选中的Item到剪切板 /// public void CopyItem() { if (_layoutMode != LayoutMode.Edit) { return; } _pasteCount = 0; if (0 < _selectedItems.Count) { CopyToClipboard(new ArrayList(_selectedItems)); } } /// /// 删除选中的Item /// public void DeleteItem() { if (_layoutMode != LayoutMode.Edit) { return; } if (0 < _selectedItems.Count) { LayoutItem[] items = _selectedItems.ToArray(); foreach (LayoutItem item in items) { ItemChangedEventArgs e = new ItemChangedEventArgs(); e.Item = item; e.ChangedType = ItemChangeType.Deleted; e.ItemID = item.ID; DeletetItem(item); if (this.UserDeletedItem != null) { this.UserDeletedItem(this, e); } } } } /// /// 根据ItemID删除Item /// /// ItemID public void DeletetItem(int itemID) { if (_layoutMode != LayoutMode.Edit) { return; } LayoutItem item = GetItem(itemID); DeletetItem(item); } /// /// 删除指定的Item /// /// item public void DeletetItem(LayoutItem item) { if (_layoutMode != LayoutMode.Edit || item == null) { return; } if (item.Selected) { item.Selected = false; _selectedItems.Remove(item); if (item.Frame != null) { item.Frame.Dispose(); item.Frame = null; } SetItemSelectionChangedArgs(item, false); } _items.Remove(item); item.Dispose(); _isDirty = true; SetItemChangedArgs(item, ItemChangeType.Deleted); } /// /// 重绘Item的内容 /// public void RefreshItems() { if (_layoutMode == LayoutMode.Preview) { RefreshItemsCurrentPositionValue(); } } /// /// 对齐选定的Item /// /// 对齐方式 public void ArrangeItem(ArrangeType arrangeType) { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } switch (arrangeType) { case ArrangeType.Left: ArrangeItemsLeft(); break; case ArrangeType.Right: ArrangeItemsRight(); break; case ArrangeType.HorizontalCenter: ArrangeItemsHorizontalCenter(); break; case ArrangeType.Top: ArrangeItemsTop(); break; case ArrangeType.Bottom: ArrangeItemsBottom(); break; case ArrangeType.VerticalCenter: ArrangeItemsVerticalCenter(); break; //case ArrangeType.LeftRight: // ArrangeItemsLeftRight(); // break; //case ArrangeType.TopBottom: // ArrangeItemsTopBottom(); // break; default: break; } } /// /// 所有选中的Item的顶部对齐 /// public void ArrangeItemsTop() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } float minTop = paperArea.Height; foreach (LayoutItem item in _selectedItems) { minTop = Math.Min(item.Top, minTop); } foreach (LayoutItem item in _selectedItems) { item.Top = minTop; } _isDirty = true; } /// /// 所有选中的Item的底部对齐 /// public void ArrangeItemsBottom() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } float maxBottom = 0; foreach (LayoutItem item in _selectedItems) { maxBottom = Math.Max(item.Bottom, maxBottom); } foreach (LayoutItem item in _selectedItems) { item.Top = maxBottom - item.Height; } _isDirty = true; } /// /// 所有选中的Item的左侧对齐 /// public void ArrangeItemsLeft() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } float minLeft = paperArea.Width; foreach (LayoutItem item in _selectedItems) { minLeft = Math.Min(item.Left, minLeft); } foreach (LayoutItem item in _selectedItems) { item.Left = minLeft; } _isDirty = true; } /// /// 所有选中的Item的右侧对齐 /// public void ArrangeItemsRight() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } float maxRight = 0; foreach (LayoutItem item in _selectedItems) { maxRight = Math.Max(item.Right, maxRight); } foreach (LayoutItem item in _selectedItems) { item.Left = maxRight - item.Width; } _isDirty = true; } /// /// 所有选中的Item的垂直方向中心对齐 /// public void ArrangeItemsVerticalCenter() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } float minTop = paperArea.Height; float maxBottom = 0; foreach (LayoutItem item in _selectedItems) { minTop = Math.Min(item.Top, minTop); maxBottom = Math.Max(item.Bottom, maxBottom); } float center = (minTop + maxBottom) / 2; foreach (LayoutItem item in _selectedItems) { item.Top = center - item.Height / 2; } _isDirty = true; } /// /// 所有选中的Item的水平方向中心对齐 /// public void ArrangeItemsHorizontalCenter() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count < 2) { return; } float minLeft = paperArea.Width; float maxRight = 0; foreach (LayoutItem item in _selectedItems) { minLeft = Math.Min(item.Left, minLeft); maxRight = Math.Max(item.Right, maxRight); } float center = (minLeft + maxRight) / 2; foreach (LayoutItem item in _selectedItems) { item.Left = center - item.Width / 2; } _isDirty = true; } /// /// 更改所选Item(Z顺序)的顺序 /// /// 指定的位置MovingPosition的枚举值,Z-顺序 public void ChangeItemOrder(MovingPosition position) { if (_layoutMode != LayoutMode.Edit || 0 == _selectedItems.Count) { return; } switch (position) { case MovingPosition.Foremost: ChangeItemsOrderForemost(); break; case MovingPosition.Aftermost: ChangeItemsOrderAftermost(); break; case MovingPosition.Front: ChangeItemsOrderFront(); break; case MovingPosition.Back: ChangeItemsOrderBack(); break; default: break; } } /// /// 将选定的Item移动到最前面 /// public void ChangeItemsOrderForemost() { if (_layoutMode != LayoutMode.Edit) { return; } int count = _selectedItems.Count; if (0 < count) { foreach (LayoutItem item in _selectedItems) { paperArea.ShapeContainer.Shapes.SetChildIndex(item.Shape, 0); } paperArea.ShapeContainer.Refresh(); _items.Sort(_comparisonItems); _isDirty = true; } } /// /// 将选定的Item上移一层 /// public void ChangeItemsOrderFront() { if (_layoutMode != LayoutMode.Edit) { return; } int count = _selectedItems.Count; if (0 < count) { int childIndex = paperArea.ShapeContainer.Shapes. GetChildIndex(_selectedItems[count - 1].Shape) - 1; childIndex = (childIndex < 0) ? 0 : childIndex; foreach (LayoutItem item in _selectedItems) { paperArea.ShapeContainer.Shapes.SetChildIndex(item.Shape, childIndex); } paperArea.ShapeContainer.Refresh(); _items.Sort(_comparisonItems); _isDirty = true; } } /// /// 将选定的Item移动到最后面 /// public void ChangeItemsOrderBack() { if (_layoutMode != LayoutMode.Edit) { return; } int count = _selectedItems.Count; if (0 < count) { int childIndex = paperArea.ShapeContainer.Shapes. GetChildIndex(_selectedItems[0].Shape) + 1; for (int i = count - 1; 0 <= i; i--) { paperArea.ShapeContainer.Shapes.SetChildIndex(_selectedItems[i].Shape, childIndex); } paperArea.ShapeContainer.Refresh(); _items.Sort(_comparisonItems); _isDirty = true; } } /// /// 将选定的Item下移一层 /// public void ChangeItemsOrderAftermost() { if (_layoutMode != LayoutMode.Edit) { return; } int count = _selectedItems.Count; if (0 < count) { for (int i = count - 1; 0 <= i; i--) { paperArea.ShapeContainer.Shapes.SetChildIndex(_selectedItems[i].Shape, int.MaxValue); } paperArea.ShapeContainer.Refresh(); _items.Sort(_comparisonItems); _isDirty = true; } } /// /// 将LayoutBox的Dirty状态修改成false /// 接受之前所有的改变 /// public void AcceptChange() { this._isDirty = false; } #endregion Item操作相关 #region 设置对话框 /// /// 显示背景设置的对话框 /// /// /// DialogResult.OK:设置成功
/// DialogResult.Cancel:取消设置
/// DialogResult.None:LayoutBox不是编辑模式 ///
public DialogResult ShowBackgroundSettingDialog() { if (_layoutMode != LayoutMode.Edit) { return DialogResult.None; } using (BackgroundSetting backgroundSetting = new BackgroundSetting(this)) { DialogResult result = backgroundSetting.ShowDialog(); if (result == DialogResult.OK) { _backgroundImageName = backgroundSetting.BackgroundImageName; paperArea.BackgroundImage = backgroundSetting.BackgroundImage; _isDirty = true; } return result; } } /// /// 显示纸张设置的对话框 /// /// /// DialogResult.OK:设置成功
/// DialogResult.Cancel:取消设置
/// DialogResult.None:LayoutBox不是编辑模式 ///
public DialogResult ShowPaperPropertyDialog() { if (_layoutMode != LayoutMode.Edit) { return DialogResult.None; } using (PaperAreaSetting paperSizeSetting = new PaperAreaSetting()) { paperSizeSetting.PaperWidth = _paperWidth; paperSizeSetting.PaperHeight = _paperHeight; DialogResult result = paperSizeSetting.ShowDialog(); if (result == DialogResult.OK) { SetPaperAreaSize(paperSizeSetting.PaperWidth, paperSizeSetting.PaperHeight); } return result; } } /// /// 显示选中Item的属性设置画面 /// /// /// DialogResult.OK:选中的Item有效,设置成功
/// DialogResult.Cancel:选中的Item有效,取消设置
/// DialogResult.None:LayoutBox不是编辑模式,或选中的Item不是一个 ///
public DialogResult ShowItemPropertyDialog() { if (_layoutMode != LayoutMode.Edit || _selectedItems.Count != 1) { return DialogResult.None; } LayoutItem item = _selectedItems[0]; if (item != null) { return item.ShowItemPropertyDialog(); } return DialogResult.None; } #endregion 设置对话框 #region 打印相关 /// /// 使用打印机已设置的信息进行打印测试 /// public bool PrintTest() { if (_layoutMode != LayoutMode.Edit) { return false; } _printType = PrintType.PrintTest; if (CheckPrintSetting()) { DialogResult result = printDialog.ShowDialog(this); if (result == DialogResult.OK) { printDocument.PrinterSettings.PrinterName = printDialog.PrinterSettings.PrinterName; if (printDocument.PrinterSettings.IsValid) { printDocument.Print(); return true; } else { MessageBox.Show(string.Format("打印机名({0}/{1})不正确。" , printDocument.PrinterSettings.PrinterName , printDialog.PrinterSettings.PrinterName), "打印失败", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return false; } } } return false; } /// /// 使用打印机已设置的信息进行打印 /// public bool Print(bool checkPrintSetting = true) { //#if DEBUG // Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, // "Print", // "begin", // DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), // Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); //#endif _printType = PrintType.Print; if (!checkPrintSetting || CheckPrintSetting()) { printDocument.Print(); //#if DEBUG // Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, // "Print", // "end", // DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), // Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); //#endif return true; } return false; } /// /// 使用打印机已设置的信息进行分配打印 /// public bool AllocationPrint() { _printType = PrintType.AllocationPrint; if (CheckPrintSetting()) { printDocument.Print(); return true; } return false; } /// /// 使用打印机已设置的信息进行打印预览 /// public bool PrintPreview() { _printType = PrintType.PrintPreview; if (CheckPrintSetting()) { //printPreviewDialogEx.WindowState = FormWindowState.Maximized; //printPreviewDialogEx.PrintPreviewControl.Columns = 1; //printPreviewDialogEx.PrintPreviewControl.Rows = 1; //printPreviewDialogEx.PrintPreviewControl.StartPage = 0; //printPreviewDialogEx.ShowDialog(); printPreviewDialog1.WindowState = FormWindowState.Maximized; printPreviewDialog1.PrintPreviewControl.Columns = 1; printPreviewDialog1.PrintPreviewControl.Rows = 1; printPreviewDialog1.PrintPreviewControl.StartPage = 0; printPreviewDialog1.ShowDialog(); return true; } return false; } /// /// 使用打印机已设置的信息进行分配打印预览 /// public bool AllocationPrintPreview() { _printType = PrintType.AllocationPrintPreview; if (CheckPrintSetting()) { //printPreviewDialogEx.WindowState = FormWindowState.Maximized; //printPreviewDialogEx.PrintPreviewControl.Columns = 1; //printPreviewDialogEx.PrintPreviewControl.Rows = 1; //printPreviewDialogEx.PrintPreviewControl.StartPage = 0; //printPreviewDialogEx.ShowDialog(); printPreviewDialog1.WindowState = FormWindowState.Maximized; printPreviewDialog1.PrintPreviewControl.Columns = 1; printPreviewDialog1.PrintPreviewControl.Rows = 1; printPreviewDialog1.PrintPreviewControl.StartPage = 0; printPreviewDialog1.ShowDialog(); return true; } return false; } #endregion 打印相关 #endregion public函数 #region private函数 #region 保存、读取相关 /// /// 创建一个新条码文本Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewQRcodeItem(bool isShowDialog) { TextItem textItem = new TextItem(null); textItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(LayoutCommon.DefaultTextItemSizeWidth, LayoutCommon.DefaultTextItemSizeHeight); if (isShowDialog) { using (TextItemSetting itemPropertySetting = new TextItemSetting()) { itemPropertySetting.IsNew = true; itemPropertySetting.IsDataBinding = false; itemPropertySetting.TextPreview = "1234567890"; itemPropertySetting.TextWidth = 25; itemPropertySetting.TextHeight = 25; itemPropertySetting.TextFont = textItem.Font; itemPropertySetting.TextLocationX = newItemLocation.X; itemPropertySetting.TextLocationY = newItemLocation.Y; itemPropertySetting.ItemStyle = ItemStyle.QRCode; itemPropertySetting.ItemName = LayoutBox.ITEMNAME_FIX + _newItemID; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { textItem.Init(this, true); textItem.IsDataBinding = false; textItem.Left = itemPropertySetting.TextLocationX; textItem.Top = itemPropertySetting.TextLocationY; textItem.Width = itemPropertySetting.TextWidth; textItem.Height = itemPropertySetting.TextHeight; textItem.LineSpace = itemPropertySetting.LineSpace; textItem.CharacterSpace = itemPropertySetting.CharacterSpace; textItem.CharacterCount = itemPropertySetting.CharacterCount; textItem.Font = itemPropertySetting.TextFont; textItem.Wrap = itemPropertySetting.Wrap; textItem.TextColor = itemPropertySetting.TextColor; textItem.TextAlign = itemPropertySetting.TextAlign; textItem.TextAlignVertical = itemPropertySetting.TextAlignVertical; textItem.DisplayValue = itemPropertySetting.TextPreview; textItem.ItemStyle = itemPropertySetting.ItemStyle; textItem.TextItemName = itemPropertySetting.ItemName; textItem.Format = itemPropertySetting.TextFormat; textItem.Culture = itemPropertySetting.Culture; textItem.DefaultValue = itemPropertySetting.DefaultValue; textItem.IsNew = false; textItem.PicColumn = false; textItem.PicMargin = itemPropertySetting.chkM.Checked; textItem.FixedRatio = itemPropertySetting.chkFixedRatio.Checked; textItem.SetDrawProperty(); return textItem; } else { return null; } } } else { textItem.Init(this, true); textItem.Left = newItemLocation.X; textItem.Top = newItemLocation.Y; textItem.ItemStyle = ItemStyle.QRCode; textItem.Width = 25; textItem.Height = 25; textItem.DisplayValue = "1234567890"; textItem.IsNew = false; textItem.PicColumn = false; textItem.PicMargin = false; textItem.FixedRatio = false; textItem.SetDrawProperty(); return textItem; } } /// /// 创建一个新条码文本Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewBarcodeItem(bool isShowDialog) { TextItem textItem = new TextItem(null); textItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(LayoutCommon.DefaultTextItemSizeWidth, LayoutCommon.DefaultTextItemSizeHeight); if (isShowDialog) { using (TextItemSetting itemPropertySetting = new TextItemSetting()) { itemPropertySetting.IsNew = true; itemPropertySetting.IsDataBinding = false; itemPropertySetting.TextPreview = "12345678901"; itemPropertySetting.TextWidth = 50; itemPropertySetting.TextHeight = 20; itemPropertySetting.TextFont = textItem.Font; itemPropertySetting.TextLocationX = newItemLocation.X; itemPropertySetting.TextLocationY = newItemLocation.Y; itemPropertySetting.ItemStyle = ItemStyle.Barcode; itemPropertySetting.ItemName = LayoutBox.ITEMNAME_FIX + _newItemID; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { textItem.Init(this, true); textItem.IsDataBinding = false; textItem.Left = itemPropertySetting.TextLocationX; textItem.Top = itemPropertySetting.TextLocationY; textItem.Width = itemPropertySetting.TextWidth; textItem.Height = itemPropertySetting.TextHeight; textItem.LineSpace = itemPropertySetting.LineSpace; textItem.CharacterSpace = itemPropertySetting.CharacterSpace; textItem.CharacterCount = itemPropertySetting.CharacterCount; textItem.Font = itemPropertySetting.TextFont; textItem.Wrap = itemPropertySetting.Wrap; textItem.TextColor = itemPropertySetting.TextColor; textItem.TextAlign = itemPropertySetting.TextAlign; textItem.TextAlignVertical = itemPropertySetting.TextAlignVertical; textItem.DisplayValue = itemPropertySetting.TextPreview; textItem.ItemStyle = itemPropertySetting.ItemStyle; textItem.TextItemName = itemPropertySetting.ItemName; textItem.Format = itemPropertySetting.TextFormat; textItem.Culture = itemPropertySetting.Culture; textItem.DefaultValue = itemPropertySetting.DefaultValue; textItem.IsNew = false; textItem.PicColumn = false; textItem.PicMargin = itemPropertySetting.chkM.Checked; textItem.FixedRatio = itemPropertySetting.chkFixedRatio.Checked; textItem.SetDrawProperty(); return textItem; } else { return null; } } } else { textItem.Init(this, true); textItem.Left = newItemLocation.X; textItem.Top = newItemLocation.Y; textItem.ItemStyle = ItemStyle.Barcode; textItem.Width = 50; textItem.Height = 20; textItem.DisplayValue = "12345678901"; textItem.IsNew = false; textItem.PicColumn = false; textItem.PicMargin = false; textItem.FixedRatio = false; textItem.SetDrawProperty(); return textItem; } } /// /// 创建一个新文本Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewTextItem(bool isShowDialog) { TextItem textItem = new TextItem(null); textItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(LayoutCommon.DefaultTextItemSizeWidth, LayoutCommon.DefaultTextItemSizeHeight); if (isShowDialog) { using (TextItemSetting itemPropertySetting = new TextItemSetting()) { itemPropertySetting.IsNew = true; itemPropertySetting.IsDataBinding = false; itemPropertySetting.TextFont = textItem.Font; itemPropertySetting.TextLocationX = newItemLocation.X; itemPropertySetting.TextLocationY = newItemLocation.Y; itemPropertySetting.ItemStyle = ItemStyle.Other; itemPropertySetting.ItemName = LayoutBox.ITEMNAME_FIX + _newItemID; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { textItem.Init(this, true); textItem.IsDataBinding = false; textItem.Left = itemPropertySetting.TextLocationX; textItem.Top = itemPropertySetting.TextLocationY; textItem.Width = itemPropertySetting.TextWidth; textItem.Height = itemPropertySetting.TextHeight; textItem.LineSpace = itemPropertySetting.LineSpace; textItem.CharacterSpace = itemPropertySetting.CharacterSpace; textItem.CharacterCount = itemPropertySetting.CharacterCount; textItem.Font = itemPropertySetting.TextFont; textItem.Wrap = itemPropertySetting.Wrap; textItem.TextColor = itemPropertySetting.TextColor; textItem.TextAlign = itemPropertySetting.TextAlign; textItem.TextAlignVertical = itemPropertySetting.TextAlignVertical; textItem.DisplayValue = itemPropertySetting.TextPreview; textItem.ItemStyle = itemPropertySetting.ItemStyle; textItem.TextItemName = itemPropertySetting.ItemName; textItem.Format = itemPropertySetting.TextFormat; textItem.Culture = itemPropertySetting.Culture; textItem.DefaultValue = itemPropertySetting.DefaultValue; textItem.IsNew = false; textItem.SetDrawProperty(); return textItem; } else { return null; } } } else { textItem.Init(this, true); textItem.Left = newItemLocation.X; textItem.Top = newItemLocation.Y; textItem.IsNew = false; textItem.SetDrawProperty(); return textItem; } } /// /// 创建一个新图片Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewImageItem(bool isShowDialog) { ImageItem imageItem = new ImageItem(null); imageItem.IsNew = true; openFileDialog.FileName = string.Empty; if (openFileDialog.ShowDialog() == DialogResult.OK) { FileInfo fileInfo = new FileInfo(openFileDialog.FileName); // 图片尺寸超过200kbyte if (LayoutConsts.FILE_DIALOG_IMAGE_MAX_SIZE < fileInfo.Length) { DialogResult dr = MessageBox.Show( "图片太大,影响显示和打印速度,请准备200KByte以下的图片。", "LayoutBox", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); if (dr == DialogResult.Yes) { return null; } } Image image = null; float imageWidth = LayoutConsts.SHAPE_ITEM_SIZE_DEFAULT_WIDTH; float imageHeigh = LayoutConsts.SHAPE_ITEM_SIZE_DEFAULT_HEIGHT; if (fileInfo.Length > 0) { Stream imageStream = null; try { imageStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); image = Image.FromStream(imageStream); MemoryStream mstream = new MemoryStream(); image.Save(mstream, image.RawFormat); image = Image.FromStream(mstream); } finally { if (imageStream != null) { imageStream.Dispose(); } } imageWidth = LayoutCommon.PixelToMillimeter(image.Width, _zoom, image.HorizontalResolution); imageHeigh = LayoutCommon.PixelToMillimeter(image.Height, _zoom, image.VerticalResolution); } else { MessageBox.Show("不能设置大小为0的图片。", "LayoutBox", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return null; } PointF newItemLocation = GetNewItemLocation(imageWidth, imageHeigh); if (isShowDialog) { ImageItemSetting itemPropertySetting = new ImageItemSetting(); itemPropertySetting.ImageLocationX = newItemLocation.X; itemPropertySetting.ImageLocationY = newItemLocation.Y; itemPropertySetting.ImageWidth = imageWidth; itemPropertySetting.ImageHeight = imageHeigh; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { imageItem.Init(this, true); imageItem.Width = itemPropertySetting.ImageWidth; imageItem.Height = itemPropertySetting.ImageHeight; imageItem.Left = itemPropertySetting.ImageLocationX; imageItem.Top = itemPropertySetting.ImageLocationY; imageItem.SideRatioFixed = itemPropertySetting.SideRatioFixed; imageItem.Image = image; imageItem.FileName = openFileDialog.FileName; imageItem.IsNew = false; imageItem.SetDrawProperty(); return imageItem; } else { if (image != null) { image.Dispose(); } return null; } } else { if (imageWidth < LayoutConsts.ITEM_SIZE_MIN) { imageWidth = LayoutConsts.ITEM_SIZE_MIN; } else if (LayoutConsts.ITEM_SIZE_WIDTH_MAX < imageWidth) { imageWidth = LayoutConsts.ITEM_SIZE_WIDTH_MAX; } if (imageHeigh < LayoutConsts.ITEM_SIZE_MIN) { imageHeigh = LayoutConsts.ITEM_SIZE_MIN; } else if (LayoutConsts.ITEM_SIZE_HEIGHT_MAX < imageHeigh) { imageHeigh = LayoutConsts.ITEM_SIZE_HEIGHT_MAX; } imageItem.Init(this, true); imageItem.Left = newItemLocation.X; imageItem.Top = newItemLocation.Y; imageItem.Width = imageWidth; imageItem.Height = imageHeigh; imageItem.Image = image; imageItem.FileName = openFileDialog.FileName; imageItem.SideRatioFixed = true; imageItem.IsNew = false; imageItem.SetDrawProperty(); return imageItem; } } else { return null; } } /// /// 创建一个新矩形Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewRectangleItem(bool isShowDialog) { RectangleItem rectangleItem = new RectangleItem(null); rectangleItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(50, 50); if (isShowDialog) { using (GraphicsItemSetting itemPropertySetting = new GraphicsItemSetting()) { itemPropertySetting.ShapeLocationX = newItemLocation.X; itemPropertySetting.ShapeLocationY = newItemLocation.Y; itemPropertySetting.ShapeWidth = rectangleItem.Width; itemPropertySetting.ShapeHeight = rectangleItem.Height; itemPropertySetting.LineColor = rectangleItem.LineColor; itemPropertySetting.FillColor = rectangleItem.FillColor; itemPropertySetting.LineWidth = rectangleItem.LineWidth; itemPropertySetting.Transparent = rectangleItem.Transparent; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { rectangleItem.Init(this, true); rectangleItem.Left = itemPropertySetting.ShapeLocationX; rectangleItem.Top = itemPropertySetting.ShapeLocationY; rectangleItem.Width = itemPropertySetting.ShapeWidth; rectangleItem.Height = itemPropertySetting.ShapeHeight; rectangleItem.LineColor = itemPropertySetting.LineColor; rectangleItem.FillColor = itemPropertySetting.FillColor; rectangleItem.LineWidth = itemPropertySetting.LineWidth; rectangleItem.Transparent = itemPropertySetting.Transparent; rectangleItem.IsNew = false; rectangleItem.SetDrawProperty(); return rectangleItem; } else { return null; } } } else { rectangleItem.Init(this, true); rectangleItem.Left = newItemLocation.X; rectangleItem.Top = newItemLocation.Y; rectangleItem.IsNew = false; rectangleItem.SetDrawProperty(); return rectangleItem; } } /// /// 创建一个新椭圆Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewEllipseItem(bool isShowDialog) { EllipseItem ellipseItem = new EllipseItem(null); ellipseItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(50, 50); if (isShowDialog) { using (GraphicsItemSetting itemPropertySetting = new GraphicsItemSetting()) { itemPropertySetting.ShapeLocationX = newItemLocation.X; itemPropertySetting.ShapeLocationY = newItemLocation.Y; itemPropertySetting.ShapeWidth = ellipseItem.Width; itemPropertySetting.ShapeHeight = ellipseItem.Height; itemPropertySetting.LineColor = ellipseItem.LineColor; itemPropertySetting.FillColor = ellipseItem.FillColor; itemPropertySetting.LineWidth = ellipseItem.LineWidth; itemPropertySetting.Transparent = ellipseItem.Transparent; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { ellipseItem.Init(this, true); ellipseItem.Left = itemPropertySetting.ShapeLocationX; ellipseItem.Top = itemPropertySetting.ShapeLocationY; ellipseItem.Width = itemPropertySetting.ShapeWidth; ellipseItem.Height = itemPropertySetting.ShapeHeight; ellipseItem.LineColor = itemPropertySetting.LineColor; ellipseItem.FillColor = itemPropertySetting.FillColor; ellipseItem.LineWidth = itemPropertySetting.LineWidth; ellipseItem.Transparent = itemPropertySetting.Transparent; ellipseItem.IsNew = false; ellipseItem.SetDrawProperty(); return ellipseItem; } else { return null; } } } else { ellipseItem.Init(this, true); ellipseItem.Left = newItemLocation.X; ellipseItem.Top = newItemLocation.Y; ellipseItem.IsNew = false; ellipseItem.SetDrawProperty(); return ellipseItem; } } /// /// 创建一个新表格Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewGridItem(bool isShowDialog) { GridItem gridItem = new GridItem(null); gridItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(50, 50); if (isShowDialog) { using (GridItemSetting itemPropertySetting = new GridItemSetting()) { itemPropertySetting.ShapeLocationX = newItemLocation.X; itemPropertySetting.ShapeLocationY = newItemLocation.Y; itemPropertySetting.ShapeWidth = gridItem.Width; itemPropertySetting.ShapeHeight = gridItem.Height; itemPropertySetting.LineColor = gridItem.LineColor; itemPropertySetting.FillColor = gridItem.FillColor; itemPropertySetting.LineWidth = gridItem.LineWidth; itemPropertySetting.Transparent = gridItem.Transparent; itemPropertySetting.TitleVisible = gridItem.TitleVisible; itemPropertySetting.AlwaysTitleVisible = gridItem.AlwaysTitleVisible; itemPropertySetting.RowsHeight = gridItem.RowsHeight; itemPropertySetting.HeadRowsHeight = gridItem.HeadRowsHeight; itemPropertySetting.RowsCount = gridItem.DisplayRowCount; itemPropertySetting.Columns = gridItem.Columns.CopyTo(); DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { gridItem.Init(this, true); gridItem.Left = itemPropertySetting.ShapeLocationX; gridItem.Top = itemPropertySetting.ShapeLocationY; gridItem.Width = itemPropertySetting.ShapeWidth; gridItem.Height = itemPropertySetting.ShapeHeight; gridItem.LineColor = itemPropertySetting.LineColor; gridItem.FillColor = itemPropertySetting.FillColor; gridItem.LineWidth = itemPropertySetting.LineWidth; gridItem.Transparent = itemPropertySetting.Transparent; gridItem.TitleVisible = itemPropertySetting.TitleVisible; gridItem.AlwaysTitleVisible = itemPropertySetting.AlwaysTitleVisible; gridItem.DisplayRowCount = itemPropertySetting.RowsCount; gridItem.RowsHeight = itemPropertySetting.RowsHeight; gridItem.HeadRowsHeight = itemPropertySetting.HeadRowsHeight; if (itemPropertySetting.ColumnsChanged) { itemPropertySetting.Columns.GridItem = gridItem; gridItem.Columns = itemPropertySetting.Columns; } gridItem.IsNew = false; gridItem.SetDrawProperty(); return gridItem; } else { return null; } } } else { gridItem.Init(this, true); gridItem.Left = newItemLocation.X; gridItem.Top = newItemLocation.Y; gridItem.IsNew = false; gridItem.SetDrawProperty(); return gridItem; } } /// /// 创建一个Grid页码Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewPageNumItem(bool isShowDialog) { PageNumItem pageNumItem = new PageNumItem(null); pageNumItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(50, 50); if (isShowDialog) { using (PageNumItemSetting itemPropertySetting = new PageNumItemSetting()) { itemPropertySetting.TextLocationX = newItemLocation.X; itemPropertySetting.TextLocationY = newItemLocation.Y; itemPropertySetting.TextWidth = pageNumItem.Width; itemPropertySetting.TextHeight = pageNumItem.Height; itemPropertySetting.TextAlign = pageNumItem.TextAlign; itemPropertySetting.TextAlignVertical = pageNumItem.TextAlignVertical; itemPropertySetting.TextColor = pageNumItem.TextColor; itemPropertySetting.TextFormat = pageNumItem.Format; itemPropertySetting.TextFont = pageNumItem.Font; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { pageNumItem.Init(this, true); pageNumItem.Left = itemPropertySetting.TextLocationX; pageNumItem.Top = itemPropertySetting.TextLocationY; pageNumItem.Width = itemPropertySetting.TextWidth; pageNumItem.Height = itemPropertySetting.TextHeight; pageNumItem.Font = itemPropertySetting.TextFont; pageNumItem.TextAlign = itemPropertySetting.TextAlign; pageNumItem.TextAlignVertical = itemPropertySetting.TextAlignVertical; pageNumItem.TextColor = itemPropertySetting.TextColor; pageNumItem.Format = itemPropertySetting.TextFormat; pageNumItem.IsNew = false; pageNumItem.SetDrawProperty(); return pageNumItem; } else { return null; } } } else { pageNumItem.Init(this, true); pageNumItem.Left = newItemLocation.X; pageNumItem.Top = newItemLocation.Y; pageNumItem.IsNew = false; pageNumItem.SetDrawProperty(); return pageNumItem; } } /// /// 创建一个合计文本Item /// /// 是否显示属性设置对话框 /// 创建的新Item对象 private LayoutItem NewTotalTextItem(bool isShowDialog) { TotalTextItem textItem = new TotalTextItem(null); textItem.IsNew = true; PointF newItemLocation = GetNewItemLocation(LayoutCommon.DefaultTextItemSizeWidth, LayoutCommon.DefaultTextItemSizeHeight); if (isShowDialog) { using (TotalTextItemSetting itemPropertySetting = new TotalTextItemSetting()) { itemPropertySetting.IsNew = true; itemPropertySetting.IsDataBinding = false; itemPropertySetting.TextFont = textItem.Font; itemPropertySetting.TextLocationX = newItemLocation.X; itemPropertySetting.TextLocationY = newItemLocation.Y; itemPropertySetting.ItemStyle = ItemStyle.Other; itemPropertySetting.ItemName = LayoutBox.ITEMNAME_FIX + _newItemID; itemPropertySetting.NotTotalFont = textItem.NotTotalFont; itemPropertySetting.NotTotalColor = textItem.NotTotalColor; itemPropertySetting.NotTotalValue = textItem.NotTotalValue; itemPropertySetting.NotTotalAlign = textItem.NotTotalAlign; itemPropertySetting.NotTotalAlignVertical = textItem.NotTotalAlignVertical; DialogResult result = itemPropertySetting.ShowDialog(); if (result == DialogResult.OK) { textItem.Init(this, true); textItem.IsDataBinding = false; textItem.Left = itemPropertySetting.TextLocationX; textItem.Top = itemPropertySetting.TextLocationY; textItem.Width = itemPropertySetting.TextWidth; textItem.Height = itemPropertySetting.TextHeight; textItem.LineSpace = itemPropertySetting.LineSpace; textItem.CharacterSpace = itemPropertySetting.CharacterSpace; textItem.CharacterCount = itemPropertySetting.CharacterCount; textItem.Font = itemPropertySetting.TextFont; textItem.Wrap = itemPropertySetting.Wrap; textItem.TextColor = itemPropertySetting.TextColor; textItem.TextAlign = itemPropertySetting.TextAlign; textItem.TextAlignVertical = itemPropertySetting.TextAlignVertical; textItem.DisplayValue = itemPropertySetting.TextPreview; textItem.ItemStyle = itemPropertySetting.ItemStyle; textItem.TextItemName = itemPropertySetting.ItemName; textItem.Format = itemPropertySetting.TextFormat; textItem.Culture = itemPropertySetting.Culture; textItem.DefaultValue = itemPropertySetting.DefaultValue; textItem.NotTotalFont = itemPropertySetting.NotTotalFont; textItem.NotTotalColor = itemPropertySetting.NotTotalColor; textItem.NotTotalValue = itemPropertySetting.NotTotalValue; textItem.NotTotalAlign = itemPropertySetting.NotTotalAlign; textItem.NotTotalAlignVertical = itemPropertySetting.NotTotalAlignVertical; textItem.IsNew = false; textItem.SetDrawProperty(); return textItem; } else { return null; } } } else { textItem.Init(this, true); textItem.Left = newItemLocation.X; textItem.Top = newItemLocation.Y; textItem.IsNew = false; textItem.SetDrawProperty(); return textItem; } } /// /// 清除LayoutBox的设置 /// private void ClearLayoutBox() { // TODO if (this._clipboardFormat != null) { this.ClearClipboard(); //if (Clipboard.ContainsData(_clipboardFormat.Name)) //{ // CopyToClipboard(_clipboardFormat.Name, null); //} //_clipboardFormat = // DataFormats.GetFormat(typeof(LayoutItem).FullName // + "{" // + Guid.NewGuid().ToString().ToUpper() // + "}"); } _lastItemRF = RectangleF.Empty; _mouseRect = Rectangle.Empty; SetDitry(false); _selectedItems.Clear(); foreach (LayoutItem item in _items) { if (item.Frame != null) { item.Frame.Dispose(); item.Frame = null; } item.Selected = false; item.Dispose(); } _items.Clear(); _updateCount = 0; _newItemID = 1; _paperHeight = 297.0f; _paperWidth = 210.0f; _backgroundImageName = string.Empty; paperArea.BackgroundImage = null; _isPrintAreaVisible = true; _isPrintBackground = false; if (_zoomType != ZoomType.Whole) { ChangePaperSize(); } else { InitializeZoom(); } } /// /// 初始化LayoutBox /// private void InitializeLayoutBox() { openFileDialog.Filter = LayoutConsts.FILE_DIALOG_IMAGE_FILTER; openFileDialog.FilterIndex = 6; string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); if (Directory.Exists(directory)) { openFileDialog.InitialDirectory = directory; } else { openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } _comparisonItems = new Comparison(SortItemsWithChildIndex); //// TODO //if (this._layoutMode == InvoiceLayout.LayoutMode.Edit) //{ // _clipboardFormat = // DataFormats.GetFormat(typeof(LayoutItem).FullName // + "{" // + Guid.NewGuid().ToString().ToUpper() // + "}"); //} tsmiPaste.Enabled = true; _lastItemRF = RectangleF.Empty; _mouseRect = Rectangle.Empty; _updateCount = 0; _newItemID = 1; _dataMember = string.Empty; _printDataMember = string.Empty; //_layoutMode = LayoutMode.Display; _paperHeight = 297.0f; _paperWidth = 210.0f; _zoom = 100; _backgroundImageName = string.Empty; _isDirty = false; _isPrintAreaVisible = true; _isPrintBackground = false; _selectedItems = new List(); _items = new List(); _zoomType = ZoomType.Specify; ChangePaperSize(); InitItemZoom(); } /// /// 获取新建Item的位置 /// /// 新建Item的位置 private PointF GetNewItemLocation(float itemWidth, float itemHeight) { PointF newItemLocation = new PointF(LayoutConsts.ITEM_LOCATION_DEF, LayoutConsts.ITEM_LOCATION_DEF); if (paperArea.Left < 0) { newItemLocation.X += LayoutCommon.PixelToMillimeter(Math.Abs(paperArea.Left), _zoom); } if (paperArea.Top < 0) { newItemLocation.Y += LayoutCommon.PixelToMillimeter(Math.Abs(paperArea.Top), _zoom); } return newItemLocation; } /// /// 复制到剪贴板中 /// /// 格式 /// 选定的Item private void CopyToClipboard(object items) { this.GetCipboardFormat(); if (this._clipboardFormat != null) { IDataObject dataObj = new DataObject(); dataObj.SetData(this._clipboardFormat.Name, false, items); Clipboard.SetDataObject(dataObj, false); } } /// /// 获取剪贴板中的数据 /// /// 格式 /// Item private object GetFromClipboard() { this.GetCipboardFormat(); if (this._clipboardFormat != null) { if (Clipboard.ContainsData(this._clipboardFormat.Name)) { return Clipboard.GetData(this._clipboardFormat.Name); } } return null; } private void ClearClipboard() { if (this._clipboardFormat != null) { if (Clipboard.ContainsData(_clipboardFormat.Name)) { IDataObject dataObj = new DataObject(); dataObj.SetData(this._clipboardFormat.Name, false, null); Clipboard.SetDataObject(dataObj, false); } } this._clipboardFormat = null; } private DataFormats.Format GetCipboardFormat() { if (_clipboardFormat != null) { return _clipboardFormat; } // TODO if (this._layoutMode == InvoiceLayout.LayoutMode.Edit) { _clipboardFormat = DataFormats.GetFormat(typeof(LayoutItem).FullName + "{" + Guid.NewGuid().ToString().ToUpper() + "}"); } return _clipboardFormat; } #endregion 保存、读取相关 #region 缩放比例和位置 /// /// 设置纸张的高和宽 /// /// 纸张的宽 /// 纸张的高 public void SetPaperAreaSize(float paperWidth, float paperHeight) { if (paperWidth < LayoutConsts.PAPER_SIZE_MIN || LayoutConsts.PAPER_SIZE_MAX < paperWidth) { return; } if (paperHeight < LayoutConsts.PAPER_SIZE_MIN || LayoutConsts.PAPER_SIZE_MAX < paperHeight) { return; } if (_paperHeight != paperHeight || _paperWidth != paperWidth) { //foreach (LayoutItem item in _items) //{ // if (paperHeight < item.Top + item.Height // || paperWidth < item.Left + item.Width) // { // MessageBox.Show("在纸张范围外有Item,请设置纸张大小包含所有Item", // "LayoutBox", // MessageBoxButtons.OK, // MessageBoxIcon.Error, // MessageBoxDefaultButton.Button1); // return; // } //} _paperHeight = paperHeight; _paperWidth = paperWidth; if (_zoomType != ZoomType.Whole) { ChangePaperSize(); } else { InitializeZoom(); } if (PaperSizeChanged != null) { PaperSizeChanged(this, EventArgs.Empty); } _isDirty = true; } } /// /// 设置所有Item的缩放比例 /// private void ZoomAllItems() { InitItemZoom(); if (0 < _items.Count) { foreach (LayoutItem item in _items) { item.ResetShapeLocationAndSize(false); item.SetDrawProperty(); } } } /// /// 整页显示 /// private void InitializeZoom() { int paperHeight = LayoutCommon.MillimeterToPixel(_paperHeight); int paperWidth = LayoutCommon.MillimeterToPixel(_paperWidth); int marginHeight = Height - LayoutConsts.LAYOUT_MARGIN - LayoutConsts.LAYOUT_MARGIN; int marginWidth = Width - LayoutConsts.LAYOUT_MARGIN - LayoutConsts.LAYOUT_MARGIN; double zoomHeight = 100.0 * marginHeight / paperHeight; double zoomWidth = 100.0 * marginWidth / paperWidth; int zoom = System.Convert.ToInt32(Math.Truncate(Math.Min(zoomHeight, zoomWidth))); if (zoom < 0) { _zoom = 0; } else { _zoom = zoom; } ChangePaperSize(); ZoomAllItems(); } /// /// 纸张的显示比率 /// private void ChangePaperSize() { int width = LayoutCommon.MillimeterToPixel(_paperWidth, _zoom); int height = LayoutCommon.MillimeterToPixel(_paperHeight, _zoom); paperArea.Size = new Size(width, height); AdjustPaperArea(); } /// /// 缩放比例变更 /// private void InitItemZoom() { _maxItemLeft = LayoutCommon.MillimeterToPixel(LayoutConsts.ITEM_LOCATION_MAX, _zoom); _maxItemTop = _maxItemLeft; _maxItemWidth = LayoutCommon.MillimeterToPixel(LayoutConsts.ITEM_SIZE_WIDTH_MAX, _zoom); _maxItemHeight = LayoutCommon.MillimeterToPixel(LayoutConsts.ITEM_SIZE_HEIGHT_MAX, _zoom); _minItemWidth = LayoutCommon.MillimeterToPixel(LayoutConsts.ITEM_SIZE_MIN, _zoom); _minItemHeight = _minItemWidth; } /// /// 设置纸张范围和位置 /// private void AdjustPaperArea() { int top = AdjustPaperAreaTop(); int left = AdjustPaperAreaLeft(); paperArea.Location = new Point(left, top); lblRightBottomPoint.Location = new Point(paperArea.Right, paperArea.Bottom); } /// /// 设置纸张位置Y /// /// 位置Y private int AdjustPaperAreaTop() { int margin = paperBox.ClientSize.Height - paperArea.Height - LayoutConsts.LAYOUT_MARGIN - LayoutConsts.LAYOUT_MARGIN; if (0 < margin) { return lblLeftTopPoint.Top + LayoutConsts.LAYOUT_MARGIN + (margin) / 2; } else { return lblLeftTopPoint.Top + LayoutConsts.LAYOUT_MARGIN; } } /// /// 设置纸张位置X /// /// 位置X private int AdjustPaperAreaLeft() { int margin = paperBox.ClientSize.Width - paperArea.Width - LayoutConsts.LAYOUT_MARGIN - LayoutConsts.LAYOUT_MARGIN; if (0 < margin) { return lblLeftTopPoint.Left + LayoutConsts.LAYOUT_MARGIN + (margin) / 2; } else { return lblLeftTopPoint.Left + LayoutConsts.LAYOUT_MARGIN; } } #endregion 缩放比例和位置 #region Item操作相关 /// /// 设置Ditry /// /// private void SetDitry(bool vaule) { _isDirty = vaule; } /// /// 计算滚动到指定子控制的偏移 /// /// 滚动显示的子控制 /// 滚动到指定子控制的偏移 protected override Point ScrollToControl(Control activeControl) { // 选定Item时,滚动条不动 return DisplayRectangle.Location; } /// /// 代表一个函数来比较两个相同类型的对象 /// /// 第一个比较对象 /// 第二个比较对象 /// /// 小于0 x小于y。 /// 等于0 x等于y。 /// 大于0 x大于y。 /// private int SortItemsWithChildIndex(LayoutItem itemX, LayoutItem itemY) { try { int x = paperArea.ShapeContainer.Shapes.GetChildIndex(itemX.Shape); int y = paperArea.ShapeContainer.Shapes.GetChildIndex(itemY.Shape); return y - x; } catch { return 0; } } /// /// 调整拖动范围 /// /// 鼠标所在位置 private void ResizeToRectangle(Point p) { Rectangle rect = _mouseRect; _mouseRect.Width = p.X - _mouseRect.Left; _mouseRect.Height = p.Y - _mouseRect.Top; DrawReversibleFrame(_mouseRect); DrawReversibleFrame(rect); } /// /// 显示拖动范围 /// /// 范围 internal void DrawReversibleFrame(Rectangle rect) { ControlPaint.DrawReversibleFrame(paperArea.RectangleToScreen(rect), Color.Black, FrameStyle.Dashed); } /// /// 当前选择的对象已经改变 /// private void SetTSMIOnSelectionChanged() { if (0 < _selectedItems.Count) { tsmiCut.Enabled = true; tsmiCopy.Enabled = true; tsmiDelete.Enabled = true; tsmiOrder.Enabled = true; if (_selectedItems.Count == 1) { tsmiProperties.Enabled = true; tsmiArrange.Enabled = false; } else { tsmiProperties.Enabled = false; tsmiArrange.Enabled = true; } } else { tsmiCut.Enabled = false; tsmiCopy.Enabled = false; tsmiDelete.Enabled = false; tsmiProperties.Enabled = false; tsmiArrange.Enabled = false; tsmiOrder.Enabled = false; } } /// /// 调整Item范围 /// /// 鼠标所在位置 /// Item索引 private void ResizeToRectangle(Point p, int index) { Rectangle rect = _moveRectangles[index]; if (_isShiftDown) { // 长宽比例 double sizeRatio = 1.0 * _downRectangles[index].Height / _downRectangles[index].Width; int changedX = Math.Abs(p.X - _startX); int changedY = Math.Abs(p.Y - _startY); if (Math.Abs(p.X - _startX) < Math.Abs(p.Y - _startY)) { rect.X = _downRectangles[index].Left; rect.Y = _downRectangles[index].Top + p.Y - _startY; } else { rect.X = _downRectangles[index].Left + p.X - _startX; rect.Y = _downRectangles[index].Top; } rect.Width = _downRectangles[index].Width; rect.Height = _downRectangles[index].Height; } else if (_isCtrlDown) { rect.X = _downRectangles[index].Left + p.X - _startX; rect.Y = _downRectangles[index].Top + p.Y - _startY; rect.Width = _downRectangles[index].Width; rect.Height = _downRectangles[index].Height; } else { rect.X = _downRectangles[index].Left + p.X - _startX; rect.Y = _downRectangles[index].Top + p.Y - _startY; rect.Width = _downRectangles[index].Width; rect.Height = _downRectangles[index].Height; } { DrawReversibleFrame(_selectedItems[index].ItemLockType, _moveRectangles[index], rect); } _moveRectangles[index] = rect; } /// /// 绘制Item移动范围 /// /// Item锁定状态 /// 源范围 /// 新范围 private void DrawReversibleFrame(ItemLock itemLock, Rectangle? rectOriginal, Rectangle? rectCurrent) { if (itemLock == ItemLock.LockLocationAndSize) { return; } if (rectCurrent.HasValue) { Rectangle rect = rectCurrent.Value; rect.Width += 1; rect.Height += 1; DrawReversibleFrame(rect); } if (rectOriginal.HasValue && _isMouseMove) { Rectangle rect = rectOriginal.Value; rect.Width += 1; rect.Height += 1; DrawReversibleFrame(rect); } } /// /// 调整控件的大小 /// /// Item /// 范围 private void DragHandler(LayoutItem item, Rectangle rect) { if (item.ItemLockType == ItemLock.LockLocationAndSize) { return; } int top = 0; int left = 0; int width = 0; int height = 0; if (rect.Width < 0) { left = rect.Right; width -= rect.Width; } else { left = rect.Left; width = rect.Width; } if (rect.Height < 0) { top = rect.Bottom; height -= rect.Height; } else { top = rect.Top; height = rect.Height; } if (left < 0 || _maxItemLeft < left || top < 0 || _maxItemTop < top || width < _minItemWidth || _maxItemWidth < width || height < _minItemHeight || _maxItemHeight < height || paperArea.Width - 1 < left || paperArea.Height - 1 < top ) { //return; } item.MoveItem(left, top); item.ChangeItemSize(width, height); item.ResetItemFrame(); Dirty = true; } #endregion Item操作相关 #region 数据绑定相关 /// /// 设置数据源 /// private void SetDataSource() { if (_dataBinding == null) { _dataBinding = new LayoutBoxDataBinding(this); _dataBinding.SetDataConnection(_dataSource, _dataMember); } else { if (_dataBinding.ContainsDataMember(_dataSource)) { _dataMember = string.Empty; } _dataBinding.SetDataConnection(_dataSource, _dataMember); if (_dataSource == null) { _dataBinding = null; } } RefreshItemsBound(); } /// /// 设置数据成员 /// private void SetDataMember() { if (_dataBinding == null) { _dataBinding = new LayoutBoxDataBinding(this); } _dataBinding.SetDataConnection(_dataSource, _dataMember); RefreshItemsBound(); } /// /// 设置打印数据源 /// private void SetPrintDataSource() { if (_printDataBinding == null) { _printDataBinding = new LayoutBoxPrintDataBinding(this); _printDataBinding.SetDataConnection(_printDataSource, _printDataMember); } else { if (_printDataBinding.ContainsDataMember(_printDataSource)) { _printDataMember = string.Empty; } _printDataBinding.SetDataConnection(_printDataSource, _printDataMember); if (_printDataSource == null) { _printDataBinding = null; } } RefreshItemsPrintBound(); } /// /// 设置打印数据成员 /// private void SetPrintDataMember() { if (_printDataBinding == null) { _printDataBinding = new LayoutBoxPrintDataBinding(this); } _printDataBinding.SetDataConnection(_printDataSource, _printDataMember); RefreshItemsPrintBound(); } /// /// 启动数据更新 /// private void BeginUpdateInternal() { if (IsHandleCreated) { if (_updateCount == 0) { SendMessage(new HandleRef(this, Handle), 11, 0, 0); } _updateCount = (short)(_updateCount + 1); } } /// /// 结束数据更新 /// private void EndUpdateInternal() { if (_updateCount <= 0) { return; } _updateCount = (short)(_updateCount - 1); if (_updateCount == 0) { SendMessage(new HandleRef(this, Handle), 11, -1, 0); } } /// /// 刷新该项目的数据 /// private void RefreshItemsCurrentPositionValue() { bool visible = base.Visible; if (visible) { BeginUpdateInternal(); } try { if (_dataBinding == null) { return; } foreach (LayoutItem item in _items) { if ((item.ItemType == ItemType.Text || item.ItemType == ItemType.TotalText) && _dataBinding != null) { _dataBinding.BoundDataValueToTextItem(item as TextItem); } else { continue; } } } finally { if (visible) { EndUpdateInternal(); base.Invalidate(true); } } } /// /// 刷新该项目的数据绑定 /// internal void RefreshItemsBound() { bool visible = base.Visible; if (visible) { BeginUpdateInternal(); } try { if (_dataBinding == null) { return; } foreach (LayoutItem item in _items) { if ((item.ItemType == ItemType.Text || item.ItemType == ItemType.TotalText) && _dataBinding != null) { _dataBinding.BoundFieldToTextItem(item as TextItem); } else { continue; } } } finally { if (visible) { EndUpdateInternal(); base.Invalidate(true); } } } /// /// 刷新文本项目的数据绑定 /// /// 文本Item internal void RefreshTextItemBound(TextItem textItem) { bool visible = base.Visible; if (visible) { BeginUpdateInternal(); } try { if (_dataBinding != null) { _dataBinding.BoundFieldToTextItem(textItem); } } finally { if (visible) { EndUpdateInternal(); base.Invalidate(true); } } } /// /// 刷新该项目的打印数据 /// internal void RefreshItemsCurrentPositionPrintValue() { bool visible = base.Visible; if (visible) { BeginUpdateInternal(); } try { if (_printDataBinding == null) { return; } foreach (LayoutItem item in _items) { if ((item.ItemType == ItemType.Text || item.ItemType == ItemType.TotalText) && _printDataBinding != null) { _printDataBinding.BoundPrintDataValueToTextItem(item as TextItem); } else { continue; } } } finally { if (visible) { EndUpdateInternal(); base.Invalidate(true); } } } /// /// 刷新该项目的打印数据绑定 /// internal void RefreshItemsPrintBound() { bool visible = base.Visible; if (visible) { BeginUpdateInternal(); } try { if (_printDataBinding == null) { return; } foreach (LayoutItem item in _items) { if ((item.ItemType == ItemType.Text || item.ItemType == ItemType.TotalText) && _printDataBinding != null) { _printDataBinding.BoundPrintFieldToTextItem(item as TextItem); } else { continue; } } } finally { if (visible) { EndUpdateInternal(); base.Invalidate(true); } } } /// /// 刷新文本项目的打印数据绑定 /// /// 文本Item internal void RefreshTextItemPrintBound(TextItem textItem) { bool visible = base.Visible; if (visible) { BeginUpdateInternal(); } try { if (_printDataBinding != null) { _printDataBinding.BoundPrintFieldToTextItem(textItem); } } finally { if (visible) { EndUpdateInternal(); base.Invalidate(true); } } } #endregion 数据绑定相关 #region 打印相关 /// /// 检查打印设置 /// /// 可以打印true;其他为false public bool CheckPrintSetting() { // 获取打印机设置非常慢,暂不校验 return true; //string message = this.CheckPrintSettingIn(_printType); //if (!string.IsNullOrWhiteSpace(message)) //{ // MessageBox.Show(message, // "打印失败", // MessageBoxButtons.OK, // MessageBoxIcon.Error, // MessageBoxDefaultButton.Button1); // return false; //} //return true; } public string CheckPrintSettingIn(PrintType printType) { // 获取打印机设置非常慢,暂不校验 return null; /* if (System.Drawing.Printing.PrinterSettings.InstalledPrinters.Count < 1) { return "请安装打印机驱动程序。"; } if (PrinterSettings == null || PrinterSettings.DefaultPageSettings == null) { return "请设置打印机。"; } if (PaperSize == null) { return "请设置打印纸张大小。"; } if (!printDocument.PrinterSettings.IsValid) { return string.Format("打印机名称({0}/{1})不正确。" , printDocument.PrinterSettings.PrinterName , printDialog.PrinterSettings.PrinterName); } if (short.MaxValue < _numberOfCopies) { return string.Format("此打印机一次可以打印的最大份数是{0},不能打印{1}份。" , short.MaxValue , _numberOfCopies); } if (printType == PrintType.Print || printType == PrintType.PrintPreview) { if (PrinterSettings.MaximumCopies < _numberOfCopies) { return string.Format("此打印机一次可以打印的最大份数是{0},不能打印{1}份。" , PrinterSettings.MaximumCopies , _numberOfCopies); } } else if (printType == PrintType.AllocationPrint || printType == PrintType.AllocationPrintPreview) { float paperWidth = 0; float paperHeight = 0; float horizontal = 0; float vertical = 0; if (_landscape) { paperWidth = (float)Math.Round(LayoutCommon.Inch100ToMillimeter(PaperSize.Height), 0); paperHeight = (float)Math.Round(LayoutCommon.Inch100ToMillimeter(PaperSize.Width), 0); horizontal = paperWidth + _allocationHorizontalSpace - _marginLeft - _marginRight - (_allocationHorizontalSpace + _paperWidth) * _allocationNumX; vertical = paperHeight + _allocationVerticalSpace - _marginTop - _marginBottom - (_allocationVerticalSpace + _paperHeight) * _allocationNumY; } else { paperWidth = (float)Math.Round(LayoutCommon.Inch100ToMillimeter(PaperSize.Width), 0); paperHeight = (float)Math.Round(LayoutCommon.Inch100ToMillimeter(PaperSize.Height), 0); horizontal = paperWidth + _allocationHorizontalSpace - _marginLeft - _marginRight - (_allocationHorizontalSpace + _paperWidth) * _allocationNumX; vertical = paperHeight + _allocationVerticalSpace - _marginTop - _marginBottom - (_allocationVerticalSpace + _paperHeight) * _allocationNumY; } if (horizontal < 0 && vertical < 0) { return "设置值大于纸张尺寸。请检查纸张横纵个数,间距,和余白。"; } if (horizontal < 0) { return string.Format("分配的纸张宽度不能打印{0}列,请确认。" , _allocationNumX); } if (vertical < 0) { return string.Format("分配的纸张高度不能打印{0}行,请确认。" , _allocationNumY); } } return null; */ } /// /// 打印背景图片 /// /// 用于绘制的System.Drawing.Graphics private void PrintBackgroundImage(Graphics graphics) { if (BackgroundImage != null) { // 背景图片的高宽比例 float imgWHRate = (float)BackgroundImage.Width / (float)BackgroundImage.Height; // 打印纸张的高宽比例 float paperWHRate = PaperWidth / PaperHeight; // 背景图片打印范围 RectangleF newImgRectangleF = RectangleF.Empty; // 缩放背景图片,但保持图片高宽比例 if (imgWHRate > paperWHRate) { newImgRectangleF.Width = PaperWidth; newImgRectangleF.Height = PaperWidth / imgWHRate; newImgRectangleF.X = _allOffsetX; newImgRectangleF.Y = (PaperHeight - newImgRectangleF.Height) / 2 + _allOffsetY; } else { newImgRectangleF.Width = PaperHeight * imgWHRate; newImgRectangleF.Height = PaperHeight; newImgRectangleF.X = (PaperWidth - newImgRectangleF.Width) / 2 + _allOffsetX; newImgRectangleF.Y = _allOffsetY; } // 在指定的范围绘制背景图片 graphics.DrawImage(BackgroundImage, newImgRectangleF); } } /// /// 打印文本Item /// /// 用于绘制的System.Drawing.Graphics /// 文本Item private void DrawTextItem(Graphics graphics, TextItem textItem) { // 文本Item打印范围 RectangleF rectangleFM = new RectangleF( _allOffsetX + textItem.Left, _allOffsetY + textItem.Top, textItem.Width, textItem.Height); RectangleF rectangleF = rectangleFM; rectangleF.Inflate(0 - LayoutConsts.TEXT_MARGIN, 0 - LayoutConsts.TEXT_MARGIN); rectangleFM.Height -= LayoutConsts.TEXT_MARGIN; /* Edit For Draw Pic // 在指定的范围绘制文本Item LayoutUtility.DrawText(graphics, rectangleFM, rectangleF, textItem.PrintText, textItem.Font, textItem.TextColor, textItem.LineSpace, textItem.CharacterSpace, textItem.CharacterCount, textItem.TextAlign, textItem.Wrap, textItem.Clip, false); */ textItem.DrawTextItem(textItem.PrintDataValue, textItem.PrintBoundField, graphics, rectangleFM, rectangleF, true); } /// /// 打印图片Item /// /// 用于绘制的System.Drawing.Graphics /// 图片Item private void DrawImageItem(Graphics graphics, ImageItem imageItem) { // 图片Item打印范围 RectangleF rectangleF = new RectangleF( _allOffsetX + imageItem.Left, _allOffsetY + imageItem.Top, imageItem.Width, imageItem.Height); // 在指定的范围绘制图片Item LayoutUtility.DrawImage(graphics, rectangleF, imageItem.Image); } /// /// 打印矩形Item /// /// 用于绘制的System.Drawing.Graphics /// 矩形Item private void DrawRectangleItem(Graphics graphics, RectangleItem rectangleItem) { // 矩形Item打印范围 RectangleF rectangleF = new RectangleF( _allOffsetX + rectangleItem.Left, _allOffsetY + rectangleItem.Top, rectangleItem.Width, rectangleItem.Height); float lineWidthDraw = rectangleItem.LineWidth; // 在指定的范围绘制矩形Item LayoutUtility.DrawRectangle(graphics, rectangleF, rectangleItem.LineColor, rectangleItem.FillColor, lineWidthDraw, rectangleItem.Transparent); } /// /// 打印椭圆Item /// /// 用于绘制的System.Drawing.Graphics /// 椭圆Item private void DrawEllipseItem(Graphics graphics, EllipseItem ellipseItem) { // 椭圆Item打印范围 RectangleF rectangleF = new RectangleF( _allOffsetX + ellipseItem.Left, _allOffsetY + ellipseItem.Top, ellipseItem.Width, ellipseItem.Height); float lineWidthDraw = ellipseItem.LineWidth; // 在指定的范围绘制椭圆Item LayoutUtility.DrawEllipse(graphics, rectangleF, ellipseItem.LineColor, ellipseItem.FillColor, lineWidthDraw, ellipseItem.Transparent); } /// /// 打印表格Item /// /// 用于绘制的System.Drawing.Graphics /// 表格Item private void DrawGridItem(Graphics graphics, GridItem gridItem) { // 表格Item打印范围 RectangleF rectangleF = new RectangleF( _allOffsetX + gridItem.Left, _allOffsetY + gridItem.Top, gridItem.Width, gridItem.Height); //// 在指定的范围绘制表格Item gridItem.DrawGridItem(graphics, rectangleF, 1, _printPageNum); } /// /// 打印页码Item /// /// 用于绘制的System.Drawing.Graphics /// 页码Item private void DrawPageNumItem(Graphics graphics, PageNumItem pageNumItem) { // 文本Item打印范围 RectangleF rectangleFM = new RectangleF( _allOffsetX + pageNumItem.Left, _allOffsetY + pageNumItem.Top, pageNumItem.Width, pageNumItem.Height); RectangleF rectangleF = rectangleFM; rectangleF.Inflate(0 - LayoutConsts.TEXT_MARGIN, 0 - LayoutConsts.TEXT_MARGIN); rectangleFM.Height -= LayoutConsts.TEXT_MARGIN; // 在指定的范围绘制文本Item LayoutUtility.DrawText(graphics, rectangleFM, rectangleF, pageNumItem.PrintText, pageNumItem.Font, pageNumItem.TextColor, 0, 0, 0, pageNumItem.TextAlign, pageNumItem.TextAlignVertical, false, false, false); } /// /// 打印合计Item /// /// 用于绘制的System.Drawing.Graphics /// 合计Item private void DrawTotalTextItem(Graphics graphics, TotalTextItem totalTextItem) { // 文本Item打印范围 RectangleF rectangleFM = new RectangleF( _allOffsetX + totalTextItem.Left, _allOffsetY + totalTextItem.Top, totalTextItem.Width, totalTextItem.Height); RectangleF rectangleF = rectangleFM; rectangleF.Inflate(0 - LayoutConsts.TEXT_MARGIN, 0 - LayoutConsts.TEXT_MARGIN); rectangleFM.Height -= LayoutConsts.TEXT_MARGIN; if (PrintPageNum != TotalPageNum) { LayoutUtility.DrawText(graphics, rectangleFM, rectangleF, totalTextItem.NotTotalValue, totalTextItem.NotTotalFont, totalTextItem.NotTotalColor, totalTextItem.LineSpace, totalTextItem.CharacterSpace, totalTextItem.CharacterCount, totalTextItem.NotTotalAlign, totalTextItem.NotTotalAlignVertical, totalTextItem.Wrap, totalTextItem.Clip, false); return; } // 在指定的范围绘制文本Item string text = totalTextItem.ResetTextValue(totalTextItem.PrintDataValue, totalTextItem.BoundField.IsDataBound) as string; LayoutUtility.DrawText(graphics, rectangleFM, rectangleF, text, totalTextItem.Font, totalTextItem.TextColor, totalTextItem.LineSpace, totalTextItem.CharacterSpace, totalTextItem.CharacterCount, totalTextItem.TextAlign, totalTextItem.NotTotalAlignVertical, totalTextItem.Wrap, totalTextItem.Clip, false); } #endregion 打印相关 #region 事件 /// /// 当一个项目被改变,移动,添加或删除引发此事件。 /// /// Item /// 变更类型 internal void SetItemChangedArgs(LayoutItem layoutItem, ItemChangeType itemChangeType) { if (ItemChanged != null && !layoutItem.IsNew) { ItemChangedEventArgs e = new ItemChangedEventArgs(); e.Item = layoutItem; e.ChangedType = itemChangeType; e.ItemID = layoutItem.ID; _isDirty = true; ItemChanged(this, e); } if (itemChangeType != ItemChangeType.Deleted) { layoutItem.Shape.Refresh(); } else { if (layoutItem.ItemType == ItemType.Grid) { this.OneGridItem = null; } } } /// /// 当一个项目被改变,移动,添加或删除引发此事件。 /// /// Item /// 变更类型 /// 属性 internal void SetItemChangedArgs(LayoutItem layoutItem, ItemChangeType itemChangeType, string property) { if (ItemChanged != null && !layoutItem.IsNew) { ItemChangedEventArgs e = new ItemChangedEventArgs(); e.Item = layoutItem; e.ChangedType = itemChangeType; e.ItemID = layoutItem.ID; e.Property = property; _isDirty = true; ItemChanged(this, e); } if (itemChangeType != ItemChangeType.Deleted) { layoutItem.Shape.Refresh(); } else { if (layoutItem.ItemType == ItemType.Grid) { this.OneGridItem = null; } } } /// /// 项目的选择状态改变时引发此事件。 /// /// Item /// 选择状态 internal void SetItemSelectionChangedArgs(LayoutItem layoutItem, bool isSelect) { SetTSMIOnSelectionChanged(); if (ItemSelectionChanged != null && !layoutItem.IsNew) { ItemSelectionChangedEventArgs e = new ItemSelectionChangedEventArgs(); e.Item = layoutItem; e.IsSelected = isSelect; e.ItemID = layoutItem.ID; ItemSelectionChanged(this, e); } } /// /// 打印或显示数据之前引发此事件。 /// /// Item /// 数据 /// 格式 /// e.Result格式化后结果 internal object SetItemValueFormattingArgs(LayoutItem layoutItem, object value, string format) { if (ItemValueFormatting != null && !layoutItem.IsNew) { ItemValueFormattingEventArgs e = new ItemValueFormattingEventArgs(); e.Item = layoutItem; e.ItemID = layoutItem.ID; e.Value = value; e.Format = format; ItemValueFormatting(this, e); return e.Result; } return null; } internal void SetUserChangedGridItemArgs(GridItem gItem, CollectionChangeEventArgs e) { if (this.UserChangedGridItem != null) { this.UserChangedGridItem(gItem, e); } } #endregion 事件 #endregion private函数 #region 事件处理 #region 缩放比例和位置 /// /// 调整纸张大小 /// /// 指定的对象 /// 提供的事件数据 private void PaperBox_SizeChanged(object sender, EventArgs e) { if (_zoomType == ZoomType.Whole) { InitializeZoom(); } else { AdjustPaperArea(); } } #endregion 缩放比例和位置 #region 右键菜单 /// /// 打开右键菜单 /// /// 指定的对象 /// 提供的事件数据 private void contextMenu_Opening(object sender, CancelEventArgs e) { //SetTSMIOnSelectionChanged(); tsmiPaste.Enabled = (_clipboardFormat != null && Clipboard.ContainsData(_clipboardFormat.Name)); } /// /// 打开对齐右键菜单 /// /// 指定的对象 /// 提供的事件数据 private void contextMenuArrange_Opening(object sender, CancelEventArgs e) { e.Cancel = !tsmiArrange.Enabled; } /// /// 打开排序右键菜单 /// /// 指定的对象 /// 提供的事件数据 private void contextMenuOrder_Opening(object sender, CancelEventArgs e) { e.Cancel = !tsmiOrder.Enabled; } /// /// 关闭右键菜单 /// /// 指定的对象 /// 提供的事件数据 private void contextMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e) { tsmiPaste.Enabled = true; } /// /// 删除 /// /// 指定的对象 /// 提供的事件数据 private void tsmiDelete_Click(object sender, EventArgs e) { DeleteItem(); } /// /// 属性 /// /// 指定的对象 /// 提供的事件数据 private void tsmiProperties_Click(object sender, EventArgs e) { ShowItemPropertyDialog(); } /// /// 选择全部Item /// /// 指定的对象 /// 提供的事件数据 private void tsmiAllSelect_Click(object sender, EventArgs e) { SelectItemsMultiple(_items.ToArray(), true); } /// /// 纸张大小 /// /// 指定的对象 /// 提供的事件数据 private void tsmiPaperSize_Click(object sender, EventArgs e) { ShowPaperPropertyDialog(); } /// /// 背景图片 /// /// 指定的对象 /// 提供的事件数据 private void tsmiBackgroundImage_Click(object sender, EventArgs e) { ShowBackgroundSettingDialog(); } /// /// 打开缩放比例右键菜单 /// /// 指定的对象 /// 提供的事件数据 private void contextMenuZoom_Opening(object sender, CancelEventArgs e) { tsmiZoom500.Checked = false; tsmiZoom200.Checked = false; tsmiZoom100.Checked = false; tsmiZoom75.Checked = false; tsmiZoom50.Checked = false; tsmiZoom33.Checked = false; tsmiZoom25.Checked = false; tsmiZoom10.Checked = false; tsmiZoomWhole.Checked = false; switch (_zoom) { case 500: tsmiZoom500.Checked = true; break; case 200: tsmiZoom200.Checked = true; break; case 100: tsmiZoom100.Checked = true; break; case 75: tsmiZoom75.Checked = true; break; case 50: tsmiZoom50.Checked = true; break; case 33: tsmiZoom33.Checked = true; break; case 25: tsmiZoom25.Checked = true; break; case 10: tsmiZoom10.Checked = true; break; default: tsmiZoomWhole.Checked = true; break; } } /// /// 缩放比例 /// /// 指定的对象 /// 提供的事件数据 private void tsmiZoom_Click(object sender, EventArgs e) { ToolStripMenuItem itemZoom = sender as ToolStripMenuItem; if (itemZoom == null) { return; } int zoom = System.Convert.ToInt32(itemZoom.Tag); if (zoom > 0) { Zoom = zoom; } else { ZoomType = ZoomType.Whole; } } /// /// 置于顶层 /// /// 指定的对象 /// 提供的事件数据 private void tsmiForemost_Click(object sender, EventArgs e) { ChangeItemsOrderForemost(); } /// /// 上移一层 /// /// 指定的对象 /// 提供的事件数据 private void tsmiFront_Click(object sender, EventArgs e) { ChangeItemsOrderFront(); } /// /// 下移一层 /// /// 指定的对象 /// 提供的事件数据 private void tsmiBack_Click(object sender, EventArgs e) { ChangeItemsOrderBack(); } /// /// 置于底层 /// /// 指定的对象 /// 提供的事件数据 private void tsmiAftermost_Click(object sender, EventArgs e) { ChangeItemsOrderAftermost(); } /// /// 顶端对齐 /// /// 指定的对象 /// 提供的事件数据 private void tsmiTop_Click(object sender, EventArgs e) { ArrangeItemsTop(); } /// /// 底端对齐 /// /// 指定的对象 /// 提供的事件数据 private void tsmiBottom_Click(object sender, EventArgs e) { ArrangeItemsBottom(); } /// /// 垂直居中对齐 /// /// 指定的对象 /// 提供的事件数据 private void tsmiVerticalCenter_Click(object sender, EventArgs e) { ArrangeItemsVerticalCenter(); } /// /// 右侧对齐 /// /// 指定的对象 /// 提供的事件数据 private void tsmiRight_Click(object sender, EventArgs e) { ArrangeItemsRight(); } /// /// 左侧对齐 /// /// 指定的对象 /// 提供的事件数据 private void tsmiLeft_Click(object sender, EventArgs e) { ArrangeItemsLeft(); } /// /// 水平居中对齐 /// /// 指定的对象 /// 提供的事件数据 private void tsmiHorizontalCenter_Click(object sender, EventArgs e) { ArrangeItemsHorizontalCenter(); } /// /// 剪切 /// /// 指定的对象 /// 提供的事件数据 private void tsmiCut_Click(object sender, EventArgs e) { CutItem(); } /// /// 复制 /// /// 指定的对象 /// 提供的事件数据 private void tsmiCopy_Click(object sender, EventArgs e) { CopyItem(); } /// /// 粘贴 /// /// 指定的对象 /// 提供的事件数据 private void tsmiPaste_Click(object sender, EventArgs e) { PasteItem(); } #endregion 右键菜单 #region Item操作相关 /// /// Item选择边框失去焦点时发生。 /// /// 指定的对象 /// 提供的事件数据 private void RectTracker_LostFocus(object sender, EventArgs e) { if (_moveRectangles != null && _isMouseMove) { //if (!_isRealFollow) { int count = _moveRectangles.Length; for (int i = 0; i < count; i++) { DrawReversibleFrame(_selectedItems[i].ItemLockType, _moveRectangles[i], null); } } _isMouseDown = false; _isMouseMove = false; _moveRectangles = null; } } /// /// Item选择边框 KeyDown事件 /// /// 指定的对象 /// 提供的事件数据 private void RectTracker_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && !_isShiftDown) { _isShiftDown = true; } else if (e.KeyCode == Keys.ControlKey && !_isCtrlDown) { _isCtrlDown = true; } else { return; } if (_isMouseMove) { int count = _moveRectangles.Length; for (int i = 0; i < count; i++) { ResizeToRectangle(new Point(_mouseMoveX, _mouseMoveY), i); } } } /// /// Item选择边框 KeyUp事件 /// /// 指定的对象 /// 提供的事件数据 private void RectTracker_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey) { _isShiftDown = false; } else if (e.KeyCode == Keys.ControlKey) { _isCtrlDown = false; } else { return; } if (_isMouseMove) { int count = _moveRectangles.Length; for (int i = 0; i < count; i++) { ResizeToRectangle(new Point(_mouseMoveX, _mouseMoveY), i); } } } /// /// Item选择边框 MouseDown事件 /// /// 指定的对象 /// 提供的事件数据 private void RectTracker_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (ItemShapeContainer.ClientRectangle.Contains(e.Location)) { _startX = e.X; _startY = e.Y; _mouseMoveX = e.X; _mouseMoveY = e.Y; int count = _selectedItems.Count; _downRectangles = new Rectangle[count]; _moveRectangles = new Rectangle[count]; for (int i = 0; i < count; i++) { _downRectangles[i] = _selectedItems[i].ShapeBounds; _moveRectangles[i] = _downRectangles[i]; } _isMouseDown = true; Cursor.Current = Cursors.SizeAll; } } } /// /// Item选择边框 MouseMove事件 /// /// 指定的对象 /// 提供的事件数据 private void RectTracker_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && _isMouseDown) { Cursor.Current = Cursors.SizeAll; int mx = e.X; int my = e.Y; if (_mouseMoveX != mx || _mouseMoveY != my) { int count = _moveRectangles.Length; for (int i = 0; i < count; i++) { ResizeToRectangle(new Point(mx, my), i); } _isMouseMove = true; _mouseMoveX = mx; _mouseMoveY = my; } } } /// /// Item选择边框 MouseUp事件 /// /// 指定的对象 /// 提供的事件数据 private void RectTracker_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && _isMouseDown) { if (_isMouseMove) { Capture = false; int count = _moveRectangles.Length; for (int i = 0; i < count; i++) { DrawReversibleFrame(_selectedItems[i].ItemLockType, _moveRectangles[i], null); DragHandler(_selectedItems[i], _moveRectangles[i]); } } _isMouseDown = false; _isMouseMove = false; _moveRectangles = null; } } /// /// 鼠标在纸张范围内移动 /// /// 指定的对象 /// 提供的事件数据 private void paperArea_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && _layoutMode == LayoutMode.Edit) { if (_isMouseDownInPaperArea) { _mouseRect.X = e.X; _mouseRect.Y = e.Y; _isMouseDownInPaperArea = false; _isMouseMoveInPaperArea = true; } else if (_isMouseMoveInPaperArea) { ResizeToRectangle(e.Location); } } } /// /// 鼠标在纸张范围内抬起 /// /// 指定的对象 /// 提供的事件数据 private void paperArea_MouseUp(object sender, MouseEventArgs e) { if (_layoutMode != LayoutMode.Edit || e.Button != MouseButtons.Left) { return; } if (_isMouseMoveInPaperArea) { Capture = false; DrawReversibleFrame(_mouseRect); bool isChanging = false; if (Items.Count > 0) { if (_mouseRect.Height > 0 && _mouseRect.Width > 0) { //_mouseRect.X = _mouseRect.X - paperArea.Left; //_mouseRect.Y = _mouseRect.Y - paperArea.Top; } else if (_mouseRect.Height <= 0 && _mouseRect.Width > 0) { //_mouseRect.X = _mouseRect.X - paperArea.Left; _mouseRect.Y = e.Y; _mouseRect.Height = Math.Abs(_mouseRect.Height); //_mouseRect.Width = Math.Abs(_mouseRect.Width); } else if (_mouseRect.Height > 0 && _mouseRect.Width <= 0) { _mouseRect.X = e.X; //_mouseRect.Y = _mouseRect.Y - paperArea.Top; _mouseRect.Width = Math.Abs(_mouseRect.Width); } else if (_mouseRect.Height <= 0 && _mouseRect.Width <= 0) { _mouseRect.X = e.X; _mouseRect.Y = e.Y; _mouseRect.Height = Math.Abs(_mouseRect.Height); _mouseRect.Width = Math.Abs(_mouseRect.Width); } ItemSelectionChanging = true; if (Control.ModifierKeys == Keys.Control) { foreach (LayoutItem item in _items) { if (item.BoundsContainsBy(_mouseRect)) { SelectItemMultiple(item, !item.Selected, ref isChanging); } } } else if (Control.ModifierKeys == Keys.Shift) { foreach (LayoutItem item in _items) { if (item.BoundsContainsBy(_mouseRect)) { SelectItemMultiple(item, true, ref isChanging); } } } else { foreach (LayoutItem item in _items) { //if (item.BoundsContainsBy(_mouseRect)) //{ // SelectItemMultiple(item, true, ref isChanging); //} //else //{ // SelectItemMultiple(item, false, ref isChanging); //} bool isSelet = false; if (item.ShapeBounds.Height <= 1 || item.ShapeBounds.Width <= 1) { isSelet = item.IntersectsWith(_mouseRect); } else { isSelet = item.BoundsContainsBy(_mouseRect); } SelectItemMultiple(item, isSelet, ref isChanging); } } } ItemSelectionChanging = false; if (isChanging) { if (UserSelectionChanged != null) { UserSelectionChanged(this, EventArgs.Empty); } } _isMouseMoveInPaperArea = false; _mouseRect = Rectangle.Empty; } } /// /// 鼠标在纸张范围内按下 /// /// 指定的对象 /// 提供的事件数据 private void paperArea_MouseDown(object sender, MouseEventArgs e) { if (_layoutMode != LayoutMode.Edit) { return; } if (e.Button == MouseButtons.Left) { _isMouseDownInPaperArea = true; _isMouseMoveInPaperArea = false; } } /// /// 鼠标在纸张范围内点击 /// /// 指定的对象 /// 提供的事件数据 private void paperArea_Click(object sender, EventArgs e) { if (_layoutMode != LayoutMode.Edit) { return; } // 选择状态全部解除 if (Control.ModifierKeys == Keys.Control || Control.ModifierKeys == Keys.Shift) { return; } ClearSelection(); paperArea.Focus(); } #endregion Item操作相关 #region 打印相关 //private PageSettings _defaultPageSettings = null; //private PaperSize _defaultPaperSize = null; //private RectangleF _defaultPrintableArea = RectangleF.Empty; /// /// 打印开始。 /// /// 指定的对象 /// 提供的事件数据 private void printDocument_BeginPrint(object sender, PrintEventArgs e) { //#if DEBUG // Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, // "printDocument_BeginPrint", // "begin", // DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), // Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); //#endif // 选定打印页码 modify by chenxy 2014-03-27 begin //if (PrinterSettings.PrintRange == PrintRange.SomePages) //{ // if (PrinterSettings.ToPage == 0 || TotalPageNum < PrinterSettings.FromPage) // { // e.Cancel = true; // return; // } //} // 选定打印页码 modify by chenxy 2014-03-27 end //if (_numberOfCopies < 1 || !CheckPrintSetting()) //{ // e.Cancel = true; // return; //} // 获取打印机配置非常慢, //_defaultPageSettings = PrinterSettings.DefaultPageSettings; //_defaultPaperSize = _defaultPageSettings.PaperSize; //_defaultPrintableArea = _defaultPageSettings.PrintableArea; // 页面左上点的坐标(1/100英寸) if (_printAction == PrintAction.PrintToPreview) { _printerOffsetX = 0; _printerOffsetY = 0; _allOffsetX = _printOffsetX; _allOffsetY = _printOffsetY; } else { //if (_landscape) //{ // _printerOffsetX = LayoutCommon.Inch100ToMillimeter(_defaultPaperSize.Height - _defaultPrintableArea.Bottom); // _printerOffsetY = LayoutCommon.Inch100ToMillimeter(_defaultPrintableArea.Left); //} //else //{ // _printerOffsetX = LayoutCommon.Inch100ToMillimeter(_defaultPrintableArea.Left); // _printerOffsetY = LayoutCommon.Inch100ToMillimeter(_defaultPrintableArea.Top); //} _allOffsetX = _printOffsetX - _printerOffsetX; _allOffsetY = _printOffsetY - _printerOffsetY; } _rectangleFGreed = RectangleF.Empty; _printPageNum = 1; if (_printType == PrintType.PrintTest) { //printDocument.PrinterSettings.Copies = 1; } else if (_printType == PrintType.Print || _printType == PrintType.PrintPreview) { if (_printDataBinding != null && _printDataBinding.BindingSource != null && 0 < _printDataBinding.BindingSource.Count) { _printDataBinding.BindingSource.MoveFirst(); _printDataTotal = _printDataBinding.BindingSource.Count * _numberOfCopies; } else { _printDataTotal = _numberOfCopies; } _printDataPosition = 0; _printDataCopies = 0; //if (_printType == PrintType.Print) if (_printAction == PrintAction.PrintToPrinter) { printDocument.PrinterSettings.Copies = (short)_numberOfCopies; } else { printDocument.PrinterSettings.Copies = 1; } } else if (_printType == PrintType.AllocationPrint || _printType == PrintType.AllocationPrintPreview) { if (_printDataBinding != null && _printDataBinding.BindingSource != null && 0 < _printDataBinding.BindingSource.Count) { _printDataBinding.BindingSource.MoveFirst(); _printDataTotal = _printDataBinding.BindingSource.Count * _numberOfCopies; } else { _printDataTotal = _numberOfCopies; } _printDataPosition = 0; _printDataCopies = 0; _allocationNum = _allocationNumY * _allocationNumX; _printDataTotal = _printDataTotal + _allocationSkipCount; printDocument.PrinterSettings.Copies = 1; } else { printDocument.PrinterSettings.Copies = 1; } //#if DEBUG // Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, // "printDocument_BeginPrint", // "end", // DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), // Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); //#endif } // 选定打印页码 modify by chenxy 2014-03-27 begin /// /// 打印每页 /// /// 指定的对象 /// 提供的事件数据 private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e) { //#if DEBUG // Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, // "PrintDocument_PrintPage", // "begin", // DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), // Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); //#endif /* if (PrinterSettings.PrintRange == PrintRange.SomePages) { bool isPrintCurrentPage = false; do { if (_printPageNum < PrinterSettings.FromPage) { isPrintCurrentPage = false; } else if (PrinterSettings.ToPage < _printPageNum) { isPrintCurrentPage = false; e.HasMorePages = false; e.Cancel = true; return; } else { isPrintCurrentPage = true; } if (isPrintCurrentPage) { e.Cancel = false; this.PrintPage(e); if (_printPageNum - 1 == PrinterSettings.ToPage) { e.HasMorePages = false; } } else { e.Cancel = true; if (_printType == PrintType.PrintTest) { e.HasMorePages = false; return; } else if (_printType == PrintType.Print || _printType == PrintType.PrintPreview) { // 表格Item是否有下一页 if (_printPageNum < TotalPageNum) { _printPageNum++; e.HasMorePages = true; //return; } else { if (_printAction == PrintAction.PrintToPrinter) { // 纸张数是否增加判断 if (_printDataBinding != null && _printDataBinding.BindingSource != null && 0 < _printDataBinding.BindingSource.Count) { if (_printDataBinding.BindingSource.Position + 1 < _printDataBinding.BindingSource.Count) { // 打印数据源下移一条记录 _printDataBinding.BindingSource.MoveNext(); _printPageNum = 1; e.HasMorePages = true; } else { e.HasMorePages = false; return; } } else { e.HasMorePages = false; return; } } else { // 纸张数是否增加判断 if (++_printDataPosition < _printDataTotal) { _printPageNum = 1; e.HasMorePages = true; // 同一数据一次印刷/分批印刷 if (true) { // 同一数据一次印刷 if (++_printDataCopies < _numberOfCopies) { return; } else { _printDataCopies = 0; } } } else { e.HasMorePages = false; return; } if (_printDataBinding != null && _printDataBinding.BindingSource != null && 0 < _printDataBinding.BindingSource.Count) { // 打印数据源下移一条记录 if (_printDataBinding.BindingSource.Position + 1 < _printDataBinding.BindingSource.Count) { _printDataBinding.BindingSource.MoveNext(); } else { _printDataBinding.BindingSource.MoveFirst(); } } } } } else if (_printType == PrintType.AllocationPrint || _printType == PrintType.AllocationPrintPreview) { int allocationIndex = -1; // 一张纸打印 for (int i = 0; i < _allocationNum; i++) { allocationIndex++; if (_printDataPosition < _allocationSkipCount) { // 跳过的打印位置 e.HasMorePages = true; continue; } // 表格Item是否有下一页 if (_printPageNum < TotalPageNum) { _printPageNum++; continue; } // 纸张数是否增加判断 if (++_printDataPosition < _printDataTotal) { _printPageNum = 1; e.HasMorePages = true; // 同一数据一次印刷/分批印刷 if (true) { // 同一数据一次印刷 if (++_printDataCopies < _numberOfCopies) { continue; } else { _printDataCopies = 0; } } } else { e.HasMorePages = false; break; } if (_printDataBinding != null && _printDataBinding.BindingSource != null && 1 < _printDataBinding.BindingSource.Count) { // 打印数据源下移一条记录 if (_printDataBinding.BindingSource.Position + 1 < _printDataBinding.BindingSource.Count) { _printDataBinding.BindingSource.MoveNext(); } else { _printDataBinding.BindingSource.MoveFirst(); } } } // 纸张数是否增加判断 if (e.HasMorePages && _printDataPosition < _printDataTotal) { e.HasMorePages = true; } else { e.HasMorePages = false; return; } } else { e.HasMorePages = false; return; } //e.HasMorePages = false; //e.Graphics.Clear(Color.White); } } while (!isPrintCurrentPage); } else */ { this.PrintPage(e); } //#if DEBUG // Dongke.IBOSS.PRD.Basics.Library.OutputLog.TraceLog(Dongke.IBOSS.PRD.Basics.Library.LogPriority.Debug, // "PrintDocument_PrintPage", // "end", // DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"), // Dongke.IBOSS.PRD.Basics.Library.LocalPath.LogExePath + @"printdebug\"); //#endif } private void PrintPage(PrintPageEventArgs e) { e.Graphics.PageUnit = GraphicsUnit.Millimeter; if (_isPrintAreaVisible && _rectangleFGreed.IsEmpty) { //if (_landscape) //{ // // 横向打印 // _rectangleFGreed = new RectangleF( // (_defaultPaperSize.Height - _defaultPrintableArea.Bottom) / 100 * e.Graphics.DpiY, // _defaultPrintableArea.Left / 100 * e.Graphics.DpiX, // _defaultPrintableArea.Height / 100 * e.Graphics.DpiY, // _defaultPrintableArea.Width / 100 * e.Graphics.DpiX); //} //else //{ // // 纵向打印 // _rectangleFGreed = new RectangleF( // _defaultPrintableArea.Left / 100 * e.Graphics.DpiX, // _defaultPrintableArea.Top / 100 * e.Graphics.DpiY, // _defaultPrintableArea.Width / 100 * e.Graphics.DpiX, // _defaultPrintableArea.Height / 100 * e.Graphics.DpiY); //} _rectangleFGreed = new RectangleF( 0, 0, LayoutCommon.MillimeterToInch100Single(this.PaperWidth) / 100 * e.Graphics.DpiX, LayoutCommon.MillimeterToInch100Single(this.PaperHeight) / 100 * e.Graphics.DpiY); } if (_printType == PrintType.PrintTest) { // 打印范围 RectangleF rectangleF = new RectangleF(_allOffsetX, _allOffsetY, _paperWidth, _paperHeight); e.Graphics.SetClip(rectangleF); // 背景打印 if (_isPrintBackground) { PrintBackgroundImage(e.Graphics); } // Item打印 foreach (LayoutItem layoutItem in _items) { switch (layoutItem.ItemType) { case ItemType.Text: DrawTextItem(e.Graphics, (TextItem)layoutItem); break; case ItemType.Image: DrawImageItem(e.Graphics, (ImageItem)layoutItem); break; case ItemType.Rectangle: DrawRectangleItem(e.Graphics, (RectangleItem)layoutItem); break; case ItemType.Ellipse: DrawEllipseItem(e.Graphics, (EllipseItem)layoutItem); break; //case ItemType.Line: // DrawLineItem(e.Graphics, (LineItem)layoutItem); // break; case ItemType.Grid: DrawGridItem(e.Graphics, (GridItem)layoutItem); break; case ItemType.PageNum: DrawPageNumItem(e.Graphics, (PageNumItem)layoutItem); break; case ItemType.TotalText: DrawTotalTextItem(e.Graphics, (TotalTextItem)layoutItem); break; default: //throw new NotImplementedException(); break; } } // 可以打印范围 if (_isPrintAreaVisible) { e.Graphics.PageUnit = GraphicsUnit.Pixel; e.Graphics.ResetClip(); e.Graphics.DrawRectangle(LayoutCommon.GreedDotPen, _rectangleFGreed.X, _rectangleFGreed.Y, _rectangleFGreed.Width, _rectangleFGreed.Height); } e.HasMorePages = false; } else if (_printType == PrintType.Print || _printType == PrintType.PrintPreview) { // 打印范围 RectangleF rectangleF = new RectangleF(_allOffsetX, _allOffsetY, _paperWidth, _paperHeight); e.Graphics.SetClip(rectangleF); // 背景打印 if (_isPrintBackground) { PrintBackgroundImage(e.Graphics); } // Item打印 foreach (LayoutItem layoutItem in _items) { switch (layoutItem.ItemType) { case ItemType.Text: DrawTextItem(e.Graphics, (TextItem)layoutItem); break; case ItemType.Image: DrawImageItem(e.Graphics, (ImageItem)layoutItem); break; case ItemType.Rectangle: DrawRectangleItem(e.Graphics, (RectangleItem)layoutItem); break; case ItemType.Ellipse: DrawEllipseItem(e.Graphics, (EllipseItem)layoutItem); break; //case ItemType.Line: // DrawLineItem(e.Graphics, (LineItem)layoutItem); // break; case ItemType.Grid: DrawGridItem(e.Graphics, (GridItem)layoutItem); break; case ItemType.PageNum: DrawPageNumItem(e.Graphics, (PageNumItem)layoutItem); break; case ItemType.TotalText: DrawTotalTextItem(e.Graphics, (TotalTextItem)layoutItem); break; default: //throw new NotImplementedException(); break; } } // 可以打印范围 if (_isPrintAreaVisible) { e.Graphics.PageUnit = GraphicsUnit.Pixel; e.Graphics.ResetClip(); e.Graphics.DrawRectangle(LayoutCommon.GreedDotPen, _rectangleFGreed.X, _rectangleFGreed.Y, _rectangleFGreed.Width, _rectangleFGreed.Height); } // 表格Item是否有下一页 if (_printPageNum < TotalPageNum) { _printPageNum++; e.HasMorePages = true; return; } if (_printAction == PrintAction.PrintToPrinter) { // 纸张数是否增加判断 if (_printDataBinding != null && _printDataBinding.BindingSource != null && 0 < _printDataBinding.BindingSource.Count) { if (_printDataBinding.BindingSource.Position + 1 < _printDataBinding.BindingSource.Count) { // 打印数据源下移一条记录 _printDataBinding.BindingSource.MoveNext(); _printPageNum = 1; e.HasMorePages = true; } else { e.HasMorePages = false; } } else { e.HasMorePages = false; } } else { // 纸张数是否增加判断 if (++_printDataPosition < _printDataTotal) { _printPageNum = 1; e.HasMorePages = true; // 同一数据一次印刷/分批印刷 if (true) { // 同一数据一次印刷 if (++_printDataCopies < _numberOfCopies) { return; } else { _printDataCopies = 0; } } } else { e.HasMorePages = false; return; } if (_printDataBinding != null && _printDataBinding.BindingSource != null && 0 < _printDataBinding.BindingSource.Count) { // 打印数据源下移一条记录 if (_printDataBinding.BindingSource.Position + 1 < _printDataBinding.BindingSource.Count) { _printDataBinding.BindingSource.MoveNext(); } else { _printDataBinding.BindingSource.MoveFirst(); } } } } else if (_printType == PrintType.AllocationPrint || _printType == PrintType.AllocationPrintPreview) { e.Graphics.SetClip(RectangleF.Empty); int allocationIndex = -1; // 一张纸打印 for (int i = 0; i < _allocationNum; i++) { allocationIndex++; if (_printDataPosition < _allocationSkipCount) { // 跳过的打印位置 e.HasMorePages = true; continue; } _allOffsetX = _marginLeft + (allocationIndex % _allocationNumX) * (_paperWidth + _allocationHorizontalSpace) - _printerOffsetX; _allOffsetY = _marginTop + (allocationIndex / _allocationNumX) * (_paperHeight + _allocationVerticalSpace) - _printerOffsetY; // 打印范围 RectangleF rectangleF = new RectangleF(_allOffsetX, _allOffsetY, _paperWidth, _paperHeight); e.Graphics.SetClip(rectangleF); // 背景打印 if (_isPrintBackground) { PrintBackgroundImage(e.Graphics); } // Item打印 foreach (LayoutItem layoutItem in _items) { switch (layoutItem.ItemType) { case ItemType.Text: DrawTextItem(e.Graphics, (TextItem)layoutItem); break; case ItemType.Image: DrawImageItem(e.Graphics, (ImageItem)layoutItem); break; case ItemType.Rectangle: DrawRectangleItem(e.Graphics, (RectangleItem)layoutItem); break; case ItemType.Ellipse: DrawEllipseItem(e.Graphics, (EllipseItem)layoutItem); break; //case ItemType.Line: // DrawLineItem(e.Graphics, (LineItem)layoutItem); // break; case ItemType.Grid: DrawGridItem(e.Graphics, (GridItem)layoutItem); break; case ItemType.PageNum: DrawPageNumItem(e.Graphics, (PageNumItem)layoutItem); break; case ItemType.TotalText: DrawTotalTextItem(e.Graphics, (TotalTextItem)layoutItem); break; default: break; } } // 表格Item是否有下一页 if (_printPageNum < TotalPageNum) { _printPageNum++; continue; } // 纸张数是否增加判断 if (++_printDataPosition < _printDataTotal) { _printPageNum = 1; e.HasMorePages = true; // 同一数据一次印刷/分批印刷 if (true) { // 同一数据一次印刷 if (++_printDataCopies < _numberOfCopies) { continue; } else { _printDataCopies = 0; } } } else { e.HasMorePages = false; break; } if (_printDataBinding != null && _printDataBinding.BindingSource != null && 1 < _printDataBinding.BindingSource.Count) { // 打印数据源下移一条记录 if (_printDataBinding.BindingSource.Position + 1 < _printDataBinding.BindingSource.Count) { _printDataBinding.BindingSource.MoveNext(); } else { _printDataBinding.BindingSource.MoveFirst(); } } } // 可以打印范围 if (_isPrintAreaVisible) { e.Graphics.PageUnit = GraphicsUnit.Pixel; e.Graphics.ResetClip(); e.Graphics.DrawRectangle(LayoutCommon.GreedDotPen, _rectangleFGreed.X, _rectangleFGreed.Y, _rectangleFGreed.Width, _rectangleFGreed.Height); } // 纸张数是否增加判断 if (e.HasMorePages && _printDataPosition < _printDataTotal) { e.HasMorePages = true; } else { e.HasMorePages = false; } } else { e.HasMorePages = false; } } // 选定打印页码 modify by chenxy 2014-03-27 end #endregion 打印相关 #endregion 事件处理 #region 委托事件 /// /// 用户操作数据项目完成时发生 /// /// /// public delegate void UserChangedItemEventHandler(object sender, ItemChangedEventArgs e); /// /// 用户操作数据项目完成时发生 /// /// /// public delegate void UserChangedGridItemEventHandler(object sender, CollectionChangeEventArgs e); #endregion #region 事件 /// /// 改变纸张尺寸。 /// public event EventHandler PaperSizeChanged; /// /// 改变缩放比例 /// public event EventHandler ZoomChanged; /// /// 当一个项目被改变,移动,添加或删除引发此事件。 /// public event ItemChangedEventHandler ItemChanged; /// /// 项目的选择状态改变时引发此事件。 /// public event ItemSelectionChangedEventHandler ItemSelectionChanged; /// /// 打印或显示数据之前引发此事件。 /// public event ItemValueFormattingEventHandler ItemValueFormatting; /// /// 用户追加Item完成时触发事件 /// public event UserChangedItemEventHandler UserAddedItem; /// /// 用户删除Item完成时触发事件 /// public event UserChangedItemEventHandler UserDeletedItem; /// /// 用户修改GridItem列时触发事件 /// public event UserChangedGridItemEventHandler UserChangedGridItem; /// /// 改变项目的选中状态 /// public event EventHandler UserSelectionChanged; #endregion 事件 #region User32 /// /// /// [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, int lParam); #endregion User32 #region Grid页码相关 /// /// 当前页码 /// [Browsable(false)] public int CurrentPageNum { get { return _currentPageNum; } } /// /// 页数 /// [Browsable(false)] public int TotalPageNum { get { return _totalPageNum; } } /// /// 打印页码 /// internal int PrintPageNum { get { return _printPageNum; } } /// /// 设置总页数 /// internal void SetTotalPageNum() { LayoutItem[] grids = this.GetItems(ItemType.Grid); int total = 1; foreach (GridItem grid in grids) { total = Math.Max(total, grid.TotalPageNum); } if (total != _totalPageNum) { _totalPageNum = total; LayoutItem[] pageNums = this.GetItems(ItemType.PageNum); foreach (PageNumItem pageNum in pageNums) { pageNum.Refresh(); } } } /// /// 设定显示第几页 /// /// public void SetPageNum(int pageNum) { if (pageNum < 1) { pageNum = 1; } if (pageNum > _totalPageNum) { pageNum = _totalPageNum; } if (pageNum != _currentPageNum) { _currentPageNum = pageNum; LayoutItem[] grids = this.GetItems(ItemType.Grid); foreach (GridItem grid in grids) { grid.Refresh(); } LayoutItem[] pageNums = this.GetItems(ItemType.PageNum); foreach (PageNumItem pageNumItem in pageNums) { pageNumItem.Refresh(); } LayoutItem[] totalTextItems = this.GetItems(ItemType.TotalText); foreach (TotalTextItem totalTextItem in totalTextItems) { totalTextItem.Refresh(); } } } /// /// Grid使用的数据源 /// [Browsable(false)] public DataSet GridDataSource { get { return _gridDataSet; } set { if (value != _gridDataSet) { _gridDataSet = value; LayoutItem[] grids = this.GetItems(ItemType.Grid); if (grids != null && grids.Length > 0) { if (_gridDataSet == null || _gridDataSet.Tables.Count == 0) { foreach (GridItem grid in grids) { grid.GridSource = null; } } else { foreach (GridItem grid in grids) { if (_gridDataSet.Tables.Contains(grid.GridDataMember)) { grid.GridSource = _gridDataSet.Tables[grid.GridDataMember]; } else { grid.GridSource = null; } } } } } } } #endregion Grid页码相关 } }