ReportViewer 自定義報表應用

 

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Reporting.WinForms;
using System.ComponentModel;
using System.IO;

namespace CRReportDesigner
{
    public class ReportViewer : Microsoft.Reporting.WinForms.ReportViewer
    {
        private string _rcfile;
        private ReportConfig _rpc;
        private object _datasource;
        private MemoryStream m_rdl;
        private ReportManager reportManager;

        public ReportViewer()
            : base()
        {
            reportManager = new ReportManager(this);
        }

        public ReportManager ReportManager
        {
            get { return reportManager; }
        }

        /// <summary>
        /// 配置文件
        /// </summary>
        [DefaultValue("")]
        public string Filename
        {
            get { return _rcfile; }
            set
            {
                _rcfile = value;
                _rpc = new ReportConfig(_rcfile);
            }
        }

        /// <summary>
        /// 報表配置
        /// </summary>
        public ReportConfig ReportConfig
        {
            get { return _rpc; }
            set { this._rpc = value; }
        }

        /// <summary>
        /// 數據源
        /// </summary>
        public object DataSource
        {
            get { return _datasource; }
            set { _datasource = value; }
        }

        /// <summary>
        /// 顯示報表
        /// </summary>
        public void ShowReport()
        {
            if (m_rdl != null)
                m_rdl.Dispose();
            m_rdl = GenerateRdl();

            Reset();
            LocalReport.LoadReportDefinition(m_rdl);
            LocalReport.DataSources.Add(new ReportDataSource("FaibLists", _datasource));
            RefreshReport();
        }

        /// <summary>
        /// 生成Rdl流
        /// </summary>
        /// <returns></returns>
        private MemoryStream GenerateRdl()
        {
            MemoryStream ms = new MemoryStream();
            RdlGenerator gen = new RdlGenerator();
            gen.ReportConfig = _rpc;
            gen.WriteXml(ms);
            ms.Position = 0;
            return ms;
        }

      
    }
}

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace CRReportDesigner
{
    public class ReportManager
    {
        ReportViewer reportViewer;
        public ReportManager(ReportViewer rv)
        {
            reportViewer = rv;
        }

        /// <summary>
        /// 頁面設置
        /// </summary>
        public void PageSetting()
        {
            FrmPageSettings frm = new FrmPageSettings(this.m_ReportName);
            frm.ShowDialog();
        }
        private string m_ReportName = string.Empty;

        protected System.Windows.Forms.PrintPreviewDialog previewDialog = new System.Windows.Forms.PrintPreviewDialog();

        public string ReportName
        {
            get
            {
                return this.m_ReportName;
            }
            set
            {
                this.m_ReportName = value;
            }
        }

        private EMFStreamPrintDocument printDoc = null;
        /// <summary>
        /// 打印預覽
        /// </summary>
        public void Preview()
        {
            if (this.printDoc == null)
            {
                this.printDoc = new EMFStreamPrintDocument(this.reportViewer.LocalReport, this.m_ReportName);
                if (this.printDoc.ErrorMessage != string.Empty)
                {
                    System.Windows.Forms.MessageBox.Show("Report Viewer:\r\n    " + this.printDoc.ErrorMessage);
                    this.printDoc = null;
                    return;
                }
            }

            this.previewDialog.Document = this.printDoc;
            this.previewDialog.ShowDialog();
            this.printDoc = null;

        }
        /// <summary>
        /// 打印
        /// </summary>
        public void Print()
        {
            if (this.printDoc == null)
            {
                this.printDoc = new EMFStreamPrintDocument(this.reportViewer.LocalReport, this.m_ReportName);
                if (this.printDoc.ErrorMessage != string.Empty)
                {
                    System.Windows.Forms.MessageBox.Show("Report Viewer: \r\n    " + this.printDoc.ErrorMessage);
                    this.printDoc = null;
                    return;
                }
            }

            this.printDoc.Print();
            this.printDoc = null;
        }
        /// <summary>
        /// 刷新
        /// </summary>
        public void Refresh()
        {
            this.reportViewer.RefreshReport();
        }

        public void Stop()
        {
            this.reportViewer.CancelRendering(0);
        }

        public void Back()
        {
            if (this.reportViewer.LocalReport.IsDrillthroughReport)
                this.reportViewer.PerformBack();
        }
        /// <summary>
        /// 保存Excel
        /// </summary>
        public void SaveToExcel()
        {
            Microsoft.Reporting.WinForms.Warning[] Warnings;
            string[] strStreamIds;
            string strMimeType;
            string strEncoding;
            string strFileNameExtension;

            byte[] bytes = this.reportViewer.LocalReport.Render("Excel", null, out strMimeType, out strEncoding, out strFileNameExtension, out strStreamIds, out Warnings);

            string strFilePath = @"D:\" + this.GetTimeStamp() + ".xls";

            using (System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Create))
            {
                fs.Write(bytes, 0, bytes.Length);
            }

            if (System.Windows.Forms.MessageBox.Show("Report Viewer: \r\n    Succeed to export the excel file!" + strFilePath + "\r\n    Do you want to open the file" + strFilePath + "?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start(strFilePath);
            }
        }

        private string GetTimeStamp()
        {
            string strRet = string.Empty;
            System.DateTime dtNow = System.DateTime.Now;
            strRet += dtNow.Year.ToString() +
                        dtNow.Month.ToString("00") +
                        dtNow.Day.ToString("00") +
                        dtNow.Hour.ToString("00") +
                        dtNow.Minute.ToString("00") +
                        dtNow.Second.ToString("00") +
                        System.DateTime.Now.Millisecond.ToString("000");
            return strRet;

        }

        /// <summary>
        /// 放縮
        /// </summary>
        /// <param name="v"></param>
        public void Zoom(int v)
        {
            this.reportViewer.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.Percent;
            this.reportViewer.ZoomPercent = v;
        }

        public void ZoomWhole()
        {
            this.reportViewer.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.FullPage;
        }

        public void ZoomPageWidth()
        {
            this.reportViewer.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
        }

        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="startPage"></param>
        public void Find(string txt, int startPage)
        {
            if (string.IsNullOrEmpty(txt.Trim())) return;
            this.reportViewer.Find(txt.Trim(), startPage);
        }

        public void FindNext(string txt)
        {
            if (string.IsNullOrEmpty(txt.Trim())) return;
            this.reportViewer.FindNext();
        }

        public void FirstPage()
        {
            this.reportViewer.CurrentPage = 1;
        }

        public void LastPage()
        {
            this.reportViewer.CurrentPage = this.reportViewer.LocalReport.GetTotalPages();
        }

        public void PreviousPage()
        {
            if (this.reportViewer.CurrentPage != 1)
                this.reportViewer.CurrentPage--;
        }

        public void NextPage()
        {
            if (this.reportViewer.CurrentPage != this.reportViewer.LocalReport.GetTotalPages())
                this.reportViewer.CurrentPage++;
        }

        public void GoToPage(int i)
        {
            if (i <= this.reportViewer.LocalReport.GetTotalPages())
                this.reportViewer.CurrentPage = i;
        }
    }
}

 

  using System;
  using System.Collections.Generic;
  using System.Drawing;
  using System.Drawing.Printing;
  using System.Text;
  using System.Reflection;
  using System.Xml;

namespace CRReportDesigner
{
   /// <summary>
   /// 報表配置
   /// </summary>
   public class ReportConfig
   {
       private string _filename;
       private bool _autosize;
       private PageSettings _pset = new PageSettings();
       private Dictionary<string, TextItem> _header;
       private Dictionary<string, TextItem> _dataitem;
       private Dictionary<string, TextItem> _footer;
       private Dictionary<string, object> _cusmdata;
       private float _headheight ;
       private float _footheight ;
       private float _width, _height, _lm, _tm, _rm, _bm;////頁面大小
       private string _unit;

       public ReportConfig()
       {
           _headheight = 60f;
           _footheight = 60f;
           _header = new Dictionary<string, TextItem>();
           _dataitem = new Dictionary<string, TextItem>();
           _footer = new Dictionary<string, TextItem>();
           _cusmdata = new Dictionary<string, object>();
       }

       public ReportConfig(string frpFile)
       {
           if (string.IsNullOrEmpty(frpFile)) return;
           _filename = frpFile;
           XmlDocument xdoc = new XmlDocument();
           xdoc.Load(frpFile);
           XmlNode pnode = xdoc.SelectSingleNode("//configuration/pageset");
           ReportConfig.GetAttribute(pnode, "unit", ref _unit);
           if(string.IsNullOrEmpty(_unit)) //沒有單位
           {
               //頁面大小
               int w = 0, h = 0;
               ReportConfig.GetAttribute(pnode, "width", ref w);
               ReportConfig.GetAttribute(pnode, "height", ref h);
               _autosize = h == 0;
               _pset.PaperSize = new PaperSize(frpFile, w, h);
               //頁邊距
               int m_left = 0, m_top = 0, m_right = 0, m_bottom = 0;
               ReportConfig.GetAttribute(pnode, "margin-left", ref m_left);
               ReportConfig.GetAttribute(pnode, "margin-top", ref m_top);
               ReportConfig.GetAttribute(pnode, "margin-right", ref m_right);
               ReportConfig.GetAttribute(pnode, "margin-bottom", ref m_bottom);
               _pset.Margins = new Margins(m_left, m_right, m_top, m_bottom);
           }
           else
           {
               ReportConfig.GetAttribute(pnode, "width", ref _width);
               ReportConfig.GetAttribute(pnode, "height", ref _height);
               ReportConfig.GetAttribute(pnode, "margin-left", ref _lm);
               ReportConfig.GetAttribute(pnode, "margin-top", ref _tm);
               ReportConfig.GetAttribute(pnode, "margin-right", ref _rm);
               ReportConfig.GetAttribute(pnode, "margin-bottom", ref _bm);
           }
           //頭
           pnode = xdoc.SelectSingleNode("//configuration/header");
           ReportConfig.GetAttribute(pnode, "height", ref _headheight);
           //字段
           foreach (XmlNode node in xdoc.SelectNodes("//configuration/header/textitem"))
           {
               TextItem item = new TextItem(node);
               if (_header == null)
               {
                   _header = new Dictionary<string, TextItem>();
               }
               _header.Add(item.Key, item);
           }
           //尾
           pnode = xdoc.SelectSingleNode("//configuration/footer");
           ReportConfig.GetAttribute(pnode, "height", ref _footheight);
           //字段
           foreach (XmlNode node in xdoc.SelectNodes("//configuration/footer/textitem"))
           {
               TextItem item = new TextItem(node);
               if (_footer == null)
               {
                   _footer = new Dictionary<string, TextItem>();
               }
               _footer.Add(item.Key, item);
           }
           //數據字段
           foreach (XmlNode node in xdoc.SelectNodes("//configuration/dataitem/textitem"))
           {
               TextItem item = new TextItem(node);
               if(_dataitem == null)
               {
                   _dataitem = new Dictionary<string, TextItem>();
               }
               _dataitem.Add(item.Key, item);
           }
       }

       public Dictionary<string, object> CustomData
       {
           get {
               if (_cusmdata == null)
                   _cusmdata = new Dictionary<string, object>();
               return _cusmdata;
           }
       }

       public Dictionary<string, TextItem> Header
       {
           get { return _header; }
       }

       public Dictionary<string, TextItem> DataItem
       {
           get { return _dataitem; }
       }

       public Dictionary<string, TextItem> Footer
       {
           get { return _footer; }
       }

       public PageSettings PageSettings
       {
           get { return _pset; }
       }

       public float HeadHeight
       {
           get { return _headheight; }
           set { this._headheight = value; }
       }

       public float FootHeight
       {
           get { return _footheight; }
           set { this._footheight = value; }
       }

       public float Width
       {
           get { return _width; }
           set { this._width = value; }
       }

       public float Height
       {
           get { return _height; }
           set { this._height = value; }
       }

       public float LeftMargin
       {
           get { return _lm; }
           set { this._lm = value; }
       }

       public float TopMargin
       {
           get { return _tm; }
           set { this._tm = value; }
       }

       public float RightMargin
       {
           get { return _rm; }
           set { this._rm = value; }
       }

       public float BottomMargin
       {
           get { return _bm; }
           set { this._bm = value; }
       }

       public bool AutoSize
       {
           get { return _autosize; }
           set { _autosize = value; }
       }

       public string Unit
       {
           get { return _unit; }
           set { _unit = value; }
       }

       /// <summary>
       /// 從一個類獲取數據
       /// </summary>
       /// <param name="data"></param>
       public void DataFromDataItem(object data)
       {
           Type type = data.GetType();
           foreach (PropertyInfo pinfo in type.GetProperties(BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Public))
           {
               if (CustomData.ContainsKey(pinfo.Name))
                   continue;
               object value = type.InvokeMember(pinfo.Name, BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic, null, data, null);
               if(value != null)
               {
                   CustomData.Add(pinfo.Name, value);
               }
           }
       }

       internal static void GetAttribute(XmlNode node, string key, ref string value)
       {
           if (node.Attributes[key] != null)
           {
               value = node.Attributes[key].Value;
           }
       }

       internal static void GetAttribute(XmlNode node, string key, ref int value)
       {
           if (node.Attributes[key] != null)
           {
               value = int.Parse(node.Attributes[key].Value);
           }
       }

       internal static void GetAttribute(XmlNode node, string key, ref float value)
       {
           if (node.Attributes[key] != null)
           {
               value = float.Parse(node.Attributes[key].Value);
           }
       }
   }
}

 

  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.IO;
  using System.Xml.Serialization;

namespace CRReportDesigner
  {
     public class RdlGenerator
   {
       private ReportConfig _rpc;

       /// <summary>
       /// 報表配置
       /// </summary>
       public ReportConfig ReportConfig
       {
           get { return _rpc; }
           set { _rpc = value; }
       }

       /// <summary>
       /// 創建報表
       /// </summary>
       /// <returns></returns>
       private Rdl.Report CreateReport()
       {
           Rdl.Report report = new Rdl.Report();
           string w = "", h = "", lm = "", tm = "", rm = "", bm = "";
           //設置報表頁面
           if(!string.IsNullOrEmpty(_rpc.Unit))
           {
               w = _rpc.Width + _rpc.Unit;
               h = _rpc.Height + _rpc.Unit;
               lm = _rpc.LeftMargin + _rpc.Unit;
               tm = _rpc.TopMargin + _rpc.Unit;
               rm = _rpc.RightMargin + _rpc.Unit;
               bm = _rpc.BottomMargin + _rpc.Unit;
           }
           else
           {
               w = (_rpc.PageSettings.PaperSize.Width / 96.0) + "in";
               h = (_rpc.PageSettings.PaperSize.Height / 96.0) + "in";
               lm = (_rpc.LeftMargin / 96.0) + "in";
               tm = (_rpc.TopMargin / 96.0) + "in";
               rm = (_rpc.RightMargin / 96.0) + "in";
               bm = (_rpc.BottomMargin / 96.0) + "in";
           }
           report.Items = new object[]
               {
                   CreateDataSources(),
                   CreateHeader(),
                   CreateBody(),
                   CreateFooter(),
                   CreateDataSets(),
                   w,
                   h,
                   lm,
                   tm,
                   rm,
                   bm,
               };
           report.ItemsElementName = new Rdl.ItemsChoiceType37[]
               {
                   Rdl.ItemsChoiceType37.DataSources,
                   Rdl.ItemsChoiceType37.PageHeader,
                   Rdl.ItemsChoiceType37.Body,
                   Rdl.ItemsChoiceType37.PageFooter,
                   Rdl.ItemsChoiceType37.DataSets,
                   Rdl.ItemsChoiceType37.Width,
                   Rdl.ItemsChoiceType37.PageHeight,
                   Rdl.ItemsChoiceType37.LeftMargin,
                   Rdl.ItemsChoiceType37.TopMargin,
                   Rdl.ItemsChoiceType37.RightMargin,
                   Rdl.ItemsChoiceType37.BottomMargin,
               };
           return report;
       }

       #region 數據源
       /// <summary>
       /// 數據源
       /// </summary>
       /// <returns></returns>
       private Rdl.DataSourcesType CreateDataSources()
       {
           Rdl.DataSourcesType dataSources = new Rdl.DataSourcesType();
           dataSources.DataSource = new Rdl.DataSourceType[] { CreateDataSource() };
           return dataSources;
       }

       private Rdl.DataSourceType CreateDataSource()
       {
           Rdl.DataSourceType dataSource = new Rdl.DataSourceType();
           dataSource.Name = "FaibLists";
           dataSource.Items = new object[] { CreateConnectionProperties() };
           return dataSource;
       }

       private Rdl.ConnectionPropertiesType CreateConnectionProperties()
       {
           Rdl.ConnectionPropertiesType connectionProperties = new Rdl.ConnectionPropertiesType();
           connectionProperties.Items = new object[]
               {
                   "",
                   "SQL",
               };
           connectionProperties.ItemsElementName = new Rdl.ItemsChoiceType[]
               {
                   Rdl.ItemsChoiceType.ConnectString,
                   Rdl.ItemsChoiceType.DataProvider,
               };
           return connectionProperties;
       }
       #endregion

       #region 主體
       /// <summary>
       /// 報表主體
       /// </summary>
       /// <returns></returns>
       private Rdl.BodyType CreateBody()
       {
           Rdl.BodyType body = new Rdl.BodyType();
           body.Items = new object[]
               {
                   CreateReportItems(),
                   "1in",
               };
           body.ItemsElementName = new Rdl.ItemsChoiceType30[]
               {
                   Rdl.ItemsChoiceType30.ReportItems,
                   Rdl.ItemsChoiceType30.Height,
               };
           return body;
       }

       private Rdl.ReportItemsType CreateReportItems()
       {
           Rdl.ReportItemsType reportItems = new Rdl.ReportItemsType();
           TableRdlGenerator tableGen = new TableRdlGenerator();
           tableGen.Fields = _rpc.DataItem;
           reportItems.Items = new object[] { tableGen.CreateTable() };
           return reportItems;
       }
       #endregion

       #region 頁頭頁尾
       private Rdl.PageHeaderFooterType CreateHeader()
       {
           Rdl.PageHeaderFooterType header = new Rdl.PageHeaderFooterType();
           HeaderFooterRdlGenerator headerGen = new HeaderFooterRdlGenerator();
           headerGen.Fields = _rpc.Header;

           header.Items = new object[]
               {
                   (_rpc.HeadHeight / 96.0) + "in",
                   true,
                   true,
                   headerGen.CreateItems(),
               };
           header.ItemsElementName = new Rdl.ItemsChoiceType34[]
               {
                   Rdl.ItemsChoiceType34.Height,
                   Rdl.ItemsChoiceType34.PrintOnFirstPage,
                   Rdl.ItemsChoiceType34.PrintOnLastPage,
                   Rdl.ItemsChoiceType34.ReportItems
               };
           return header;
       }

       private Rdl.PageHeaderFooterType CreateFooter()
       {
           Rdl.PageHeaderFooterType footer = new Rdl.PageHeaderFooterType();
           HeaderFooterRdlGenerator footerGen = new HeaderFooterRdlGenerator();
           footerGen.Fields = _rpc.Footer;

           footer.Items = new object[]
               {
                   (_rpc.FootHeight / 96.0) + "in",
                   true,
                   true,
                   footerGen.CreateItems(),
               };
           footer.ItemsElementName = new Rdl.ItemsChoiceType34[]
               {
                   Rdl.ItemsChoiceType34.Height,
                   Rdl.ItemsChoiceType34.PrintOnFirstPage,
                   Rdl.ItemsChoiceType34.PrintOnLastPage,
                   Rdl.ItemsChoiceType34.ReportItems
               };
           return footer;
       }
       #endregion

       #region 數據集
       private Rdl.DataSetsType CreateDataSets()
       {
           Rdl.DataSetsType dataSets = new Rdl.DataSetsType();
           dataSets.DataSet = new Rdl.DataSetType[] { CreateDataSet() };
           return dataSets;
       }

       private Rdl.DataSetType CreateDataSet()
       {
           Rdl.DataSetType dataSet = new Rdl.DataSetType();
           dataSet.Name = "FaibLists";
           dataSet.Items = new object[] { CreateQuery(), CreateFields() };
           return dataSet;
       }

       private Rdl.QueryType CreateQuery()
       {
           Rdl.QueryType query = new Rdl.QueryType();
           query.Items = new object[]
               {
                   "FaibLists",
                   "",
               };
           query.ItemsElementName = new Rdl.ItemsChoiceType2[]
               {
                   Rdl.ItemsChoiceType2.DataSourceName,
                   Rdl.ItemsChoiceType2.CommandText,
               };
           return query;
       }

       private Rdl.FieldsType CreateFields()
       {
           Rdl.FieldsType fields = new Rdl.FieldsType();
           Dictionary<string, TextItem> m_fields = _rpc.DataItem;
           fields.Field = new Rdl.FieldType[m_fields.Count];
           int i = 0;
           foreach (string key in m_fields.Keys)
           {
               fields.Field[i++] = CreateField(m_fields[key]);
           }

           return fields;
       }

       private Rdl.FieldType CreateField(TextItem item)
       {
           Rdl.FieldType field = new Rdl.FieldType();
           field.Name = item.DataMember;
           field.Items = new object[] { item.DataMember };
           field.ItemsElementName = new Rdl.ItemsChoiceType1[] { Rdl.ItemsChoiceType1.DataField };
           return field;
       }
       #endregion

       public void WriteXml(Stream stream)
       {
           XmlSerializer serializer = new XmlSerializer(typeof(Rdl.Report));
           serializer.Serialize(stream, CreateReport());
       }
   }
}

 

  using System;
  using System.Drawing;
  using System.Drawing.Printing;
  using System.Text;
  using System.Xml;
 
  namespace CRReportDesigner
  {
     [Serializable]
   public class TextItem
   {
       private string _text;
       private string _key;
       private string _datamember;
       private Color backgroundColor=Color.White;
       private Color textColor=Color.Black;
       private Rectangle _rect = Rectangle.Empty;
       private StringFormat _align;
       private bool _count;
       private string _format;
       private Font _font = System.Windows.Forms.Control.DefaultFont;
       private Font _headerfont = System.Windows.Forms.Control.DefaultFont;

       public TextItem()
       {
           AlignStringFormat = "center";
       }

       public TextItem(string key, string text)
       {
           AlignStringFormat = "center";
           this._key = key;
           this._text = text;
       }

       public TextItem(string key, string text, string datamember, Rectangle rect)
       {
           AlignStringFormat = "center";
           this._key = key;
           this._text = text;
           this.DataMember = datamember;
           this._rect = rect;
       }
 
       public TextItem(XmlNode node)
       {
           _key = node.Attributes["key"].Value;
           if(!string.IsNullOrEmpty(node.InnerText))
           {
               _text = node.InnerText;
           }
           else
           {
               ReportConfig.GetAttribute(node, "text", ref _text);
           }
           ReportConfig.GetAttribute(node, "data", ref _datamember);
           ReportConfig.GetAttribute(node, "format", ref _format);
           string font_name = _font.Name;
           string font_bold = "";
           string font_italic = "";
           string font_underline = "";
           float font_size = Font.Size;
           FontStyle fsty = FontStyle.Regular;
           ReportConfig.GetAttribute(node, "font-name", ref font_name);
           ReportConfig.GetAttribute(node, "font-size", ref font_size);
           ReportConfig.GetAttribute(node, "font-bold", ref font_bold);
           ReportConfig.GetAttribute(node, "font-italic", ref font_italic);
           ReportConfig.GetAttribute(node, "font-underline", ref font_underline);
           if (font_bold.Equals("1"))
           {
               fsty |= FontStyle.Bold;
           }
           if (font_italic.Equals("1"))
           {
               fsty |= FontStyle.Italic;
           }
           if (font_underline.Equals("1"))
           {
               fsty |= FontStyle.Underline;
           }
           _font = new Font(font_name, font_size, fsty);

           font_name = _font.Name;
           font_bold = "";
           font_italic = "";
           font_underline = "";
           font_size = Font.Size;
           fsty = FontStyle.Regular;
           ReportConfig.GetAttribute(node, "header-font-name", ref font_name);
           ReportConfig.GetAttribute(node, "header-font-size", ref font_size);
           ReportConfig.GetAttribute(node, "header-font-bold", ref font_bold);
           ReportConfig.GetAttribute(node, "header-font-italic", ref font_italic);
           ReportConfig.GetAttribute(node, "header-font-underline", ref font_underline);
           if (font_bold.Equals("1"))
           {
               fsty |= FontStyle.Bold;
           }
           if (font_italic.Equals("1"))
           {
               fsty |= FontStyle.Italic;
           }
           if (font_underline.Equals("1"))
           {
               fsty |= FontStyle.Underline;
           }
           _headerfont = new Font(font_name, font_size, fsty);

           int left = 0, top = 0, width = 0, height = 0;
           ReportConfig.GetAttribute(node, "left", ref left);
           ReportConfig.GetAttribute(node, "top", ref top);
           ReportConfig.GetAttribute(node, "width", ref width);
           ReportConfig.GetAttribute(node, "height", ref height);
           _rect = new Rectangle(left, top, width, height);

           string align = "left";
           ReportConfig.GetAttribute(node, "align", ref align);
           string valign = "top";
           ReportConfig.GetAttribute(node, "valign", ref valign);
           _align = new StringFormat();
           if (align.Equals("right", StringComparison.OrdinalIgnoreCase))
           {
               _align.Alignment = StringAlignment.Far;
           }
           else if (align.Equals("center", StringComparison.OrdinalIgnoreCase))
           {
               _align.Alignment = StringAlignment.Center;
           }
           if (valign.Equals("bottom", StringComparison.OrdinalIgnoreCase))
           {
               _align.LineAlignment = StringAlignment.Far;
           }
           else if (valign.Equals("middle", StringComparison.OrdinalIgnoreCase))
           {
               _align.LineAlignment = StringAlignment.Center;
           }

           string count = "";
           ReportConfig.GetAttribute(node, "count", ref count);
           if(count.Equals("1"))
           {
               _count = true;
           }
       }

       public string Key
       {
           get { return _key; }
           set { this._key = value; }
       }

       public string Text
       {
           get { return _text; }
           set { _text = value; }
       }

       public string DataMember
       {
           get { return _datamember; }
           set { this._datamember = value; }
       }

       public string DataFormat
       {
           get { return _format; }
           set { this._format = value; }
       }

       public StringFormat Align
       {
           get { return _align; }
       }

       public string AlignStringFormat
       {
           get {
               if (_align.Alignment.Equals(StringAlignment.Far))
               {
                   return "right";
               }
               else if (_align.Alignment.Equals( StringAlignment.Center))
               {
                   return "center";
               }
               if (_align.LineAlignment.Equals(StringAlignment.Far))
               {
                   return "bottom";
               }
               else if (_align.LineAlignment.Equals(StringAlignment.Center))
               {
                   return "middle";
               }
               return "center";
           }
           set
           {
               _align = new StringFormat();
               if (value.Equals("right", StringComparison.OrdinalIgnoreCase))
               {
                   _align.Alignment = StringAlignment.Far;
               }
               else if (value.Equals("center", StringComparison.OrdinalIgnoreCase))
               {
                   _align.Alignment = StringAlignment.Center;
               }
               if (value.Equals("bottom", StringComparison.OrdinalIgnoreCase))
               {
                   _align.LineAlignment = StringAlignment.Far;
               }
               else if (value.Equals("middle", StringComparison.OrdinalIgnoreCase))
               {
                   _align.LineAlignment = StringAlignment.Center;
               }
           }
       }

       public Rectangle Rect
       {
           get { return _rect; }
           set { _rect = value; }
       }

       public bool Count
       {
           get { return _count; }
           set { this._count = value; }
       }

       public Color BackgroundColor
       {
           get { return backgroundColor; }
           set { backgroundColor = value; }
       }

       public Color TextColor
       {
           get { return textColor; }
           set { textColor = value; }
       }

       public Font Font
       {
           get { return _font; }
           set { this._font = value; }
       }

       public Font HeaderFont
       {
           get { return _headerfont; }
           set { this._headerfont = value; }
       }
   }
}

 

  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Drawing;
  using System.Xml.Serialization;

namespace CRReportDesigner
  {
     public class TableRdlGenerator
     {
         private float _tableTop = 0;
         private float _tableLeft = 30;

         public float TableTop
         {
             get { return _tableTop; }
             set { this._tableTop = value; }
         }

         public float TableLeft
         {
             get { return _tableLeft; }
             set { this._tableLeft = value; }
         }

       private Dictionary<string, TextItem> m_fields;

       public Dictionary<string, TextItem> Fields
       {
           get { return m_fields; }
           set { m_fields = value; }
       }

       public Rdl.TableType CreateTable()
       {
           //定義表格
           Rdl.TableType table = new Rdl.TableType();
           table.Name = "Table1";
           table.Items = new object[]
               {
                   CreateTableColumns(),
                   CreateHeader(),
                   CreateDetails(),
                   (_tableTop / 96.0) + "in",
                   (_tableLeft/ 96.0) + "in",
               };
           table.ItemsElementName = new Rdl.ItemsChoiceType21[]
               {
                   Rdl.ItemsChoiceType21.TableColumns,
                   Rdl.ItemsChoiceType21.Header,
                   Rdl.ItemsChoiceType21.Details,
                   Rdl.ItemsChoiceType21.Top,
                   Rdl.ItemsChoiceType21.Left
               };
           return table;
       }

       private Rdl.HeaderType CreateHeader()
       {
           Rdl.HeaderType header = new Rdl.HeaderType();
           header.Items = new object[]
               {
                   CreateHeaderTableRows(),
                   true,
               };
           header.ItemsElementName = new Rdl.ItemsChoiceType20[]
               {
                   Rdl.ItemsChoiceType20.TableRows,
                   Rdl.ItemsChoiceType20.RepeatOnNewPage,
               };
           return header;
       }

       private Rdl.TableRowsType CreateHeaderTableRows()
       {
           Rdl.TableRowsType headerTableRows = new Rdl.TableRowsType();
           headerTableRows.TableRow = new Rdl.TableRowType[] { CreateHeaderTableRow() };
           return headerTableRows;
       }

       private Rdl.TableRowType CreateHeaderTableRow()
       {
           Rdl.TableRowType headerTableRow = new Rdl.TableRowType();
           headerTableRow.Items = new object[] { CreateHeaderTableCells(), "0.25in" };
           return headerTableRow;
       }

       private Rdl.TableCellsType CreateHeaderTableCells()
       {
           Rdl.TableCellsType headerTableCells = new Rdl.TableCellsType();
           headerTableCells.TableCell = new Rdl.TableCellType[m_fields.Count];
           int i = 0;
           foreach (string key in m_fields.Keys)
           {
               headerTableCells.TableCell[i++] = CreateHeaderTableCell(m_fields[key]);
           }
           return headerTableCells;
       }

       private Rdl.TableCellType CreateHeaderTableCell(TextItem item)
       {
           Rdl.TableCellType headerTableCell = new Rdl.TableCellType();
           headerTableCell.Items = new object[] { CreateHeaderTableCellReportItems(item) };
           return headerTableCell;
       }

       private Rdl.ReportItemsType CreateHeaderTableCellReportItems(TextItem item)
       {
           Rdl.ReportItemsType headerTableCellReportItems = new Rdl.ReportItemsType();
           headerTableCellReportItems.Items = new object[] { CreateHeaderTableCellTextbox(item) };
           return headerTableCellReportItems;
       }

       private Rdl.TextboxType CreateHeaderTableCellTextbox(TextItem item)
       {
           Rdl.UserSortType sortType = new Rdl.UserSortType();
           sortType.Items = new object[] { "=Fields!" + item.DataMember + ".Value" };
           sortType.ItemsElementName = new Rdl.ItemsChoiceType13[] { Rdl.ItemsChoiceType13.SortExpression };

           Rdl.TextboxType headerTableCellTextbox = new Rdl.TextboxType();
           headerTableCellTextbox.Name = item.Text + "_Header";
           headerTableCellTextbox.Items = new object[]
               {
                   item.Text,
                   CreateHeaderTableCellTextboxStyle(item),
                   true,
                   sortType,
               };
           headerTableCellTextbox.ItemsElementName = new Rdl.ItemsChoiceType14[]
               {
                   Rdl.ItemsChoiceType14.Value,
                   Rdl.ItemsChoiceType14.Style,
                   Rdl.ItemsChoiceType14.CanGrow,
                   Rdl.ItemsChoiceType14.UserSort
               };
           return headerTableCellTextbox;
       }

       private Rdl.StyleType CreateHeaderTableCellTextboxStyle(TextItem item)
       {
           Rdl.StyleType headerTableCellTextboxStyle = new Rdl.StyleType();
           headerTableCellTextboxStyle.Items = new object[]
               {
                   item.BackgroundColor.Name,
                   item.TextColor.Name,
                   item.HeaderFont.Name,
                   item.HeaderFont.Size + "pt",
                   "700",//item.HeaderFont.Bold ? "700" : "100",
                   "Center",
                   "Middle",
                   CreateBorderStyle(),
               };
           headerTableCellTextboxStyle.ItemsElementName = new Rdl.ItemsChoiceType5[]
               {
                   Rdl.ItemsChoiceType5.BackgroundColor,
                    Rdl.ItemsChoiceType5.Color,
                   Rdl.ItemsChoiceType5.FontFamily,
                   Rdl.ItemsChoiceType5.FontSize,
                   Rdl.ItemsChoiceType5.FontWeight,
                   Rdl.ItemsChoiceType5.TextAlign,
                   Rdl.ItemsChoiceType5.VerticalAlign,
                   Rdl.ItemsChoiceType5.BorderStyle,
               };
           return headerTableCellTextboxStyle;
       }

       private Rdl.DetailsType CreateDetails()
       {
           Rdl.DetailsType details = new Rdl.DetailsType();
           details.Items = new object[] { CreateTableRows() };
           return details;
       }

       private Rdl.TableRowsType CreateTableRows()
       {
           Rdl.TableRowsType tableRows = new Rdl.TableRowsType();
           tableRows.TableRow = new Rdl.TableRowType[] { CreateTableRow() };
           return tableRows;
       }

       private Rdl.TableRowType CreateTableRow()
       {
           Rdl.TableRowType tableRow = new Rdl.TableRowType();
           tableRow.Items = new object[] { CreateTableCells(), "0.25in" };
           return tableRow;
       }

       private Rdl.TableCellsType CreateTableCells()
       {
           Rdl.TableCellsType tableCells = new Rdl.TableCellsType();
           tableCells.TableCell = new Rdl.TableCellType[m_fields.Count];
           int i = 0;
           foreach(string key in m_fields.Keys)
           {
               tableCells.TableCell[i++] = CreateTableCell(m_fields[key]);
           }
           return tableCells;
       }

       private Rdl.TableCellType CreateTableCell(TextItem item)
       {
           Rdl.TableCellType tableCell = new Rdl.TableCellType();
           tableCell.Items = new object[] { CreateTableCellReportItems(item) };
           return tableCell;
       }

       private Rdl.ReportItemsType CreateTableCellReportItems(TextItem item)
       {
           Rdl.ReportItemsType reportItems = new Rdl.ReportItemsType();
           reportItems.Items = new object[] { CreateTableCellTextbox(item) };
           return reportItems;
       }

       private Rdl.TextboxType CreateTableCellTextbox(TextItem item)
       {
           Rdl.TextboxType textbox = new Rdl.TextboxType();
           textbox.Name = item.Key;
           textbox.Items = new object[]
               {
                   "=Fields!" + item.DataMember + ".Value",
                   CreateTableCellTextboxStyle(item),
                   true,
               };
           textbox.ItemsElementName = new Rdl.ItemsChoiceType14[]
               {
                   Rdl.ItemsChoiceType14.Value,
                   Rdl.ItemsChoiceType14.Style,
                   Rdl.ItemsChoiceType14.CanGrow,
               };
           return textbox;
       }

       private Rdl.StyleType CreateTableCellTextboxStyle(TextItem item)
       {
           Rdl.StyleType style = new Rdl.StyleType();
           style.Items = new object[]
               {
                    "=iif(RowNumber(Nothing) mod 2, \"AliceBlue\", \"White\")",
                   item.Font.Name,
                   item.Font.Size + "pt",
                   item.Font.Bold ? "400" : "100",
                   GetAlign(item.Align.Alignment),
                   "Middle",
                   CreateBorderStyle(),
                   "1pt",
                   "1pt",
                   "1pt",
                   "1pt",
               };
           style.ItemsElementName = new Rdl.ItemsChoiceType5[]
               {
                   Rdl.ItemsChoiceType5.BackgroundColor,
                   Rdl.ItemsChoiceType5.FontFamily,
                   Rdl.ItemsChoiceType5.FontSize,
                   Rdl.ItemsChoiceType5.FontWeight,
                   Rdl.ItemsChoiceType5.TextAlign,
                   Rdl.ItemsChoiceType5.VerticalAlign,
                   Rdl.ItemsChoiceType5.BorderStyle,
                   Rdl.ItemsChoiceType5.PaddingLeft,
                   Rdl.ItemsChoiceType5.PaddingTop,
                   Rdl.ItemsChoiceType5.PaddingRight,
                   Rdl.ItemsChoiceType5.PaddingBottom,
               };
           return style;
       }

       private Rdl.TableColumnsType CreateTableColumns()
       {
           Rdl.TableColumnsType tableColumns = new Rdl.TableColumnsType();
           tableColumns.TableColumn = new Rdl.TableColumnType[m_fields.Count];
           int i = 0;
           foreach (string key in m_fields.Keys)
           {
               tableColumns.TableColumn[i++] = CreateTableColumn(m_fields[key]);
           }
           return tableColumns;
       }

       private Rdl.TableColumnType CreateTableColumn(TextItem item)
       {
           Rdl.TableColumnType tableColumn = new Rdl.TableColumnType();
           tableColumn.Items = new object[] { (item.Rect.Width / 96.0) + "in" };
           return tableColumn;
       }

       private Rdl.BorderColorStyleWidthType CreateBorderStyle()
       {
           Rdl.BorderColorStyleWidthType bstyle = new Rdl.BorderColorStyleWidthType();
           bstyle.Items = new object[]
               {
                   "Solid",
               };
           bstyle.ItemsElementName = new Rdl.ItemsChoiceType3[]
               {
                   Rdl.ItemsChoiceType3.Default,
               };
           return bstyle;
       }

       private string GetVAlign(StringAlignment sformat)
       {
           switch (sformat)
           {
               case StringAlignment.Center: return "Middle";
               case StringAlignment.Far: return "Bottom";
               default: return "Top";
           }
       }

       private string GetAlign(StringAlignment sformat)
       {
           switch (sformat)
           {
               case StringAlignment.Center: return "Center";
               case StringAlignment.Far: return "Right";
               default: return "Left";
           }
       }
   }
}

 

  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Drawing;

namespace CRReportDesigner
  {
     public class HeaderFooterRdlGenerator
     {
       private Dictionary<string, TextItem> m_fields;
       private int m_height;

       public Dictionary<string, TextItem> Fields
       {
           get { return m_fields; }
           set { m_fields = value; }
       }

       public int Height
       {
           get { return m_height; }
           set { m_height = value; }
       }

       public Rdl.ReportItemsType CreateItems()
       {
           Rdl.ReportItemsType items = new Rdl.ReportItemsType();
           items.Items = new Rdl.TextboxType[m_fields.Count];
           int i = 0;
           foreach (string key in m_fields.Keys)
           {
               items.Items[i++] = CreateTextBox(m_fields[key]);
           }
           return items;
       }

       private Rdl.TextboxType CreateTextBox(TextItem item)
       {
           Rdl.TextboxType textbox = new Rdl.TextboxType();
           textbox.Name = item.Key;
           if (item.Rect != Rectangle.Empty)
           {
               textbox.Items = new object[]
               {
                   item.Text,
                   CreateTextboxStyle(item),
                   true,
                   (item.Rect.Left / 96.0) + "in",
                   (item.Rect.Top / 96.0) + "in",
                   (item.Rect.Width / 96.0) + "in",
                   (item.Rect.Height / 96.0) + "in",
               };
               textbox.ItemsElementName = new Rdl.ItemsChoiceType14[]
               {
                   Rdl.ItemsChoiceType14.Value,
                   Rdl.ItemsChoiceType14.Style,
                   Rdl.ItemsChoiceType14.CanGrow,
                   Rdl.ItemsChoiceType14.Left,
                   Rdl.ItemsChoiceType14.Top,
                   Rdl.ItemsChoiceType14.Width,
                   Rdl.ItemsChoiceType14.Height,
               };
           }
           else
           {
               textbox.Items = new object[]
               {
                   item.Text,
                   CreateTextboxStyle(item),
                   true
               };
               textbox.ItemsElementName = new Rdl.ItemsChoiceType14[]
               {
                   Rdl.ItemsChoiceType14.Value,
                   Rdl.ItemsChoiceType14.Style,
                   Rdl.ItemsChoiceType14.CanGrow
               };
           }
           return textbox;
       }

       private Rdl.StyleType CreateTextboxStyle(TextItem item)
       {
           Rdl.StyleType style = new Rdl.StyleType();
           style.Items = new object[]
               {
                   item.BackgroundColor.Name,
                   item.TextColor.Name,
                   GetAlign(item.Align.Alignment),
                   GetVAlign(item.Align.LineAlignment),
                   item.Font.Name,
                   item.Font.Size + "pt",
                   item.Font.Bold ? "700" : "100",
               };
           style.ItemsElementName = new Rdl.ItemsChoiceType5[]
               {
                    Rdl.ItemsChoiceType5.BackgroundColor,
                    Rdl.ItemsChoiceType5.Color,
                   Rdl.ItemsChoiceType5.TextAlign,
                   Rdl.ItemsChoiceType5.VerticalAlign,
                   Rdl.ItemsChoiceType5.FontFamily,
                   Rdl.ItemsChoiceType5.FontSize,
                   Rdl.ItemsChoiceType5.FontWeight,
               };
           return style;
       }

       private string GetVAlign(StringAlignment sformat)
       {
           switch(sformat)
           {
               case StringAlignment.Center: return "Middle";
               case StringAlignment.Far: return "Bottom";
               default: return "Top";
           }
       }

       private string GetAlign(StringAlignment sformat)
       {
           switch (sformat)
           {
               case StringAlignment.Center: return "Center";
               case StringAlignment.Far: return "Right";
               default: return "Left";
           }
       }
   }
}

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using System.ComponentModel;

namespace CRReportDesigner
{
    public class Printer
    {
        private Printer()
        {

        }

        #region API

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct structPrinterDefaults
        {
            [MarshalAs(UnmanagedType.LPTStr)]
            public String pDatatype;
            public IntPtr pDevMode;
            [MarshalAs(UnmanagedType.I4)]
            public int DesiredAccess;
        };

        [DllImport("winspool.Drv", EntryPoint = "OpenPrinter", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall),
        SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)]
            string printerName,
            out IntPtr phPrinter,
            ref structPrinterDefaults pd);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = false,
             CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern bool ClosePrinter(IntPtr phPrinter);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct structSize
        {
            public Int32 width;
            public Int32 height;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct structRect
        {
            public Int32 left;
            public Int32 top;
            public Int32 right;
            public Int32 bottom;
        }

        [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
        internal struct FormInfo1
        {
            [FieldOffset(0), MarshalAs(UnmanagedType.I4)]
            public uint Flags;
            [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)]
            public String pName;
            [FieldOffset(8)]
            public structSize Size;
            [FieldOffset(16)]
            public structRect ImageableArea;
        };

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        internal struct structDevMode
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public String
dmDeviceName;
            [MarshalAs(UnmanagedType.U2)]
            public short dmSpecVersion;
            [MarshalAs(UnmanagedType.U2)]
            public short dmDriverVersion;
            [MarshalAs(UnmanagedType.U2)]
            public short dmSize;
            [MarshalAs(UnmanagedType.U2)]
            public short dmDriverExtra;
            [MarshalAs(UnmanagedType.U4)]
            public int dmFields;
            [MarshalAs(UnmanagedType.I2)]
            public short dmOrientation;
            [MarshalAs(UnmanagedType.I2)]
            public short dmPaperSize;
            [MarshalAs(UnmanagedType.I2)]
            public short dmPaperLength;
            [MarshalAs(UnmanagedType.I2)]
            public short dmPaperWidth;
            [MarshalAs(UnmanagedType.I2)]
            public short dmScale;
            [MarshalAs(UnmanagedType.I2)]
            public short dmCopies;
            [MarshalAs(UnmanagedType.I2)]
            public short dmDefaultSource;
            [MarshalAs(UnmanagedType.I2)]
            public short dmPrintQuality;
            [MarshalAs(UnmanagedType.I2)]
            public short dmColor;
            [MarshalAs(UnmanagedType.I2)]
            public short dmDuplex;
            [MarshalAs(UnmanagedType.I2)]
            public short dmYResolution;
            [MarshalAs(UnmanagedType.I2)]
            public short dmTTOption;
            [MarshalAs(UnmanagedType.I2)]
            public short dmCollate;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public String dmFormName;
            [MarshalAs(UnmanagedType.U2)]
            public short dmLogPixels;
            [MarshalAs(UnmanagedType.U4)]
            public int dmBitsPerPel;
            [MarshalAs(UnmanagedType.U4)]
            public int dmPelsWidth;
            [MarshalAs(UnmanagedType.U4)]
            public int dmPelsHeight;
            [MarshalAs(UnmanagedType.U4)]
            public int dmNup;
            [MarshalAs(UnmanagedType.U4)]
            public int dmDisplayFrequency;
            [MarshalAs(UnmanagedType.U4)]
            public int dmICMMethod;
            [MarshalAs(UnmanagedType.U4)]
            public int dmICMIntent;
            [MarshalAs(UnmanagedType.U4)]
            public int dmMediaType;
            [MarshalAs(UnmanagedType.U4)]
            public int dmDitherType;
            [MarshalAs(UnmanagedType.U4)]
            public int dmReserved1;
            [MarshalAs(UnmanagedType.U4)]
            public int dmReserved2;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct PRINTER_INFO_9
        {
            public IntPtr pDevMode;
        }

        [DllImport("winspool.Drv", EntryPoint = "AddFormW", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = true,
             CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern bool AddForm(
         IntPtr phPrinter,
            [MarshalAs(UnmanagedType.I4)] int level,
         ref FormInfo1 form);

        [DllImport("winspool.Drv", EntryPoint = "DeleteForm", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall),
        SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern bool DeleteForm(
         IntPtr phPrinter,
            [MarshalAs(UnmanagedType.LPTStr)] string pName);

        [DllImport("kernel32.dll", EntryPoint = "GetLastError", SetLastError = false,
             ExactSpelling = true, CallingConvention = CallingConvention.StdCall),
        SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern Int32 GetLastError();

        [DllImport("GDI32.dll", EntryPoint = "CreateDC", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = false,
             CallingConvention = CallingConvention.StdCall),
        SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern IntPtr CreateDC([MarshalAs(UnmanagedType.LPTStr)]
            string pDrive,
            [MarshalAs(UnmanagedType.LPTStr)] string pName,
            [MarshalAs(UnmanagedType.LPTStr)] string pOutput,
            ref structDevMode pDevMode);

        [DllImport("GDI32.dll", EntryPoint = "ResetDC", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = false,
             CallingConvention = CallingConvention.StdCall),
        SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern IntPtr ResetDC(
         IntPtr hDC,
         ref structDevMode
            pDevMode);

        [DllImport("GDI32.dll", EntryPoint = "DeleteDC", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = false,
             CallingConvention = CallingConvention.StdCall),
        SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern bool DeleteDC(IntPtr hDC);

        [DllImport("winspool.Drv", EntryPoint = "SetPrinterA", SetLastError = true,
            CharSet = CharSet.Auto, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
        internal static extern bool SetPrinter(
           IntPtr hPrinter,
           [MarshalAs(UnmanagedType.I4)] int level,
           IntPtr pPrinter,
           [MarshalAs(UnmanagedType.I4)] int command);

        /*
         LONG DocumentProperties(
           HWND hWnd,               // handle to parent window
           HANDLE hPrinter,         // handle to printer object
           LPTSTR pDeviceName,      // device name
           PDEVMODE pDevModeOutput, // modified device mode
           PDEVMODE pDevModeInput,  // original device mode
           DWORD fMode              // mode options
           );
         */
        [DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesA", SetLastError = true,
        ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern int DocumentProperties(
           IntPtr hwnd,
           IntPtr hPrinter,
           [MarshalAs(UnmanagedType.LPStr)] string pDeviceName,
           IntPtr pDevModeOutput,
           IntPtr pDevModeInput,
           int fMode
           );

        [DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
        ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool GetPrinter(
           IntPtr hPrinter,
           int dwLevel,
           IntPtr pPrinter,
           int dwBuf,
           out int dwNeeded
           );

        [Flags]
        internal enum SendMessageTimeoutFlags : uint
        {
            SMTO_NORMAL = 0x0000,
            SMTO_BLOCK = 0x0001,
            SMTO_ABORTIFHUNG = 0x0002,
            SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
        }
        const int WM_SETTINGCHANGE = 0x001A;
        const int HWND_BROADCAST = 0xffff;

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern IntPtr SendMessageTimeout(
           IntPtr windowHandle,
           uint Msg,
           IntPtr wParam,
           IntPtr lParam,
           SendMessageTimeoutFlags flags,
           uint timeout,
           out IntPtr result
           );

 

 


        //EnumPrinters
        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool EnumPrinters(PrinterEnumFlags Flags, string Name, uint Level,
            IntPtr pPrinterEnum, uint cbBuf,
        ref uint pcbNeeded, ref uint pcReturned);

        [StructLayout(LayoutKind.Sequential)]
        internal struct PRINTER_INFO_2
        {
            public string pServerName;
            public string pPrinterName;
            public string pShareName;
            public string pPortName;
            public string pDriverName;
            public string pComment;
            public string pLocation;
            public IntPtr pDevMode;
            public string pSepFile;
            public string pPrintProcessor;
            public string pDatatype;
            public string pParameters;
            public IntPtr pSecurityDescriptor;
            public uint Attributes;
            public uint Priority;
            public uint DefaultPriority;
            public uint StartTime;
            public uint UntilTime;
            public uint Status;
            public uint cJobs;
            public uint AveragePPM;
        }

        [FlagsAttribute]
        internal enum PrinterEnumFlags
        {
            PRINTER_ENUM_DEFAULT = 0x00000001,
            PRINTER_ENUM_LOCAL = 0x00000002,
            PRINTER_ENUM_CONNECTIONS = 0x00000004,
            PRINTER_ENUM_FAVORITE = 0x00000004,
            PRINTER_ENUM_NAME = 0x00000008,
            PRINTER_ENUM_REMOTE = 0x00000010,
            PRINTER_ENUM_SHARED = 0x00000020,
            PRINTER_ENUM_NETWORK = 0x00000040,
            PRINTER_ENUM_EXPAND = 0x00004000,
            PRINTER_ENUM_CONTAINER = 0x00008000,
            PRINTER_ENUM_ICONMASK = 0x00ff0000,
            PRINTER_ENUM_ICON1 = 0x00010000,
            PRINTER_ENUM_ICON2 = 0x00020000,
            PRINTER_ENUM_ICON3 = 0x00040000,
            PRINTER_ENUM_ICON4 = 0x00080000,
            PRINTER_ENUM_ICON5 = 0x00100000,
            PRINTER_ENUM_ICON6 = 0x00200000,
            PRINTER_ENUM_ICON7 = 0x00400000,
            PRINTER_ENUM_ICON8 = 0x00800000,
            PRINTER_ENUM_HIDE = 0x01000000
        }

        //Printer Status
        [FlagsAttribute]
        internal enum PrinterStatus
        {
            PRINTER_STATUS_BUSY = 0x00000200,
            PRINTER_STATUS_DOOR_OPEN = 0x00400000,
            PRINTER_STATUS_ERROR = 0x00000002,
            PRINTER_STATUS_INITIALIZING = 0x00008000,
            PRINTER_STATUS_IO_ACTIVE = 0x00000100,
            PRINTER_STATUS_MANUAL_FEED = 0x00000020,
            PRINTER_STATUS_NO_TONER = 0x00040000,
            PRINTER_STATUS_NOT_AVAILABLE = 0x00001000,
            PRINTER_STATUS_OFFLINE = 0x00000080,
            PRINTER_STATUS_OUT_OF_MEMORY = 0x00200000,
            PRINTER_STATUS_OUTPUT_BIN_FULL = 0x00000800,
            PRINTER_STATUS_PAGE_PUNT = 0x00080000,
            PRINTER_STATUS_PAPER_JAM = 0x00000008,
            PRINTER_STATUS_PAPER_OUT = 0x00000010,
            PRINTER_STATUS_PAPER_PROBLEM = 0x00000040,
            PRINTER_STATUS_PAUSED = 0x00000001,
            PRINTER_STATUS_PENDING_DELETION = 0x00000004,
            PRINTER_STATUS_PRINTING = 0x00000400,
            PRINTER_STATUS_PROCESSING = 0x00004000,
            PRINTER_STATUS_TONER_LOW = 0x00020000,
            PRINTER_STATUS_USER_INTERVENTION = 0x00100000,
            PRINTER_STATUS_WAITING = 0x20000000,
            PRINTER_STATUS_WARMING_UP = 0x00010000
        }

 

 

 

        //GetDefaultPrinter
        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int size);


        //SetDefaultPrinter
        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool SetDefaultPrinter(string Name);


        //EnumFormsA
        [DllImport("winspool.drv", EntryPoint = "EnumForms")]
        internal static extern int EnumFormsA(IntPtr hPrinter, int Level, ref byte pForm, int cbBuf, ref int pcbNeeded, ref int pcReturned);

 

        #endregion

        internal static int GetPrinterStatusInt(string PrinterName)
        {
            int intRet = 0;
            IntPtr hPrinter;
            structPrinterDefaults defaults = new structPrinterDefaults();

            if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
            {
                int cbNeeded = 0;
                bool bolRet = GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out cbNeeded);
                if (cbNeeded > 0)
                {
                    IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded);
                    bolRet = GetPrinter(hPrinter, 2, pAddr, cbNeeded, out cbNeeded);
                    if (bolRet)
                    {
                        PRINTER_INFO_2 Info2 = new PRINTER_INFO_2();

                        Info2 = (PRINTER_INFO_2)Marshal.PtrToStructure(pAddr, typeof(PRINTER_INFO_2));

                        intRet = System.Convert.ToInt32(Info2.Status);
                    }
                    Marshal.FreeHGlobal(pAddr);
                }
                ClosePrinter(hPrinter);
            }

            return intRet;
        }

        internal static PRINTER_INFO_2[] EnumPrintersByFlag(PrinterEnumFlags Flags)
        {
            uint cbNeeded = 0;
            uint cReturned = 0;
            bool ret = EnumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL, null, 2, IntPtr.Zero, 0, ref cbNeeded, ref cReturned);

            IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded);
            ret = EnumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL, null, 2, pAddr, cbNeeded, ref cbNeeded, ref cReturned);

            if (ret)
            {
                PRINTER_INFO_2[] Info2 = new PRINTER_INFO_2[cReturned];

                int offset = pAddr.ToInt32();

                for (int i = 0; i < cReturned; i++)
                {
                    Info2[i].pServerName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pPrinterName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pShareName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pPortName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pDriverName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pComment = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pLocation = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pDevMode = Marshal.ReadIntPtr(new IntPtr(offset));
                    offset += 4;
                    Info2[i].pSepFile = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pPrintProcessor = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pDatatype = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pParameters = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));
                    offset += 4;
                    Info2[i].pSecurityDescriptor = Marshal.ReadIntPtr(new IntPtr(offset));
                    offset += 4;
                    Info2[i].Attributes = (uint)Marshal.ReadIntPtr(new IntPtr(offset));
                    offset += 4;
                    Info2[i].Priority = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;
                    Info2[i].DefaultPriority = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;
                    Info2[i].StartTime = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;
                    Info2[i].UntilTime = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;
                    Info2[i].Status = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;
                    Info2[i].cJobs = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;
                    Info2[i].AveragePPM = (uint)Marshal.ReadInt32(new IntPtr(offset));
                    offset += 4;

                }

                Marshal.FreeHGlobal(pAddr);

                return Info2;

            }
            else
            {
                return new PRINTER_INFO_2[0];
            }
        }

        /// <summary>
        /// Get the status of the selected printer
        /// </summary>
        public static string GetPrinterStatus(string PrinterName)
        {
            int intValue = GetPrinterStatusInt(PrinterName);
            string strRet = string.Empty;
            switch (intValue)
            {
                case 0:
                    strRet = "Ready";
                    break;
                case 0x00000200:
                    strRet = "Busy";
                    break;
                case 0x00400000:
                    strRet = "Printer Door Open";
                    break;
                case 0x00000002:
                    strRet = "Printer Error";
                    break;
                case 0x0008000:
                    strRet = "Initializing";
                    break;
                case 0x00000100:
                    strRet = "I/O Active";
                    break;
                case 0x00000020:
                    strRet = "Manual Feed";
                    break;
                case 0x00040000:
                    strRet = "No Toner";
                    break;
                case 0x00001000:
                    strRet = "Not Available";
                    break;
                case 0x00000080:
                    strRet = "Off Line";
                    break;
                case 0x00200000:
                    strRet = "Out of Memory";
                    break;
                case 0x00000800:
                    strRet = "Output Bin Full";
                    break;
                case 0x00080000:
                    strRet = "Page Punt";
                    break;
                case 0x00000008:
                    strRet = "Paper Jam";
                    break;
                case 0x00000010:
                    strRet = "Paper Out";
                    break;
                case 0x00000040:
                    strRet = "Page Problem";
                    break;
                case 0x00000001:
                    strRet = "Paused";
                    break;
                case 0x00000004:
                    strRet = "Pending Deletion";
                    break;
                case 0x00000400:
                    strRet = "Printing";
                    break;
                case 0x00004000:
                    strRet = "Processing";
                    break;
                case 0x00020000:
                    strRet = "Toner Low";
                    break;
                case 0x00100000:
                    strRet = "User Intervention";
                    break;
                case 0x20000000:
                    strRet = "Waiting";
                    break;
                case 0x00010000:
                    strRet = "Warming Up";
                    break;
                default:
                    strRet = "Unknown Status";
                    break;
            }
            return strRet;
        }

        /// <summary>
        /// Delete existed form
        /// </summary>
        public static void DeleteCustomPaperSize(string PrinterName, string PaperName)
        {
            const int PRINTER_ACCESS_USE = 0x00000008;
            const int PRINTER_ACCESS_ADMINISTER = 0x00000004;

            structPrinterDefaults defaults = new structPrinterDefaults();
            defaults.pDatatype = null;
            defaults.pDevMode = IntPtr.Zero;
            defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

            IntPtr hPrinter = IntPtr.Zero;

            if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
            {
                try
                {
                    DeleteForm(hPrinter, PaperName);
                    ClosePrinter(hPrinter);
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error to delete existed form!");
                }
            }
        }

        /// <summary>
        /// Add a form
        /// </summary>
        public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                const int PRINTER_ACCESS_USE = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
               // const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype = null;
                defaults.pDevMode = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

                IntPtr hPrinter = IntPtr.Zero;

                if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
                {
                    try
                    {
                        DeleteForm(hPrinter, PaperName);
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags = 0;
                        formInfo.pName = PaperName;
                        formInfo.Size.width = (int)(WidthInMm * 1000.0);
                        formInfo.Size.height = (int)(HeightInMm * 1000.0);
                        formInfo.ImageableArea.left = 0;
                        formInfo.ImageableArea.right = formInfo.Size.width;
                        formInfo.ImageableArea.top = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("Failed! Error code:{2}",
                                PaperName, PrinterName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }

                        const int DM_OUT_BUFFER = 2;
                        const int DM_IN_BUFFER = 8;
                        structDevMode devMode = new structDevMode();
                        IntPtr hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;


                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0);

                        if (iDevModeSize < 0)
                            throw new ApplicationException("Cannot get the size of the DEVMODE struct!");

                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                        if (iRet < 0)
                            throw new ApplicationException("Cannot get the DEVMODE Struct!");

                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());


                        devMode.dmFields = 0x10000;

                        devMode.dmFormName = PaperName;

                        Marshal.StructureToPtr(devMode, hDevMode, true);

                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName,
                                 printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                        if (iRet < 0)
                            throw new ApplicationException("Cannot set the orientation!");

                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                            throw new ApplicationException(" Call GetPrinter failed!");

                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                        if (!bSuccess)
                            throw new ApplicationException("Call GetPrinter failed!");

                        printerInfo = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;

                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                        if (!bSuccess)
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "Call GetPrinter failed!");

                        SendMessageTimeout(
                           new IntPtr(HWND_BROADCAST),
                           WM_SETTINGCHANGE,
                           IntPtr.Zero,
                           IntPtr.Zero,
                           Printer.SendMessageTimeoutFlags.SMTO_NORMAL,
                           1000,
                           out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("Cannot open prnter {0}, Error Code: {1}",
                        PrinterName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr hDC = CreateDC(null, PrinterName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH = 0x00000008L;
                    pDevMode.dmFields = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize = 256;
                    pDevMode.dmPaperWidth = (short)(WidthInMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }

        /// <summary>
        /// Get the list of local printers
        /// </summary>
        public static System.Collections.ArrayList GetPrinterList()
        {
            System.Collections.ArrayList alRet = new System.Collections.ArrayList();
            PRINTER_INFO_2[] Info2 = EnumPrintersByFlag(PrinterEnumFlags.PRINTER_ENUM_LOCAL);
            for (int i = 0; i < Info2.Length; i++)
            {
                alRet.Add(Info2[i].pPrinterName);
            }
            return alRet;
        }


        /// <summary>
        /// Get the name of the default printer
        /// </summary>
        public static string GetDeaultPrinterName()
        {
            StringBuilder dp = new StringBuilder(256);
            int size = dp.Capacity;
            if (GetDefaultPrinter(dp, ref size))
            {
                return dp.ToString();
            }
            else
            {
                int rc = GetLastError();
                System.Windows.Forms.MessageBox.Show("Failed to get default printer!Error code:" + rc.ToString());
                return string.Empty;
            }
        }

        /// <summary>
        /// Set default printer
        /// </summary>
        public static void SetPrinterToDefault(string PrinterName)
        {
            SetDefaultPrinter(PrinterName);
        }

        /// <summary>
        /// Whether the specific printer is in available printer list
        /// </summary>
        public static bool PrinterInList(string PrinterName)
        {
            bool bolRet = false;

            System.Collections.ArrayList alPrinters = GetPrinterList();

            for (int i = 0; i < alPrinters.Count; i++)
            {
                if (PrinterName == alPrinters[i].ToString())
                {
                    bolRet = true;
                    break;
                }
            }

            alPrinters.Clear();
            alPrinters = null;

            return bolRet;
        }

        /// <summary>
        /// Whether the specific form is in the selected printer
        /// </summary>
        public static bool FormInPrinter(string PrinterName, string PaperName)
        {
            bool bolRet = false;

            System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();

            pd.PrinterSettings.PrinterName = PrinterName;

            foreach (System.Drawing.Printing.PaperSize ps in pd.PrinterSettings.PaperSizes)
            {
                if (ps.PaperName == PaperName)
                {
                    bolRet = true;
                    break;
                }
            }

            pd.Dispose();

            return bolRet;
        }

        /// <summary>
        /// Whether pageheight and pagewidth of the form are same with the specific ones
        /// </summary>
        public static bool FormSameSize(string PrinterName, string FormName, decimal Width, decimal Height)
        {
            bool bolRet = false;

            System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();

            pd.PrinterSettings.PrinterName = PrinterName;

            foreach (System.Drawing.Printing.PaperSize ps in pd.PrinterSettings.PaperSizes)
            {
                if (ps.PaperName == FormName)
                {
                    decimal decWidth = FromInchToCM(System.Convert.ToDecimal(ps.Width));
                    decimal decHeight = FromInchToCM(System.Convert.ToDecimal(ps.Height));

                    if (System.Math.Round(decWidth, 0) == System.Math.Round(Width, 0) && System.Math.Round(decHeight, 0) == System.Math.Round(Height, 0))
                        bolRet = true;
                    break;
                }
            }

            pd.Dispose();

            return bolRet;
        }

        /// <summary>
        /// Convert inch to cm
        /// 1 inch = 2.5400 cm
        /// </summary>
        public static decimal FromInchToCM(decimal inch)
        {
            return Math.Round((System.Convert.ToDecimal((inch / 100)) * System.Convert.ToDecimal(2.5400)), 2);
        }

 

    }
}

 

using System;
using System.Collections.Generic;
using System.Text;

namespace CRReportDesigner
{
    public class EMFDeviceInfo
    {
        private bool m_Landscape = false;

        public bool Landscape
        {
            get
            {
                return this.m_Landscape;
            }
            set
            {
                this.m_Landscape = value;
            }
        }

        /*
         * The pixel depth of the color range supported by the image output.
         * Valid values are 1, 4, 8, 24, and 32.
         * The default value is 24.
         * ColorDepth is only supported for TIFF rendering and is otherwise ignored by the report server for other image output formats.
         * Note:
         * For this release of SQL Server, the value of this setting is ignored, and the TIFF image is always rendered as 24-bit.
        */
        private int m_ColorDepth = 24;

        public int ColorDepth
        {
            get
            {
                return this.m_ColorDepth;
            }
        }


        /*
         * The number of columns to set for the report. This value overrides the report's original settings.
         *
         * not used
         *
        */
        private int m_Columns = 0;

        public int Columns
        {
            get
            {
                return this.m_Columns;
            }
            set
            {
                this.m_Columns = value;
            }
        }


        /*
         * The column spacing to set for the report. This value overrides the report's original settings.
         *
         * not used
         *
        */
        private int m_ColumnSpacing = 0;

        public int ColumnSpacing
        {
            get
            {
                return this.m_ColumnSpacing;
            }
            set
            {
                this.m_ColumnSpacing = value;
            }
        }

        /*
         * The resolution of the output device in x-direction. The default value is 96.
         *
        */
        private int m_DpiX = 96;

        public int DpiX
        {
            get
            {
                return this.m_DpiX;
            }
            set
            {
                this.m_DpiX = value;
            }
        }


        /*
         * The resolution of the output device in y-direction. The default value is 96.
         *
        */
        private int m_DpiY = 96;

        public int DpiY
        {
            get
            {
                return this.m_DpiY;
            }
            set
            {
                this.m_DpiY = value;
            }
        }


        /*
         * The last page of the report to render. The default value is the value for StartPage.
         *
         */
        private int m_EndPage = 0;

        public int EndPage
        {
            get
            {
                return this.m_EndPage;
            }
            set
            {
                this.m_EndPage = value;
            }
        }


        /*
         * The first page of the report to render. A value of 0 indicates that all pages are rendered. The default value is 1.
         *
         */
        private int m_StartPage = 1;

        public int StartPage
        {
            get
            {
                return this.m_StartPage;
            }
            set
            {
                this.m_StartPage = value;
            }
        }

        /*
         * The bottom margin value, in inches, to set for the report. You must include an integer or decimal value followed by "in" (for example, 1in). This value overrides the report's original settings.
         *
         */
        private decimal m_MarginBottom = 0;

        public decimal MarginBottom
        {
            get
            {
                return this.m_MarginBottom;
            }
            set
            {
                this.m_MarginBottom = value;
            }
        }


        /*
         * The top margin value, in inches, to set for the report. You must include an integer or decimal value followed by "in" (for example, 1in). This value overrides the report's original settings.
         *
         */
        private decimal m_MarginTop = 0;

        public decimal MarginTop
        {
            get
            {
                return this.m_MarginTop;
            }
            set
            {
                this.m_MarginTop = value;
            }
        }


        /*
         * The left margin value, in inches, to set for the report. You must include an integer or decimal value followed by "in" (for example, 1in). This value overrides the report's original settings.
         *
         */
        private decimal m_MarginLeft = 0;

        public decimal MarginLeft
        {
            get
            {
                return this.m_MarginLeft;
            }
            set
            {
                this.m_MarginLeft = value;
            }
        }


        /*
         * The right margin value, in inches, to set for the report. You must include an integer or decimal value followed by "in" (for example, 1in). This value overrides the report's original settings.
         * 
         */
        private decimal m_MarginRight = 0;

        public decimal MarginRight
        {
            get
            {
                return this.m_MarginRight;
            }
            set
            {
                this.m_MarginRight = value;
            }
        }

        /*
         * One of the Graphics Device Interface (GDI) supported output formats: BMP, EMF, GIF, JPEG, PNG, or TIFF.
         *
         */
        private string m_OutputFormat = "EMF";

        public string OutputFormat
        {
            get
            {
                return this.m_OutputFormat;
            }
            set
            {
                this.m_OutputFormat = value;
            }
        }

        /*
         * The page height, in inches, to set for the report. You must include an integer or decimal value followed by "in" (for example, 11in). This value overrides the report's original settings.
         *
         */
        private decimal m_PageHeight = 0;

        public decimal PageHeight
        {
            get
            {
                return this.m_PageHeight;
            }
            set
            {
                this.m_PageHeight = value;
            }
        }


        /*
         * The page width, in inches, to set for the report. You must include an integer or decimal value followed by "in" (for example, 8.5in). This value overrides the report's original settings.
         *
         *
        */
        private decimal m_PageWidth = 0;

        public decimal PageWidth
        {
            get
            {
                return this.m_PageWidth;
            }
            set
            {
                this.m_PageWidth = value;
            }
        }

        public string DeviceInfoString
        {
            get
            {
                string strRet = string.Empty;

                strRet += "<DeviceInfo>" +
                    "  <OutputFormat>" + this.m_OutputFormat + "</OutputFormat>";

                if (this.m_Landscape)
                    strRet +=
                        "  <PageWidth>" + this.m_PageHeight.ToString() + "cm</PageWidth>" +
                        "  <PageHeight>" + this.m_PageWidth.ToString() + "cm</PageHeight>";
                else
                    strRet +=
                        "  <PageWidth>" + this.m_PageWidth.ToString() + "cm</PageWidth>" +
                        "  <PageHeight>" + this.m_PageHeight.ToString() + "cm</PageHeight>";

                strRet +=
                        "  <MarginTop>" + this.m_MarginTop.ToString() + "cm</MarginTop>" +
                        "  <MarginLeft>" + this.m_MarginLeft.ToString() + "cm</MarginLeft>" +
                        "  <MarginRight>" + this.m_MarginRight.ToString() + "cm</MarginRight>" +
                        "  <MarginBottom>" + this.m_MarginBottom.ToString() + "cm</MarginBottom>";

                strRet += "</DeviceInfo>";

                return strRet;

            }
        }

    }
}

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Reporting.WinForms;
using System.Drawing.Printing;
using System.Data;
using System.Drawing.Imaging;

namespace CRReportDesigner
{
    public partial class EMFStreamPrintDocument : System.Drawing.Printing.PrintDocument
    {
        private int m_CurrentPageIndex;

        private IList<Stream> m_EMFStreams;
        private Microsoft.Reporting.WinForms.LocalReport m_LocalReport = null;
        private System.Drawing.Imaging.Metafile m_PageImage = null;

        public EMFStreamPrintDocument(Microsoft.Reporting.WinForms.LocalReport localReport, string ReportName)
            : base()
        {
            this.m_ReportName = ReportName;
            string strMessage = string.Empty;
            if (this.ReadSetting(out strMessage) == null)
                this.m_ErrorMessage = strMessage;
            if (this.m_ErrorMessage == string.Empty)
            {
                this.m_LocalReport = localReport;
            }
        }

        private string m_ErrorMessage = string.Empty;

        public string ErrorMessage
        {
            get
            {
                return this.m_ErrorMessage;
            }
            set
            {
                this.m_ErrorMessage = value;
            }
        }

        private string m_ReportName = string.Empty;

        private EMFDeviceInfo ReadSetting(out string WarningMessage)
        {

            WarningMessage = string.Empty;

            System.Data.DataSet dsXML = new DataSet();

            EMFDeviceInfo emfdi = new EMFDeviceInfo();

            dsXML.ReadXml(System.Windows.Forms.Application.StartupPath + @"\ReportSettings.xml");

            System.Data.DataTable dtXML = new DataTable();

            foreach (System.Data.DataTable dt in dsXML.Tables)
            {
                if (dt.TableName == this.m_ReportName)
                {
                    dtXML = dt;
                    break;
                }
            }

            if (dtXML.Rows.Count != 0)
            {
                System.Data.DataRow dr = dtXML.Rows[0];
                if (Printer.PrinterInList(dr["PrinterName"].ToString()))
                {
                    base.PrinterSettings.PrinterName = dr["PrinterName"].ToString();
                    if (Printer.FormInPrinter(dr["PrinterName"].ToString(), dr["PaperName"].ToString()))
                    {
                        if (Printer.FormSameSize(dr["PrinterName"].ToString(), dr["PaperName"].ToString(), System.Convert.ToDecimal(dr["PageWidth"]), System.Convert.ToDecimal(dr["PageHeight"])))
                        {

                            bool bolExist = false;

                            foreach (System.Drawing.Printing.PaperSize ps in base.PrinterSettings.PaperSizes)
                            {
                                if (ps.PaperName == dr["PaperName"].ToString())
                                {
                                    base.PrinterSettings.DefaultPageSettings.PaperSize = ps;
                                    base.DefaultPageSettings.PaperSize = ps;
                                    bolExist = true;
                                    break;
                                }
                            }

                            if (!bolExist)
                            {
                                WarningMessage += "\r\n Can not use the customized paper, because the printer selected does not the customized papersize!";

                                if (dtXML != null)
                                    dtXML.Dispose();
                                if (dsXML != null)
                                {
                                    dsXML.Clear();
                                    dsXML = null;
                                }

                                return null;
                            }

                            if (dr["Orientation"].ToString() == "Z")
                            {
                                base.DefaultPageSettings.Landscape = false;
                                base.PrinterSettings.DefaultPageSettings.Landscape = false;
                                emfdi.Landscape = false;
                            }
                            else
                            {
                                base.DefaultPageSettings.Landscape = true;
                                base.PrinterSettings.DefaultPageSettings.Landscape = true;
                                emfdi.Landscape = true;
                            }

                            this.bolOrientation = emfdi.Landscape;

                            emfdi.PageWidth = System.Convert.ToDecimal(dr["PageWidth"].ToString());
                            emfdi.PageHeight = System.Convert.ToDecimal(dr["PageHeight"].ToString());
                            emfdi.MarginTop = System.Convert.ToDecimal(dr["MarginTop"].ToString());
                            emfdi.MarginBottom = System.Convert.ToDecimal(dr["MarginBottom"].ToString());
                            emfdi.MarginLeft = System.Convert.ToDecimal(dr["MarginLeft"].ToString());
                            emfdi.MarginRight = System.Convert.ToDecimal(dr["MarginRight"].ToString());

                            base.PrinterSettings.PrinterName = dr["PrinterName"].ToString();

                            if (dtXML != null)
                                dtXML.Dispose();
                            if (dsXML != null)
                            {
                                dsXML.Clear();
                                dsXML = null;
                            }
                            WarningMessage = string.Empty;
                            return emfdi;
                        }
                        else
                            WarningMessage += "\r\n Papersize defined in the config file is not the same with the one in the system!";
                    }
                    else
                        WarningMessage += "\r\n Printer defined in the config file does not support the customized papersize!";
                }
                else
                    WarningMessage += "\r\n Printer defined in the config file is not in the available printer list!";
            }
            else
                WarningMessage += "\r\n Can not get any information about the report in the config file!";

            if (dtXML != null)
                dtXML.Dispose();
            if (dsXML != null)
            {
                dsXML.Clear();
                dsXML = null;
            }
            return null;
        }

        private bool bolOrientation = false;

        private Stream CreateStream(string Name, string FileNameExtension, Encoding Encoding, string MimeType, bool WillSeek)
        {
            System.IO.Stream streamRet = new System.IO.MemoryStream();
            this.m_EMFStreams.Add(streamRet);
            return streamRet;
        }

        private void Export(LocalReport Report)
        {
            string strMessage = string.Empty;

            EMFDeviceInfo emfdi = this.ReadSetting(out strMessage);

            string strDeviceInfo = emfdi.DeviceInfoString;

            emfdi = null;

            Microsoft.Reporting.WinForms.Warning[] Warnings;

            this.m_EMFStreams = new System.Collections.Generic.List<System.IO.Stream>();

            Report.Render("Image", strDeviceInfo, this.CreateStream, out Warnings);

            foreach (System.IO.Stream s in this.m_EMFStreams)
                s.Position = 0;


        }

        protected override void OnBeginPrint(PrintEventArgs ev)
        {
            base.OnBeginPrint(ev);
        }

        protected override void OnPrintPage(PrintPageEventArgs ev)
        {
            base.OnPrintPage(ev);

            if (this.m_EMFStreams == null || this.m_EMFStreams.Count == 0)
            {
                this.Export(this.m_LocalReport);
                this.m_CurrentPageIndex = 0;
                if (this.m_EMFStreams.Count == 0 || this.m_EMFStreams == null)
                    return;
            }

            this.m_PageImage = new Metafile(this.m_EMFStreams[this.m_CurrentPageIndex]);

            ev.Graphics.DrawImageUnscaledAndClipped(this.m_PageImage, ev.PageBounds);

            this.m_CurrentPageIndex++;

            ev.HasMorePages = (this.m_CurrentPageIndex < this.m_EMFStreams.Count);

            if (this.m_CurrentPageIndex == this.m_EMFStreams.Count)
            {
                this.m_CurrentPageIndex = 0;
                this.m_EMFStreams.Clear();
                this.m_EMFStreams = null;
                this.m_PageImage.Dispose();
                base.Dispose();
            }

        }

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章