Download the source code for the encapsulation of winfrom print table strings

Source: Internet
Author: User

Therefore, it is not convenient to use the application layer. A recent project encapsulates a class that calls the default printer. Although there are several small bugs, the requirements have been met for the moment. It's not enough to upgrade later.

1. About the top and bottom margins and the height and width of the paper. In the past, all these are written to the code. Since the default printer is called, the printer model is naturally different. So I put these configurations in app. config. However, I am afraid that loading config for each print will affect the efficiency. Therefore, a PrintPaper class is designed. All the attributes are static. There is also a static constructor. In this way, config is loaded only once when the program starts running. Then, it is read directly from the memory.

PrintPaper class

Copy codeThe Code is as follows:/* CreateBy: Bonker, Date: 20121115 */
/// <Summary>
/// Read the paper size from the configuration file, distance from the border
/// </Summary>
Public class PrintPaper
{
/// <Summary>
/// Distance from the upper boundary
/// </Summary>
Public static int MarginTop {set; get ;}
/// <Summary>
/// Distance from the left boundary
/// </Summary>
Public static int MarginLeft {set; get ;}
/// <Summary>
/// Distance from the right boundary
/// </Summary>
Public static int MarginRight {set; get ;}
/// <Summary>
/// Distance from the bottom boundary
/// </Summary>
Public static int MarginBottom {set; get ;}
/// <Summary>
/// Width of the paper
/// </Summary>
Public static int Width {set; get ;}
/// <Summary>
/// The height of the paper
/// </Summary>
Public static int Height {set; get ;}
/// <Summary>
/// Exception
/// </Summary>
Public static string Error {set; get ;}

// For static attributes and constructor methods. When this class is used for the first time, the static attribute is initialized and then the static class is called.
// Therefore, the configuration file is loaded only once and will be read from the memory for future calls.
// The advantage of writing in this method: one-time loading, no longer loading in the future, and the speed is fast. Disadvantage: The config configuration is changed while the program is running. Then you need to run the program again. Configuration is loaded to take effect.
Static PrintPaper ()
{
// Assign a null value to the exception first. If the exception is not empty. Indicates that the configuration data is incorrect or the program is abnormal.
Error = null;
String marginTop = BonkerConfig. GetConfig ("marginTop ");
String marginBottom = BonkerConfig. GetConfig ("marginBottom ");
String marginLeft = BonkerConfig. GetConfig ("marginLeft ");
String marginRight = BonkerConfig. GetConfig ("marginRight ");
// The value of margin can be negative, but the width can only be positive,
// MarginTop, which defaults to 0. If margin is not empty, the value is copied to margin.
Try
{
If (! String. IsNullOrWhiteSpace (marginTop ))
{
MarginTop = int. Parse (marginTop );
}
If (! String. IsNullOrWhiteSpace (marginTop ))
{
MarginBottom = int. Parse (marginBottom );
}
If (! String. IsNullOrWhiteSpace (marginTop ))
{
MarginLeft = int. Parse (marginLeft );
}
If (! String. IsNullOrWhiteSpace (marginTop ))
{
MarginRight = int. Parse (marginRight );
}
}
Catch (Exception ex)
{
// If any exception persists
Error = ex. Message;
Return;
}
// Determine the paper width
Try
{
// If the paperWidth configuration is not positive, the default value is used when the PrintCore class is printed.
String width = BonkerConfig. GetConfig ("paperWidth ");
String height = BonkerConfig. GetConfig ("paperWidth ");
If (! String. IsNullOrWhiteSpace (width ))
{
Width = int. Parse (width );
}
If (! String. IsNullOrWhiteSpace (height ))
{
Height = int. Parse (width );
}
}
Catch (Exception ex)
{
// If any exception persists
Error = ex. Message;
Return;
}
}
}

App. config contentCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>

<Deleetask>
<! -- ****************************** Connection string settings ****** ***************************** -->
<Add key = "DBConnectionStr" value = ""/>
<! -- ********************************* Print border settings **** ***************************** -->
<! -- The distance between the printing paper and the four boundaries. If it is null, the default value is 0, which can be a negative value. -->
<! -- Distance from the upper boundary -->
<Add key = "marginTop" value = ""/>
<! -- Distance from the upper boundary -->
<Add key = "marginBottom" value = ""/>
<! -- Distance from the upper boundary -->
<Add key = "marginLeft" value = ""/>
<! -- Distance from the upper boundary -->
<Add key = "marginRight" value = ""/>
<! -- *********************************** Print paper size setting **** ***************************** -->
<! -- Print the size of the paper. If it is null, the default value is used. The value cannot be negative. -->
<! -- Width of the paper -->
<Add key = "paperWidth" value = ""/>
<! -- Height of the paper -->
<Add key = "paperHeight" value = ""/>
<! --*************************************** **************************************** -->
</AppSettings>
</Configuration>

