SoFunction
Updated on 2025-03-06

Ideas and code for C# to implement printing and printing preview functions

Printing documents in Windows applications is a very important function, and it has been a very complicated task in the past. The printing functions of Microsoft .Net Framework are provided in the form of components, providing great convenience for programmers, but the use of these components is still very complicated, so it is necessary to explain.
Printing operations usually include the following four functions:
1 Print settings Set some parameters of the printer, such as changing the printer driver, etc.;
2 Page settings Set page size paper type, etc.
3 Print preview Similar to Print preview in word
4 Print

The core of implementing the printing function is that the PrintDocument class belongs to the 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
Stores the printer's settings information. This property does not require programmer settings because it is obtained by the printing dialog box.
2. PrintCountroller attribute
Control the printing process
3. DefaultPageSettings property
It also does not require programmer settings to store page settings, print paper size and direction, because it is obtained by the page settings dialog box.
4. DocumentName property
Specify the document name, which appears in the printer status window

1. BeginPrint Event
Send before printing
2. PrintPage Event
Each page printed is issued, and the event accepts a PrintPageEventArgs parameter. This parameter encapsulates the printing-related information.

PrintPageEventArgs parameter has many important properties
1 Cancel Cancel Print
2 Graphics page drawing objects
3 HasMorePages Are there any pages to print?


Print method: This method has no parameters. Calling it will start printing according to the current settings.
If you implement the printing function, first construct the PrintDocument object and add the print event.

Copy the codeThe code is as follows:

PrintDocument printDocument;
 private void InitializeComponent()
 {
 ...
// The printDocument object here can be implemented by dragging and dropping the PrintDocument control onto the form. Note that you want to set the PrintPage event of the control.
 printDocument=new PrintDocument();
  += new PrintPageEventHandler (this.printDocument_PrintPage);
 ...
 }

Implement the printing event function
Printing and drawing are similar to drawing. Both Graphics methods are called to draw. The difference is that one is on the monitor and the other is on the printing paper and printing requires some complex calculations.
Such as line breaks, page paging, etc.

Copy the codeThe code is as follows:

 private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
 {
Graphics g = ; //Get the drawing object
float linesPerPage = 0; //The line number of the page
float yPosition = 0; //Draw the vertical position of the string
int count = 0; //Line Counter
float leftMargin = ; //Left margin
float topMargin = ; //top margin
string line = null; line string
Font printFont = ; //The current printed font
SolidBrush myBrush = new SolidBrush();//Brush
linesPerPage = / (g);//Number of lines that can be printed per page
//Print a page line by line
 while(count < linesPerPage && ((line=()) != null))
 {
yPosition = topMargin + (count * (g));
(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
 }
// Note: Before using this code, you must define the lineReader object in the class of the form:
// StringReader lineReader = null;
//If this page is printed and the line is not empty, it means that there are still pages that have not been completed, which will trigger the next printing event. In the next print, lineReader will
//Automatically read content that was not printed last time, because lineReader is a member of the class outside of this printing method, and it can record the current read location
 if(line != null)
  = true;
 else
{
  = false;
// Reinitialize the lineReader object, otherwise it will be blank pages when printing using the print button in the print preview.
lineReader = new StringReader(); // textBox is the content of the text box you want to print
}
}

Print settings, construct the print dialog box. Assign the Document property set in the dialog box to printDocument, which will automatically save the user's settings to printDocument.
PrinterSettings property
Copy the codeThe code is as follows:

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

Page settings and print preview are the same as print settings. Both the same construction dialog box saves the user's settings in the dialog box into the properties of the corresponding class.

Copy the codeThe code is as follows:

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

Print preview

Copy the codeThe code is as follows:

protected void FileMenuItem_PrintView_Click(object sender,EventArgs e)
{
   PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
   = printDocument;
   lineReader = new StringReader();
   try
   {
        ();
   }
   catch(Exception excep)
   {
(, "Print error", , );
   }
}

You can directly call the Print() method of printDocument because the user may have to change the printing settings before printing.
Here again the Print Settings dialog box is displayed

Copy the codeThe code is as follows:

 protected void FileMenuItem_Print_Click(object sender,EventArgs e)
  {
   PrintDialog printDialog = new PrintDialog();
   = printDocument;
   lineReader = new StringReader();
   if (() == )
   {
       try
       {
         ();
       }
       catch(Exception excep)
       {
(, "Print error", , );
              (printDocument,new PrintEventArgs());
       }
    }
  }

The printing process is
1 Construct the PrintDocument object when the application form is initialized, and add the PrintPage method of the printDocument
2 Implement PrintPage method
3 Call the Print method of printDocument in the user's click event to implement the printing function
PrintDialog PrintPreviewDialog PageSetupDialog Setting and viewing printing effects These methods are usually triggered by the click of the menu.