Cover in C #

xiaoxiao2021-03-06  69

// Version 2.2 // C # // Accept control other than a Form // You can add your own print functions for specific controls and for report title formatting // Controls can expand // Expendable TextBox multiline added // Expandable ListBox added // Expendable FlexGrid added (Grid from Component One: code in comments only [no references]) // DataGrid printing // More comments in source code // Report printed can continue on many pages // Can display a trace of controls printed // Can print page number using your own String.Format // Report can be print to a multiframe Tif file (example: for faxing) // Better algorithm to compute extension of container control with rezizable side by side childs // Test

Using system.drawing; using system.collections; using system.windows.forms; using system.data; using system.drawing.image;

Namespace formprinting {

public class FormPrinting {#region "public section" // publics property that can be changed public bool TextBoxBoxed = false; // box around TextBox controls public bool TabControlBoxed = true; // box around TabControl controls public bool LabelInBold = true; // Print all labels in bold public bool PrintPreview = true; // enabled Print preview instead of direct printing public bool DisabledControlsInGray = false; // Color for disabled controls public bool PageNumbering = false; // If true, reserve space at the bottom of each page and print page number public string PageNumberingFormat = "Page {0}"; // String format for page number public OrientationENum Orientation = OrientationENum.Automatic; // choose print orientation (Automatic, protrait or Landscape) public ControlPrinting DelegatePrintingReportTitle; // Function That Will Print Report Title. Can Be Changd // Public Bool Controlscanexpand = True; // Indicate If Class Accept Control's Expansion Public Single TopMargin = 0; // If 0, use default margin, else use this public Single BottomMargin = 0; // If 0, use default margin, else use this public HorizontalAlignment HAlignment = HorizontalAlignment.Center; public enum OrientationENum {Automatic = 1, Portrait = 2, lanscape = 3}

Public Enum parentcontrolprinting {beforechilds = 1, afterChilds = 2,}

// delegate for providing of print function by control type public delegate void ControlPrinting (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls);

// Constructor public FormPrinting (System.Windows.Forms.Control f) {_f = f; _TextBoxLikeControl = new ArrayList (); _DelegatesforControls = new ArrayList (); _Pen = new Pen (Color.Black); // add build-in TYPES AND FUNCTIONS

AddTextBoxLikeControl ("ComboBox"); AddTextBoxLikeControl ("DateTimePicker"); AddTextBoxLikeControl ("DateTimeslicker); AddTextBoxLikeControl (" NumericUpdown ");

AddDelegateToPrintControl ( "TextBox", new ControlPrinting (PrintTextBox)); AddDelegateToPrintControl ( "System.Windows.Forms.Label", new ControlPrinting (PrintLabel)); AddDelegateToPrintControl ( "System.Windows.Forms.CheckBox", new ControlPrinting (PrintCheckBox)) ; AddDelegateToPrintControl ( "System.Windows.Forms.RadioButton", new ControlPrinting (PrintRadioButton)); AddDelegateToPrintControl ( "System.Windows.Forms.GroupBox", new ControlPrinting (PrintGroupBox)); AddDelegateToPrintControl ( "System.Windows.Forms.Panel" , new ControlPrinting (PrintPanel)); AddDelegateToPrintControl ( "System.Windows.Forms.TabControl", new ControlPrinting (PrintTabControl)); AddDelegateToPrintControl ( "System.Windows.Forms.PictureBox", new ControlPrinting (PrintPictureBox)); AddDelegateToPrintControl ( "System .Windows.forms.listbox ", new controlprinting (printlistbox); adddelegatetoprintControl (" System.Windows.Forms.DataGrid ", New ControlPrinting (PrintDataGrid);}

///

/// Let user add TextBox like control type name /// /// TextBox like control type name public void AddTextBoxLikeControl (string stringType ) {_TextBoxLikeControl.Add (stringType);} /// /// Let users provide their own print function for specific control type /// /// Control type name /// function (must match with FormPrinting.ControlPrinting delegate) public void AddDelegateToPrintControl (string stringType, ControlPrinting printFunction) {_DelegateforControls d = new _DelegateforControls (); d .typ = stringType; D.PrintFunction = printfunction; _dlegatesForControls.add (d);} #ENDREGION

#region "Private data" // private Font _printFont; private Pen _Pen; private Brush _Brush; private System.Windows.Forms.Control _f; private ArrayList _TextBoxLikeControl; private System.Single _xform; private ArrayList _DelegatesforControls; private MultiPageManagement _MultiPage; private System .Text.stringbuilder _tracelog; private int _indent; private class _dlegateforControls {public string type; public controlprinting printfunction;} #ENDREGION

#region "Managing PrintDocument or TIF object" ///

/// Launch printing Calculate start position and orientation /// public void Print () {try {PrintDocument pd = new PrintDocument ();. InitPrinting (ref pd); pd.PrintPage = new PrintPageEventHandler (this.pd_PrintPage); pd.DocumentName = _f.Text; if (PrintPreview) {PrintPreviewDialog pp = new PrintPreviewDialog (); pp.Document = pd; pp.WindowState = FormWindowState .Maximized; pp.showdialog ();} else {pd.print ();}} catch (exception ex) {messagebox.show (ex. TString ());}}} public void printtotiftiffile (String filename) {Try {/ / Compute bitmap propertiy about same as default printer PrintDocument pd = new PrintDocument (); InitPrinting (ref pd); System.Drawing.Bitmap bitmapAllPages, bitmapAdditionnalPage; bitmapAllPages = new Bitmap (pd.DefaultPageSettings.Bounds.Width, pd.DefaultPageSettings.Bounds .Height); Bitmapadditionnalpa GE = new bitmap (pd.defaultpagesettings.bounds.width, pd.defaultpagesettings.bounds.Height); graphics g;

// prepare parameters to save multiframe image system.drawing.imaging.Encoderparameters eps; eps = new system.drawing.Imaging.EncoderParameters (); BOOL firstPAGE = true;

// Print pages do {if (firstPage) g = Graphics.FromImage (bitmapAllPages); else g = Graphics.FromImage (bitmapAdditionnalPage); g.Clear (System.Drawing.Color.White); _MultiPage.NewPage (g); Single Extendedheight; SINGLE Y;

y = 0; extendedHeight = 0; bool scanForChildControls; if (DelegatePrintingReportTitle == null) PrintReportTitle (_f, ParentControlPrinting.BeforeChilds, _MultiPage, _xform, y, ref extendedHeight, out scanForChildControls); else DelegatePrintingReportTitle (_f, ParentControlPrinting.BeforeChilds, _MultiPage, _xform, y, ref extendedHeight, out scanForChildControls); y = extendedHeight; // Print each control on the form Single globalExtendedHeight; PrintControls (_f, _MultiPage, _xform, y, out globalExtendedHeight);

if (firstPage) {// Create the parameter and choose multi-frame eps.Param [0] = new EncoderParameter (Encoder.SaveFlag, (long) EncoderValue.MultiFrame); // Get the correct encoder from the list of available encoders ImageCodecInfo [] infos = imagecodecinfo.getimageEncoders (); int n = 0; while (infos [n] .mimeType! = "image / TIFF") N ; // save the first page bitmapallpages.save (filename ".tif", infos [n], eps);} else {// Create the parameter and choose FrameDimensionPage eps.Param [0] = new EncoderParameter (Encoder.SaveFlag, (long) EncoderValue.FrameDimensionPage); // save the first page bitmapAllPages.SaveAdd (BitmapadditionNalpage, EPS);} firestpage = false;} while

// Flush pages to file eps.Param [0] = new EncoderParameter (Encoder.SaveFlag, (long) EncoderValue.Flush); bitmapAllPages.SaveAdd (eps);} catch (Exception ex) {MessageBox.Show (ex.ToString ( );

Public string gettrace () {return_tracelog.tostring ();

Private Void Initprinting (Ref PrintDocument Pd) {

_traceLog = new System.Text.StringBuilder (); _indent = 0; // Calculate Form position for printing switch (Orientation) {case OrientationENum.Automatic: if (_f.Size.Width> (pd.DefaultPageSettings.Bounds.Width - pd .DefaultPageSettings.Margins.Right - pd.DefaultPageSettings.Margins.Left)) pd.DefaultPageSettings.Landscape = true; break; case OrientationENum.Lanscape: pd.DefaultPageSettings.Landscape = true; break; case OrientationENum.Portrait: pd.DefaultPageSettings. landscape = false; break;} // Set page area Single pageTop = pd.DefaultPageSettings.Margins.Top; Single pageBottom = pd.DefaultPageSettings.Bounds.Height - pd.DefaultPageSettings.Margins.Bottom; Single pageLeft = pd.DefaultPageSettings.Margins .Lefaultpagesetting = pd.defaultpagesettings.bounds.width - pd.defaultpagesettings.Margins.right; if (TopMargin! = 0) PageTop = TopMargin; IF (bottommargin! = 0) PageTop = Bottommargin;

// Calculate left position of print switch (this.HAlignment) {case HorizontalAlignment.Left: _xform = pageLeft; break; case HorizontalAlignment.Center: _xform = (pd.DefaultPageSettings.Bounds.Width - _f.Size.Width) / 2; Break; Case HorizontalaLAlignment.right: _xform = PAGERIGHT - _F.SIZE.WIDTH; BREAK;}

_Multipage = New MultipageManagement (Paget, Pagebottom, Pageleft, PageRight, _f.font, Pagenumbering, PagenumberingFormat);

///

/// Event Handler Called by The Print Document Engine. Called for Each Pages /// /// /// private void pd_PrintPage (object sender, PrintPageEventArgs ev) {_MultiPage.NewPage (ev.Graphics); Single extendedHeight; Single y; y = 0; extendedHeight = 0; bool scanForChildControls; if (DelegatePrintingReportTitle = = null) PrintReportTitle (_f, ParentControlPrinting.BeforeChilds, _MultiPage, _xform, y, ref extendedHeight, out scanForChildControls); else DelegatePrintingReportTitle (_f, ParentControlPrinting.BeforeChilds, _MultiPage, _xform, y, ref extendedHeight, out scanForChildControls); y = extendedHeight ;

// Print Each Control on The form, print; printcontrols (_f, _multipage, _xform, y, out globalextendedheight);

IF (_multipage.lastpage ()) {ev.hasmorepages = false; _multipage.resetpage ();} else ev.hasmorepages = true;

public void PrintReportTitle (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false; Font printFont = new Font (c.Font.Name, (C.font.size * 1.3), fontstyle.bold; float fontheight = mp.FontHeight (PrintFont); Pen Pen = new pen (color.black, 2); extendedheight = fontheight 3 pen.width 1;

Mp.beginprintunit (Y, Extendedheight); //mp.drawstring(c.text, printfont, brushes.black, x, y, c.width, fontheight); y = fontheight 3; //mp.drawlines( Pen , x, y, x c.size.width, y); mp.endprintunit ();} #ENDREGION

#Region "Recursive Printing of Controls" ///

/// Print Child Controls of a "Parent" Control. ///controls areprinted from top to bottom. // this is the function That Calculate Position of Each Control Depending of the extension of child controls /// /// "parent" control /// Printing Page Object /// x position of "parent" Control /// y position of "parent" control /// < param name = "globalExtendedHeight"> necessary height grow of "parent" control to fit with combination of child control growing public void PrintControls (System.Windows.Forms.Control c, MultiPageManagement mp, Single x, Single y, out Single globalExtendedHeight) {int nbCtrl = c.Controls.Count; Single [] yPos = new Single [nbCtrl]; System.Windows.Forms.Control [] controls = new System.Windows.Forms.Control [nbCtrl];

// do a list of child controls for (int i = 0; i

// sort theme by vertical position system.Array.Sort (YPOS, Controls);

= 0; // Single GlobaleXtendedypos = 0; system.collections.arraylist extendedypos = new system.collections.arrayList (); // ************* *********************************************************** ** // This loop over child controls calculate position of them. // Algorithm take care of controls that expand besides and above. // It keep an arraylist of original and printed (after expansion) bottom // position of expanded control. / SEWAS Originally Below Expanded Controls // ************************************** ****************************** for (int i = 0; i = e.originalBottom) // completely under it {if (e.totalPushDown> pushDownHeight) Pushdownheight = E. TOTALPUSHDOWN;} Single CP = Controls [i] .Location.y pushdownhem;

SINGLE Extendedheight; PrintControl (Controls [i], MP, X Controls [i] .Location.x, y cp, out extendedheight); if (Extendedheight> 0) {// Keep Extention with y position element E = New Element (); E.originalbottom = controls [i] .Location.y controls [i] .height; E.PrINtedBottom = CP Controls [i] .height extendedheight; extendedYPos.Add (e);}} // Same .. computation for bottom of container control Its bottom line is // below all child controls So it is extended the same as the most pushed // child control globalExtendedHeight = 0;. foreach (Element e in extendedYPos) if (e.totalPushDown> globalExtendedHeight) globalExtendedHeight = e.totalPushDown;} private class Element {public Single originalBottom; public Single printedBottom; public Single totalPushDown {get {return printedBottom - originalBottom;}}}

///

/// This sub simply use recursivity to print child controls and print /// the parent control (height may grow depending of child controls). /// Extension is push up to the previous parent. // / /// /// /// /// /// public void printcontrol (System.Windows.Forms.Control C, MultipageManagement MP, Single X, Single y, out Single extendedHeight) {extendedHeight = 0;! // if (c.Visible == true) if (c.Tag = null) {bool scanForChildControls; try {// Print my header PrintOneControl (c, ParentControlPrinting.BeforeChilds, MP, X, Y, Ref Extendedheight, Out ScanforchildControls; // Print Contained Controls IF (ScanforchildControls) {y = extendedheight;

_INDENT = 1; Single ChildControlsextendedheight; PrintControls (C, MP, X, Y, Out ChildControlseXtendedheight); _INDENT - = 1;

// Print my bottom (habitually a frame arround child controls) PrintOneControl (c, ParentControlPrinting.AfterChilds, mp, x, y, ref ChildControlsExtendedHeight, out scanForChildControls); extendedHeight = ChildControlsExtendedHeight;}} catch (Exception ex) {MessageBox.Show ("Error Printing Control of Type" C.gettype (). TOSTRING () System.Environment.newline System.Environment.Newline EX.TOSTRING ());}}}}}}}}}}}}}

///

/// print a control (not is children). Call the print function depending of the type of the control /// /// /// /// /// /// < param name = "extendedHeight"> public void PrintOneControl (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {// Silver color if disable if (c.Enabled || DisabledControlsInGray!) {_Pen = new Pen (Color.Black); _Brush = Brushes.Black;} else {_Pen = new Pen (Color.Silver); _Brush = Brushes.Silver;} ScanForChildControls = true; string s = c.GetType () ToString ();. bool founded = false; // First check if it's a text box like control if foreach (string sType in _TextBoxLikeControl) if (s.IndexOf (sType (founded!) )> = 0) {SINGLE H; h = mp.fontheight (New Font (c.font.name, c.font.size); extendedheight = mp.beginprintUnit (Y, h); PrintText (C, MP, X, Y, TextBoxBoxed, False, TextBoxed, HorizontalaLight.Left); MP. Endprintunit (); foundd = true; scanforchildcontrols = false; Break;}

// process Other Type of Control, Beginning At the end of the list (! Foundd for a type) ife (@ i = _dlegatesforcontrols.count-1; i> = 0; i -) // from end to the beginning {_DelegateforControls d = (_DelegateforControls) _DelegatesforControls [i]; if (s.EndsWith (d.typ)) {d.PrintFunction (c, typePrint, mp, x, y, ref extendedHeight, out ScanForChildControls); Break;}} _tracelog.append (_indent.toString () "-" " " S "(" C.Text ":" C.Name ") x =" x.toString () "y =" y.toString () "h =" c.height.tostring () " " extendedheight.tostring () system.Environment.newline);} # EndRegion

#Region "Text Print" ///

///print a single line text for many controls. do some formatting /// /// control to print (MUST) Have these Properties: Font, Text, Width and Height) /// graphics object (printed page) /// x position /// y position /// DRAW A BOX arround text /// use bold font /// Adjust vertical to obtain precise alignment from different type of control /// Horizontal alignment of text in control print area public void PrintText (System.Windows.Forms.Control c, MultiPageManagement mp, Single x, Single y, bool tbBoxed, bool inBold, bool verticalCentering, HorizontalAlignment hAlignment) {Single yAdjusted = y; // Box if (tboxed) mp.drawRectangle (_pen, x, y, c.width, c.Height); // text Font PrintFont; if (inbold) PrintFont = New font (c.font.name, c.font.size, fontstyle.bold); else printfont = new font (c.font.name, c.font.size);

if (verticalCentering) {Single fontHeight = printFont.GetHeight (mp.Graphics ()); Single deltaHeight = (c.Height - fontHeight) / 2; yAdjusted = deltaHeight;} else yAdjusted = 2; mp.DrawString (c. Text, PrintFont, _brush, x, yadjusted, c.width, c.Height, BuildFormat (Halignment));

public StringFormat BuildFormat (HorizontalAlignment hAlignment) {StringFormat drawFormat = new StringFormat (); switch (hAlignment) {case HorizontalAlignment.Left: drawFormat.Alignment = StringAlignment.Near; break; case HorizontalAlignment.Center: drawFormat.Alignment = StringAlignment.Center; break ; case HorizontalAlignment.Right: drawFormat.Alignment = StringAlignment.Far; break;} return drawFormat;} public string TrimBlankLines (string s) {if (s == null) return s; else {for (int i = s.Length; i == 1; I -) IF ((s [i] .tostring ()! = keys.enter.tostring () && (s [i] .tostring ()! = keys.linefeed.tostring ()) && (s [i] .tostring ()! = "")) Return S.Substring (0, i); return s;}} #ENDREGION

#region "Controls printing" ///

/// Print single line or multi lines TextBox. /// public void PrintTextBox (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single X, Single Y, Ref Single Extendedheight, Out Bool ScanforchildControls) {ScanforchildControls = FALSE

TextBox TB = (System.Windows.Forms.TextBox) C; Single H = MP.FONTHEIGHT (New Font (TB.Font.Name, Tb.Font.Size)); if (! Tb.multiline) {extendedheight = MP. Beginprintunit (Y, H); PrintText (C, MP, X, Y, TextBoxBoxed, TB.Font.Bold, TextBoxBoxed, Tb.TextAlign); mp.EndprintUnit ();} else // multiline {// cut text int inTo Lines that fit in printed textBox width // Define an area of ​​one line height and call MeasureString on it // This method return charactersFitted for the line ArrayList lines = new ArrayList (); System.Drawing.Graphics g = mp.Graphics (); SizeF areaForOneLineOfText = new SizeF (); areaForOneLineOfText.Height = h; areaForOneLineOfText.Width = tb.Width; int charactersFitted; int linesFilled; int separatorCharPos; Font printFont = new Font (tb.Font.Name, tb.Font.Size);

INT POS = 0; do {g.measureString (TB.Text.Substring (POS), PrintFont, AreaForonelineOfText, New StringFormat (), OUT Charactersfitted, Out Linesfilled; // This Method with One Line Cut The Last Word ... . // So, I have to go bak in the string to find a separator // Happyly, MeasureString count separator character in charactersFitted // For example, return "this is the first line" with space at the end // even if there is not room for last space separatorCharPos = charactersFitted; if (charactersFitted POS) &&! System.char.isseparator (TB.Text, POS Separatorcharpos); if (SeparatorCharpos == POS) // No Separator SeparatorCharpos = Charactersfitted; Else SeparatorCharpos ;} lines.add. Substring (POS, SeparatorCharpo S)); POS = SeparatorCharpos;} while ((POS 0)); //print Lines One by one single yitem = y; single extraheight; single extraheightfirstline = 0; / / REMENBER if first line is pull down for (int i = 0; i

IF ((YITEM - Y)> TB.HeiGHT) extendedheight = (YITEM - Y) - TB.Height; if (TextBoxBoxed) {_pen = new pen (color.gray); // Draw A Rectangle Arround List Box. Start Downer if first line pulled down mp.DrawFrame (_Pen, x, y extraHeightFirstLine, tb.Width, tb.Height extendedHeight - extraHeightFirstLine);}}} public void printLabel (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false; // Convert ContentAlignment (property of labels) to HorizontalAlignment (Left, center, Right) HorizontalAlignment ha; string ss = c.Text; ContentAlignment ha2 = ((Label) c) .TextAlign; switch (ha2) {case ContentAlignment.BottomLeft: ha = HorizontalAlignment.Left; break; case ContentAlignment.TopLeft: ha = HorizontalAlignment.Left; break; case ContentAlignment.MiddleLeft: ha = Horizo NTALALIGNMENT.LEFT; BREAK;

case ContentAlignment.BottomCenter: ha = HorizontalAlignment.Center; break; case ContentAlignment.TopCenter: ha = HorizontalAlignment.Center; break; case ContentAlignment.MiddleCenter: ha = HorizontalAlignment.Center; break;

case ContentAlignment.BottomRight: ha = HorizontalAlignment.Right; break; case ContentAlignment.TopRight: ha = HorizontalAlignment.Right; break; case ContentAlignment.MiddleRight: ha = HorizontalAlignment.Right; break; default: ha = HorizontalAlignment.Left; break;} SINGLE H = MP.FONTHEIGHT (new font (c.size)); if (c.Height> h) h = c.Height; ExtendedHeight = mp.beginprintUnit (Y, H); PrintText (c, mp, x, y, false, LabelInBold, false, ha); mp.EndPrintUnit ();} public void PrintCheckBox (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false; Single h = mp.FontHeight (new Font (c.Font.Name, c.Font.Size)); extendedHeight = mp.BeginPrintUnit (y, h);

mp.drawRectangle (_pen, x, y, h, h); if ((CheckBox) c) .Checked) {Single D = 3; mp.drawlines (_pen, x d, y d, x h - D, Y H - D); Pointf [] Points2 = New Pointf [] {new pointf (x h - d, y d), new pointf (x d, y h - d)}; mp. Drawlines (_pen, x h - d, y d, x d, y h - d);} printtext (c, mp, (float) (x (h * 1.4)), (float) y - 2, False, False, False, Horizontalalignment.Left; mp.EndprintUnit ();

public void PrintRadioButton (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false; Single h = mp.FontHeight (new Font (c. Font.name, c.font.size); extendedheight = mp.beginprintUnit (Y, h); mp.drawellipse (_pen, x, y, h, h); if ((radiobutton c) .CHECKED) { SINGLE D = 3; Mp.Fillellipse (_brush, x d, y d, h - d - d, h - d - d);} PRINTTEXT (C, MP, FLOAT) (X (H * 1.4) ), y - 2, false, false, false, HorizontalAlignment.Left); mp.EndPrintUnit ();} public void PrintPanel (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = true; if (typePrint == ParentControlPrinting.AfterChilds) if (((System.Windows.Forms.Panel) c) .BorderStyle = BorderStyle.None) {! IF ((System.windows.Forms.Panel) .Borderstyle == BorderStyle.fixed3d) _pen = new pen (color.silver); //iff height less Than 10, Just Print An Horizontal Line IF ((c). Height <10) && (c.controls.count == 0)) {extendedheight = mp.beginprintUnit (Y, 1); mp.drawlines (_pen, x, y, x c.width, y); MP. Else mp.drawframe (_pen, x, y, c.width, c.Height Extendedheight);}}

public void PrintGroupBox (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = true; Font printFont = new Font (c.Font.Name, c.Font.Size); Single h = mp.FontHeight (printFont); _Pen = new Pen (Color.Silver); switch (typePrint) {case ParentControlPrinting.BeforeChilds: // if height less than 10, just print an horizontal line IF (C.Height <10) && (c.controls.count == 0)) {extendedheight = mp.beginprintunit (Y, 1); mp.drawlines (_pen, x, y, x c.Width, y); mp.endprintunit ();} else {single extraheight = mp.beginprintunit (Y, h); // Space Required for Group CAPTION // PrintText (C, MP, X H, Y, False, True, False , Horizontalalignment.Left; mp.drawstring (C.Text, PrintFont, Brushes.black, x h, y, c.width - H - h, h); mp.EndprintUnit (); extendedheight = extrahei GHT;}; Break; Case ParentControlprinting.Afterchilds: mp.drawframe (_pen, x, y, c.width, c.Height Extendedheight); Break;}}

public void PrintTabControl (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = true; System.Windows.Forms.TabControl tc = (TabControl) c; _Pen = new Pen (Color.Gray); switch (typePrint) {case ParentControlPrinting.BeforeChilds: // Nom du TabPage Single extraHeight = mp.BeginPrintUnit (y, tc.ItemSize.Height); // Space required for tab page Caption system.windows.forms.tabpage tp = tc.selectedTAB; font printfont = new font (tp.font.name, tp.font.size, fontstyle.bold); Single H = mp.FontHeight (PrintFont); if (h > tc.itemsize.height) h = tc.itemsize.height; mp.drawstring (tp.text, printfont, brushes.black, x, y (tc.itemsize.height - h) / 2, tp.width, h ); Mp.drawlines (_pen, x, y tc.Itemsize.height, x tc.width, y tc.itemsize.height); mp.EndprintUnit (); extendedheight = extraheig ht; break; case ParentControlPrinting.AfterChilds: if (TabControlBoxed) mp.DrawFrame (_Pen, x, y, c.Width, c.Height extendedHeight); break;}} public void PrintPictureBox (System.Windows.Forms.Control c , ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false; extendedHeight = mp.BeginPrintUnit (y, c.Height); PictureBox pic = (PictureBox) c; mp.DrawImage (pic.image, x, y, c.width, c.height); mp.endprintunit ();

public void PrintListBox (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false; ListBox lb = (ListBox) c; Single yItem = y ; Single extraHeight; Single extraHeightFirstLine = 0; // remenber if first line is pull down Font printFont = new Font (lb.Font.Name, lb.Font.Size, FontStyle.Bold); int oldPos = lb.SelectedIndex; // Save Position for (int i = 0; i

IF (YITEM - Y)> lb.height) extendedheight = (YITEM - Y) - lb.height;

. _Pen = new Pen (Color.Gray); // Draw a rectangle arround list box Start downer if first line pulled down mp.DrawFrame (_Pen, x, y extraHeightFirstLine, c.Width, c.Height extendedHeight - extraHeightFirstLine) }

public void PrintDataGrid (System.Windows.Forms.Control c, ParentControlPrinting typePrint, MultiPageManagement mp, Single x, Single y, ref Single extendedHeight, out bool ScanForChildControls) {ScanForChildControls = false;

DataGrid dg = (DataGrid) c; Single extraHeight = 0; Single extraHeightHeaderLine = 0; Font printFont = new Font (dg.Font.Name, dg.Font.Size, FontStyle.Bold); Single h = mp.FontHeight (printFont) // Column header DataGridtableEle MyGridtables; if (Dg.Tables.count == 0) {MyGridTableStyle = New DataGridTableStyle (); Dg.TablesTyles.Add (MyGridTableStyle);}

//Header of Each Column Single Xpos = X; SINGLE Y; ExtraHeightHeaderLine = Mp.BeginPrintUnit (YPOS, H 1); // Space Required for Header Text for (int i = 0; i x dg.width) W = x DG.Width - xpos; if (xpos

// Get dataTable displayed in DataGrid // This function only support DataGrid with DataTable as DataSource // This is the only case I code to obtain data in DataGrid DataTable dt = null; if (dg.DataSource is System.Data.DataTable) dt = (DATATABLE) DG.DataSource; Else IF ((DG.DataSource is system.data.dataset) && (DG.DataMember! = Null) {DataSet DS = (Dataset) DG.DataSource; if (ds.tables.contains (DG.DataMember)) DT = DS.TABLES [DG.DataMember];

// Loop on DataRow, with Embed loop on columns if (dt! = Null) {extraheight = mp.beginprintunit (YPOS, H); // Space Required for header text xpos = x; For (int i = 0; i x Dg.Width) w = x Dg.Width - XPOS; IF (XPOS DG.HEIGHT) extendedheight = (YPOS - Y) - DG.HEIGHT;

// public void PrintFlexGrid (System.Windows.Forms.Control c, // ParentControlPrinting typePrint, // MultiPageManagement mp, // Single x, Single y, // ref Single extendedHeight, out bool ScanForChildControls) // {// ScanForChildControls = False; // c1.win.c1flexgrid.c1flexgrid g = (c1.win.c1flexgrid.c1flexgrid) c; // ///print rows and color (row [0]) // Rectanglef r = new Rectanglef () ; // pointf [] Points; // ry = y; // r.Height _pen.width; // r.Height = g.Font.GRAPHIT (EV.GRAPHICS); // // for (INT i = 0; i (x g.width)) // Overtaking // R.Width = (x g.width) - rx; // ev.graphics.drawstring (g.getdatadisplay I, j), g.font, _brush, r, new stringFormat ()); // Rx = r.width; //} // r = r.Height; // if (i == 0) // columns header, add an horizontal line Below // {// r = 1; // Points = new pointf [] {new pointf (x, ry), new pointf (x g.width, ry)}; // ev.graphics.drawlines (_pen, point); // ry = _pen.width; //} //} // // Add a bottom line // points = new pointf [] {new pointf (x, ry), new pointf (x g.width, ry)}; // ev. Graphics.drawlines (_pen, points); // ry = _pen.width; /// // compute extendedHeight // if (ry> y

g.Height) // extendedHeight = rY - (y g.Height); //} // StringFormat _StringFormatFromFlexGridAlign (C1.Win.C1FlexGrid.TextAlignEnum fg) // {// StringFormat sf = new StringFormat (); // String s = fg.toString (). TouPper (); // if (S.Indexof ("Left") == 0) // sf.alignment = system.drawing.StringAlignment.near; //iff (S.Indexof) ("Right") == 0) // sf.alignment = system.drawing.stringAlignment.far; // if (S.Indexof ("center") == 0) // sf.alignment = system.drawing.StringAlignment .Center; // return sf; //} #ENDREGION

#region "Multi page class" public class MultiPageManagement {private bool _PageOverflow; private Single _realPageTop, _realPageHeight, _UsablePageHeight; private Single _realPageLeft, _realPageRight; private Single _CurrentPageTop, _CurrentPageBottom; private int _PageNumber = 0; // private PrintPageEventArgs _Ev; private Graphics _G Private bool _printunit; private bool _printincurrentpage; private single _printUnitpulldown; private bool _PAGENUMBERING; private font _fontforpagenumering; private string _pagenumberingFormat;

Public system.drawing.graphics graphics () {return_g;}

// Constructor public MultiPageManagement (Single pageTop, Single pageBottom, Single pageLeft, Single pageRight, Font formFont, bool pageNumbering, string pageNumberingFormat) {_realPageTop = pageTop; _realPageHeight = pageBottom - pageTop; _realPageLeft = pageLeft; _realPageRight = pageRight; _pageNumbering = pageNumbering; if (_pageNumbering) {_PageNumberingFormat = pageNumberingFormat; _FontForPageNumering = new Font (formFont.Name, (Single) (formFont.Size * 0.8));}} ///

/// Check if items printed below current page // / /// Return True if The IS NEED for Another Page public bool lastpage () {return (! _pageoverflow);

///

/// Change Page. RESET Page Properties /// /// Graphics Object public void newpage (graphics g) {_g = g ; _PageNumber = 1; _UsablePageHeight = _realPageHeight; if (_pageNumbering) {Single fontHeightForPageNumbering = FontHeight (_FontForPageNumering); _UsablePageHeight - = (Single) (fontHeightForPageNumbering * 1.5); // Compute rectangular space for page number RectangleF _recForPageNumbering = new RectangleF () ; _recForPageNumbering.X = _realPageLeft; _recForPageNumbering.Y = _realPageTop _realPageHeight - fontHeightForPageNumbering; _recForPageNumbering.Width = _realPageRight - _realPageLeft; _recForPageNumbering.Height = fontHeightForPageNumbering; // impression StringFormat drawFormat = new StringFormat (); drawFormat.Alignment = StringAlignment.Far; _G.drawstring (String.Format (_PAGENUMBERINGFORMAT, _PAGENUMBER), _FontforpagenuMERing, Brushes.black, _Recforpagen umbering, drawFormat);} _CurrentPageTop = _UsablePageHeight * (_PageNumber - 1); _CurrentPageBottom = _CurrentPageTop _UsablePageHeight; _PageOverflow = false;} public void ResetPage () {_PageNumber = 0;}

public Single BeginPrintUnit (Single y, Single neededHeight) {if (neededHeight> _UsablePageHeight) throw new Exception ( "Needed height can not exceed 1 page Page height =." _UsablePageHeight); _PrintUnit = true;

// Verify if unit goes accross a page break // if it's the case, calculate vertical push down height to place the // top of unit just below page break Single pageBreakPos; Single printingPos = y; for (pageBreakPos = _UsablePageHeight; pageBreakPos < (y neededHeight); pageBreakPos = _UsablePageHeight) if ((y <= pageBreakPos) && ((y neededHeight - 1)> pageBreakPos)) // accross printingPos = pageBreakPos; _PrintUnitPullDown = printingPos - y;

// test if unit is in current page else if another page is needed _PrintInCurrentPage = false; if (printingPos neededHeight - 1> _CurrentPageBottom) _PageOverflow = true; else if (printingPos> = _CurrentPageTop) _PrintInCurrentPage = true;

Return_printUnitpulldown;}

Private Single_ConvertTopage (Single Y) {Single Newy = Y - _CurrentPagetop _RealPagetop; if (_PrintUnit) Return Newy = _PrintUnitpullDown; Return Newy;}

Public void endprintunit () {_printUnit = false;

Private Bool PrintunitisincurrentPage () {if (! _printUnit) Throw new Exception ("Must Be in a print unit to print"); return _printincurrentpage;}

Public Single Fontheight (font font) {return font.getheight (_g);

public void DrawLines (Pen pen, Single x1, Single y1, Single x2, Single y2) {if (PrintUnitIsInCurrentPage ()) {Single y1page = _ConvertToPage (y1); Single y2page = _ConvertToPage (y2); PointF [] points = new PointF [2]; Points [0] .x = x1; Points [0]. Y = Y1Page; Points [1] .x = x2; Points [1] .y = y2page; _g.drawlines (Pen, points); Public Void DrawString (STRING S, FONT Printfont, Brush Brush, Single X, Single Y, Single W, Single H) {DrawString (S, PrintFont, Brush, X, Y, W, H, New StringFormat ());}

public void DrawString (string s, Font printFont, Brush brush, Single x, Single y, Single w, Single h, StringFormat sf) {if (PrintUnitIsInCurrentPage ()) {Single yPage = _ConvertToPage (y); RectangleF r = new RectangleF ( ); Rx = x; ry = ypage; r.Width = W; r.Height = h; _g.drawstring (s, printfont, brush, r, sf);}}

Public void DrawRectangle (Pen Pen, Single X, Single Y, Single W, Single H) {if (PrintunitisincurrentPage ()) {Single Ypage = _CONVERTTTOPAGE (Y); _G.drawRectangle (Pen, X, Ypage, W, H); }

Public void Drawellipse (Pen Pen, Single X, Single Y, Single W, Single H) {IF (PrintunitisincurrentPage ()) {Single Ypage = _Converttopage (Y); _G.Drawellipse (Pen, X, Ypage, W, H); }

Public Void Fillellipse (Brush Brush, Single X, Single Y, Single W, Single H) {if (PrintunitisincurrentPage ()) {Single Ypage = _ConvertTopage (Y); _G.FLLLLIPSE (Brush, x, ypage, w, h); }

Public Void DrawImage (Image Image, Single X, Single Y, Single W, Single H) {if (PrintunitisincurrentPage ()) {Single Ypage = _ConVerttopage (Y); _G.drawImage (Image, X, Ypage, W, H); }} PUBLIC VOID DRAWFRAME (Pen Pen, Single X, Single Y, Single W, Single H) {PointF [] Points = New Pointf [2]; SINGLE YTOP = _CURRENTPAGETOP; SINGLE YBOTTOM = _CURRENTPAGEBOTTOM

IF (y h <= _currentpagetop) // bottom of frame above capital page return; if (y> = _currentpagebottom) // Top of frame belde current page {_pageoverflow = true; return;

// Assign X Coordinate for Horizontal Lines Points [0] .x = x; Points [1] .x = x w;

// Draw Top Line IF (Y> = _CurrentPagetop) // TOP IN CURRENT PAGE {YTOP = Y; Points [0] .y = _ConVerttopage (Ytop); Points [1] .y = _ConVerttopage (Ytop); _g.drawlines (Pen, Points);

// DRAW BOTTOM LINE IF (Y H <= _CurrentPageBottom) // Bottom IN CURRENT Page {ybottom = y h; points [0] .y = _converttopage (ybottom); Points [1] .y = _ConvertTopage (Ybottom) ; _G.drawlines (Pen, Points);} else _pageoverflow = true;

// Assign Y Coordinate for Vertical Lines Points [0] .y = _CONVERTTOPAGE (YTOP); Points [1] .y = _CONVERTTOPAGE (YBOTTOM);

// Draw Left Line Points [0] .x = x; Points [1] .x = x; _g.drawlines (Pen, Points);

// Draw Right Line Points [0] .x = x w; Points [1] .x = x w; _G.Drawlines (Pen, Points);}} #ENDREGON}}

转载请注明原文地址:https://www.9cbs.com/read-92417.html

New Post(0)