2. Print the table and read a lot of msdn code. It looks a little rough. The print table prints a rectangle at a point without changing the X and Y coordinates. So there is a table. In theory, the four borders of such a table are a little small. The small lattice inside is a little rough. But after printing it out, there is basically no difference.

A printed table is the maximum text width in an adaptive table. However, if the table does have very few columns, the maximum width of the column is small. After printing the entire table, there is no page width. It will automatically pull the width of each column.

PrintCore

Copy codeThe Code is as follows:/* CreateBy: Bonker, Date: 20121115 */
/// <Summary>
/// Print class, responsible for printing tables and common rows.
/// </Summary>
Public class PrintCore
{
/// <Summary>
/// Print the basic encapsulation class PrintDocument
/// </Summary>
Public PrintDocument printDoc {set; get ;}
/// <Summary>
/// The x coordinate currently printed
/// </Summary>
Public float currentX {set; get ;}
/// <Summary>
/// Y coordinate currently printed
/// </Summary>
Public float currentY {set; get ;}
/// <Summary>
/// Default print font
/// </Summary>
Public Font defaultFont {set; get ;}
/// <Summary>
/// Specifies the paint brush to be printed. It is black and bold by default.
/// </Summary>
Public Brush defaultBrush {set; get ;}
/// <Summary>
/// Whether to center the print. The default value is false.
/// </Summary>
Public bool isCenter {set; get ;}
/// <Summary>
/// Error
/// </Summary>
Public string Error {set; get ;}

Private Graphics graphic {set; get ;}
/// Constructor
/// </Summary>
/// <Param name = "_ printDoc"> Print the basic class </param>
/// <Param name = "_ currentX"> Print the start x coordinate. The default value is 0. </param>
/// <Param name = "_ currentY"> Print the start y coordinate. The default value is 0. </param>
Public PrintCore (PrintDocument _ printDoc, Graphics _ graphics, Font _ defaultFont, float _ currentX = 0, float _ currentY = 0)
{
This. printDoc = _ printDoc;
This. currentX = _ currentX;
This. currentY = _ currentY;
This. defaultFont = _ defaultFont;
This. graphic = _ graphics;
This. defaultBrush = new SolidBrush (Color. Black); // Black by default
This. isCenter = false;
// Read the configuration file
PrintDocConfig (_ printDoc );
Error = PrintPaper. Error;
}
Private void printDocConfig (PrintDocument _ printDoc)
{
_ PrintDoc. DefaultPageSettings. Margins = new Margins (PrintPaper. MarginLeft, PrintPaper. MarginRight, PrintPaper. MarginTop, PrintPaper. MarginBottom );
// This parameter is configured only when the width and height of the paper configuration are greater than 0. Otherwise ignore
If (PrintPaper. Width> 0 & PrintPaper. Height> 0)
{
_ PrintDoc. DefaultPageSettings. PaperSize = new PaperSize ("", PrintPaper. Width, PrintPaper. Height );
}

}
/// <Summary>
/// Print the string. The system can always judge the line feed printing.
/// </Summary>
/// <Param name = "prnStr"> printed string </param>
/// <Param name = "isPrintLine"> specifies whether to wrap the line after printing. The default value is true. </param>
Public void printString (string prnStr, bool isPrintLine = true)
{
// Print the string and wrap it automatically based on the string length, paper width, and height
SizeF measure = graphic. MeasureString (prnStr, defaultFont );
// If the x coordinate is not 0, or the width of the printed line is greater than the width of the paper, it is useless to print the data in the center. Print not considered
If (! IsCenter | currentX! = 0 | printDoc. DefaultPageSettings. PaperSize. Width <measure. Width)
{
// Calculate the number of rows required to print so many words
Int rows = (int) Math. Ceiling (measure. Width/(printDoc. DefaultPageSettings. PaperSize. Width-currentX ));
// Calculate the rectangle to be printed Based on the row
Graphic. drawString (prnStr, defaultFont, defabrush brush, new Rectangle (int) currentX, (int) currentY, (int) Math. ceiling (printDoc. defaultPageSettings. paperSize. width-currentX), (int) Math. ceiling (measure. height * rows ))));
If (isPrintLine) // if the line feed
{
CurrentY = currentY + measure. Height * rows;
CurrentX = 0;
}
Else
{
CurrentY = currentY + measure. Height * (rows-1 );
CurrentX = (measure. Width % (printDoc. DefaultPageSettings. PaperSize. Width-currentX) + currentX;
}
}
Else
{
// Print a row in the center
// Calculate the reserved width before printing
Float blank = (printDoc. DefaultPageSettings. PaperSize. Width-measure. Width)/2.0f;
CurrentX = currentX + blank;
Graphic. DrawString (prnStr, defaultFont, defabrush brush, currentX, currentY );
If (isPrintLine) // if the line feed
{
CurrentX = 0;
CurrentY = currentY + measure. Height;
}
Else
{
CurrentX = currentX + measure. Width;
}
}
}
/// <Summary>
/// Print the table and adapt to the width of no column
/// </Summary>
/// <Param name = "prnDgv"> </param>
/// <Param name = "isPrintLine"> </param>
Public void printDataGridView (DataGridView prnDgv, Font titleFont, Brush titleBrush, Color titleBackGroup, bool isPrintLine = true)
{
If (prnDgv = null)
{
Return;
}
PrnDgv. AllowUserToAddRows = false;
// Record the width of each column
Int [] columnWidths = new int [prnDgv. ColumnCount];
// ***************** Obtain the maximum width of each column ************** *********
// Calculate the header width first
For (int I = 0; I <prnDgv. ColumnCount; I ++)
{
String celValue = prnDgv. Columns [I]. HeaderText;
SizeF measure = graphic. MeasureString (celValue, titleFont );
ColumnWidths [I] = (int) Math. Ceiling (measure. Width); // put the Width occupied by the print header in columnWidths.
}
// Maximum width of data printing in the calculation table
For (int I = 0; I <prnDgv. Rows. Count; I ++)
{
For (int j = 0; j <prnDgv. ColumnCount; j ++)
{
String celValue = prnDgv [j, I]. Value. ToString ();
SizeF measure = graphic. MeasureString (celValue, defaultFont );
If (columnWidths [j] <measure. Width) // if the Width is smaller than the print Width, assign the long print Width to the column Width.
{
ColumnWidths [j] = (int) Math. Ceiling (measure. Width );
}
}
}

// If the width of the table is smaller than the width of the paper, the width of the table without columns is increased.
Int allColumsWidth = 0;
For (int I = 0; I <prnDgv. ColumnCount; I ++)
{
AllColumsWidth + = columnWidths [I]; // put the width occupied by the print header in columnWidths.
}
If (allColumsWidth + prnDgv. ColumnCount <PrintPaper. Width)
{
Int columnAddWidth = (PrintPaper. Width-allColumsWidth-prnDgv. ColumnCount)/prnDgv. ColumnCount;
For (int I = 0; I <prnDgv. ColumnCount; I ++)
{
ColumnWidths [I] + = columnAddWidth;
}
}
//************************************** ***********************

CurrentX = 0;
Int titleHeight = (int) Math. Ceiling (graphic. MeasureString ("1e {(Khan", titleFont). Height );
// Print the header
For (int I = 0; I <prnDgv. ColumnCount; I ++)
{
String celValue = prnDgv. Columns [I]. HeaderText;
// Print the background
Graphic. FillRectangle (new SolidBrush (titleBackGroup), new Rectangle (int) currentX, (int) currentY, columnWidths [I], titleHeight ));
// Print the content
Graphic. DrawString (celValue, titleFont, titleBrush, currentX, currentY );
// Print the table border
Graphic. DrawRectangle (new Pen (titleBrush), new Rectangle (int) currentX, (int) currentY, columnWidths [I], titleHeight ));
CurrentX = currentX + columnWidths [I];
}
CurrentX = 0;
CurrentY = currentY + titleHeight;

Int contentHeight = (int) Math. Ceiling (graphic. MeasureString ("1e {(Khan", defaultFont). Height );
// Print the content
For (int I = 0; I <prnDgv. Rows. Count; I ++)
{
For (int j = 0; j <prnDgv. ColumnCount; j ++)
{
String celValue = prnDgv [j, I]. Value. ToString (); // print the content
Graphic. DrawString (celValue, defaultFont, defabrush brush, currentX, currentY); // print the table border
Graphic. DrawRectangle (new Pen (defaultBrush), new Rectangle (int) currentX, (int) currentY, columnWidths [j], contentHeight ));
CurrentX = currentX + columnWidths [j];
}
CurrentX = 0;
CurrentY = currentY + contentHeight;
}
}
}

Call sample code

Copy codeThe Code is as follows: private void printdocument#printpage (object sender, PrintPageEventArgs e)
{
PrintCore print = new PrintCore (printDocument1, e. Graphics, new Font ("", 14 ));
If (print. Error! = Null)
{
E. Cancel = true;
MessageBox. Show (print. Error );
Return;
}
Print. isCenter = true;
Print. defaultFont = new Font ("", 16 );
Print. printString ("credits are fixed to Christmas loss after weight loss", true );
Print. isCenter = false;
Print. defaultFont = new Font ("", 14 );
Print. printString christmas is dead, and the chain stores are losing weight ");

Print. printDataGridView (dataGridView1, new Font ("", 18), Brushes. Black, DefaultBackColor );
}

Conclusion: There are two small problems to solve in the above printing. One is about paging. The other is that when the table width is too long and exceeds the page width, no line breaks are processed.

Additional source code winfrom_mrdyj_jb51net

Author: Bonker

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.