C printing and printing preview function of the train of thought and code

  • 2020-05-27 07:04:21
  • OfStack

The document printing is a very important function in the windows application. In the past, it was a very complicated job. The printing function of Microsoft.Net Framework is provided in the form of components, which provides great convenience for programmers.
The printing operation usually includes the following four functions:
Set some parameters of the printer, such as changing the printer driver, etc.
Set page size, paper type, etc
3 print preview is similar to print preview in word
4 the print

The core of the printing capability is the PrintDocument class, which belongs to the System.Drawing.Printing namespace. This class encapsulates the current printing Settings page Settings and all printing-related events and methods
This class includes the following properties, events, and methods
1. PrinterSettings property
This property does not need to be set by the programmer because it is captured by the print dialog box.
2. PrintCountroller properties
Control the printing process
3. DefaultPageSettings properties
To store the page setting information, printing paper size direction, etc., also does not need the programmer to set, because it is obtained by the page setting dialog box.
4. DocumentName property
Specify the document name that appears in the printer status window

1. BeginPrint event
Send before printing
2. PrintPage events
Each page printed is emitted, and the event accepts an PrintPageEventArgs parameter that encapsulates the printing-related information

The PrintPageEventArgs parameter has many important properties
1 Cancel unprint
2 drawing objects for Graphics page
3. Does HasMorePages have any pages to print


Print method: this method is called with no arguments and it will start printing with the current Settings.
If the printing function is implemented, first construct the PrintDocument object to add the printing event


PrintDocument printDocument;
 private void InitializeComponent()
 {
 ...
//  Here, printDocument Objects can be passed by the PrintDocument Control is implemented by dragging and dropping the control onto a form, noting that you want to set the control's PrintPage Events. 
 printDocument=new PrintDocument();
 printDocument.PrintPage += new PrintPageEventHandler (this.printDocument_PrintPage);
 ...
 }

Implement the print event function
Printing and drawing are similar to calling the methods of Graphics class to draw a picture. The difference is that 1 is on the monitor and 1 is on the printer paper and printing takes some complicated calculations
Such as line feed, pagination, etc.


 private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
 {
 Graphics g = e.Graphics; // Get the drawing object 
 float linesPerPage = 0; // The line number of the page 
 float yPosition = 0; // Draws the vertical position of a string 
 int count = 0; // Line counter 
 float leftMargin = e.MarginBounds.Left; // The left margin 
 float topMargin = e.MarginBounds.Top; // From the above 
 string line = null;  Line of string 
 Font printFont = this.textBox.Font; // Current print font 
 SolidBrush myBrush = new SolidBrush(Color.Black);// brush 
 linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g);// Number of printable lines per page 
// Print in a circular fashion, line by line 1 page 
 while(count < linesPerPage && ((line=lineReader.ReadLine()) != null))
 {
yPosition = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
 }
//  Note: before using this code, define it in the form's class lineReader Object: 
// StringReader lineReader = null;
 // If this page is finished printing line Don't empty , Note that there are unfinished pages , This is going to trigger 1 Second print event. The next 1 Secondary printing lineReader will 
 // Automatically reads content that was not printed last time because lineReader Is a member of a class outside the print method that records the current read location 
 if(line != null)
 e.HasMorePages = true;
 else
{
 e.HasMorePages = false;
 //  reinitialization lineReader Object, otherwise printed out as a blank page using the print button in the print preview 
 lineReader = new StringReader(textBox.Text); // textBox Is the content of the text box that you want to print 
}
}

Print Settings, construct the print dialog and assign the Document property set in the dialog to printDocument so that the user's Settings are automatically saved to printDocument
Of the PrinterSettings property

protected  void FileMenuItem_PrintSet_Click(object sender,EventArgs e)
{
    PrintDialog printDialog = new PrintDialog();
    printDialog.Document = printDocument;
    printDialog.ShowDialog();
}

Page Settings and print previews work in the same way as print Settings by building a dialog box that saves the user's Settings in the dialog box to the properties of the corresponding class


protected  void FileMenuItem_PageSet_Click(object sender,EventArgs e)
{
    PageSetupDialog pageSetupDialog = new PageSetupDialog();
    pageSetupDialog.Document = printDocument;
    pageSetupDialog.ShowDialog();
}

Print preview


protected void FileMenuItem_PrintView_Click(object sender,EventArgs e)
{
   PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
   printPreviewDialog.Document = printDocument;
   lineReader = new StringReader(textBox.Text);
   try
   {
        printPreviewDialog.ShowDialog();
   }
   catch(Exception excep)
   {
        MessageBox.Show(excep.Message, " Printing error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
}

Print and you can call printDocument's Print() method directly because the user might have to change the print Settings before printing
Display the print Settings dialog again here


 protected void FileMenuItem_Print_Click(object sender,EventArgs e)
  {
   PrintDialog printDialog = new PrintDialog();
   printDialog.Document = printDocument;
   lineReader = new StringReader(textBox.Text);
   if (printDialog.ShowDialog() == DialogResult.OK)
   {
       try
       {
         printDocument.Print();
       }
       catch(Exception excep)
       {
              MessageBox.Show(excep.Message, " Printing error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
              printDocument.PrintController.OnEndPrint(printDocument,new PrintEventArgs());
       }
    }
  }

Summary of the printing process is
Construct the PrintDocument object when the application form initializes, adding the PrintPage method of printDocument
Implement the PrintPage method
3. Call printDocument's Print method in the user's click event to achieve the printing function
In between, you might want to use PrintDialog PrintPreviewDialog PageSetupDialog to set up and view the print effect. These methods are usually triggered by a menu click.


Related articles: