C#. Practice. Create a document to print. Controls PrintDocument, PageSetupDialog, PrintDialog, PrintPreviewDialog




Create a document to print. Controls PrintDocument, PageSetupDialog, PrintDialog, PrintPreviewDialog

This topic demonstrates document printing tools for programs written using the Windows Forms template in C# programming language.


Contents


Поиск на других ресурсах:

Theoretical information

To ensure printing, the .NET Framework implements special classes, the base of which are:

  • PrintDocument – represents a class whose object sends data to the printer;
  • PageSetupDialog – presents a dialog box that allows the user to change the page settings for printing (internal margins, print orientation, etc.);
  • PrintDialog – presents a dialog box that allows the user to select a printer and other printer settings, such as the number of copies, page orientation, etc.;
  • PrintPreviewDialog – presents a dialog box that shows the user the previous viewing of the document as it will be displayed when printing.

 

Task

Develop an application such as Windows Forms that prints the information contained in a RichTextBox control. The application should contain the commands:

  • printing a document;
  • document preview;
  • setup pages in the document.

In the program, use the PrintDocument, PageSetupDialog, PrintDialog, PrintPreviewDialog controls.

 

Instructions

1. Create project

After creating the project, an empty form is created. The form class is called Form1.

2. Form development. Placement of controls on the form

Develop the main form of the program as shown in Figure 1.

C#. Windows Forms. Application of printing a document. Main form

Figure 1. Main form

The following controls must be placed on the form:

  • the control of Label type. An instance with the name label1 is created;
  • three controls of Button type. Instances with the names button1, button2, button3 is created;
  • the control of RichTextBox type. An instance with the name richTextBox1 is created;
  • the control of PrintDocument type. An instance with the name printDocument1 is created. This control represents the document to be printed;
  • the control of PageSetupDialog. An instance with the name pageSetupDialog1 is created;
  • the control of PrintDialog type. An instance with the name printDialog1 is created;
  • the control of PrintPreviewDialog type. An instance with the name printPreviewDialog1 is created.

The placement of the PageSetupDialog, PrintDialog, PrintDocument, PrintPreviewDialog controls is shown in Figure 2.

C#. Windows Forms. Controls PageSetupDialog, PrintDialog, PrintDocument, PrintPreviewDialog

Figure 2. Controls PageSetupDialog, PrintDialog, PrintDocument, PrintPreviewDialog

 

3. Customize basic visual controls on the form

At this point, you need to configure the properties of the form controls as follows:

  • in the control Form1 property Text = “Print document”;
  • in label1 property Text = “Specified text:” (label1.Text = “Specified text:”);
  • button1.Text = “Page Setup”;
  • button2.Text = “Print”;
  • button3.Text = “Print Preview”.

After configuration, the form will look like as shown in Figure 1.

 

4. Configuring controls PageSetupDialog, PrintDialog, PrintPreviewDialog, PrintDocument

The next step is to link the pageSetupDialog1, printDialog1, printPreviewDialog1 controls to the printDocument1 document. To do this, use the Document property. The settings are as follows:

  • pageSetupDialog1.Document = printDocument1 (рисунок 3);
  • printDialog1.Document = printDocument1;
  • printPreviewDialog1.Document = printDocument1;
  • printDialog1.AllowSomePages = True. This property enables or disables the page setup button in the print window.

C#. Windows Forms. Control pageSetupDialog1. Property Document = printDocument1

Figure 3. Control pageSetupDialog1. Property Document = printDocument1

 



5. Add an additional variables to the form class

According to the task, you need to print the text that is typed in the richTextBox1 control. When printing, you need to save the line number in richTextBox1, which is currently being printed. To ensure this, an additional variable counter is introduced into the form class Form1.

Also, is introduced the curPage variable, which defines the page that is currently being printed. The text fragment of the class of form Form1 is as follows

...

public partial class Form1 : Form
{
  // Number of rows displayed:
  // 0 <= counter <= richTextBox1.Lines.Length
  int counter = 0; // end-to-end row number in an array of strings that are output
  int curPage; // current page

  ...

}

...

 

6. Programming event handlers
6.1. Main events provide printing

If a command to print to a printer or to preview a document is called, then event handlers of the PrintDocument class come into operation. Using events of the PrintDocument class, you can control the printing of a document.

The list of possible events of the PrintDocument class is as follows:

  • BeginPrint – this event occurs just before the printing of the document. In the event handler it is advisable to enter the initialization code of the internal variables that control the printing of the document;
  • PrintPage – occurs once every page is printed. For example, if 5 pages are printed, then this event will occur 5 times;
  • EndPrint – occurs after printing a document;
  • QueryPageSetting – occurs before each page has to be printed. Intercepting this event is useful in cases when you need to change the settings of a specific printable page.

 

6.2. Programming the BeginPrint event handler for the printDocument1 component

The BeginPrint event of the printDocument1 control is programmed first. To get the handler for this event, you need to select the printDocument1 control and select the BeginPrint event (double-click) in the list of events.

In our case, in the BeginPrint event handler, we need to implement the initialization of the counter and curPage variables

// Print start
private void printDocument1_BeginPrint(object sender,
System.Drawing.Printing.PrintEventArgs e)
{
  // Before printing, set counter variables to initial values
  counter = 0;
  curPage = 1;
}

 

6.3. Programming the PrintPage event handler for the printDocument1 component

The main program code that outputs to the printer is implemented in the PrintPage event handler. The handler text is as follows:

// PrintPage event handler - here you need to program printing
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
  // Create a font myFont
  Font myFont = new Font("Arial", 14, FontStyle.Regular, GraphicsUnit.Pixel);

  string curLine; // current output string

  // Padding inside page
  float leftMargin = e.MarginBounds.Left; // padding on the left in the document
  float topMargin = e.MarginBounds.Top; // padding on top of the document
  float yPos = 0; // current position Y to the output line

  int nPages; // number of pages
  int nLines; // the maximum possible number of lines per page
  int i; // current line number to display on page

  // Calculate the maximum number of lines per page
  nLines = (int)(e.MarginBounds.Height / myFont.GetHeight(e.Graphics));

  // Calculate the number of pages to print.
  nPages = (richTextBox1.Lines.Length - 1) / nLines + 1;

  // Printing cycle of one page
  i = 0;
  while ((i < nLines) && (counter < richTextBox1.Lines.Length))
  {
    // Get line for output from richTextBox1
    curLine = richTextBox1.Lines[counter];

    // Calculate the current position on the Y axis
    yPos = topMargin + i * myFont.GetHeight(e.Graphics);

    // Print string to document
    e.Graphics.DrawString(curLine, myFont, Brushes.Blue,
      leftMargin, yPos, new StringFormat());

    counter++;
    i++;
  }

  // If all the text does not fit on 1 page,
  // then you need to add an additional page for printing
  e.HasMorePages = false;

  if (curPage < nPages)
  {
    curPage++;
    e.HasMorePages = true;
  }
}

Explain some code fragments in the handler.
Based on the size of the specified myFont font and the height of the e.MarginBounds.Height page, the number of nLines lines a single page can hold is determined. Pages may be several. The current page number is defined in the internal variable curPage, which was described in section 5. Based on the number of lines on the nLines page and the total number of lines displayed richTextBox1.Lines.Length, the total number of print pages nPages is calculated.

Two counters appear in the while loop: page counter i and the counter of the end-to-end row (see section 5). As soon as one of the counters takes its maximum value, the loop is exited.
Also, in the loop in the variable yPos the y coordinate of the text output is formed by the formula. A line of text is output using the method

// Print string to document
e.Graphics.DrawString(curLine, myFont, Brushes.Blue,
    leftMargin, yPos, new StringFormat());

where

  • e – an instance of type PrintPageEventArgs that provides the necessary data for the PrintPage event. Using this data, you can control the printing of the document;
  • e.Graphics – a class that is intended for drawing on the page. In addition to text, you can display any graphic primitives;
  • e.Graphics.DrawString() – a method that outputs a specific line (curLine) at a specific position (leftMargin, yPos). The string is displayed in the font myFont and the color Brushes.Blue.

The e.Graphics.DrawString() method sets an optional output format of type StringFormat by calling

new StringFormat()

After the while loop, it determines whether to generate the next page

...

// first accept that the next page is not generated
e.HasMorePages = false;

if (curPage < nPages) // If this is not the last page
{
  curPage++;
  e.HasMorePages = true; // then you need to generate a new page
}

...

The value e.HasMorePages is responsible for generating the next page. The value e.HasMorePages is responsible for generating the next page. Otherwise, the next page is not generated, which means that the current page is the last. The program compares the value of curPage (current page) with the total number of pages nPages. If the values of curPage and nPages are equal, then e.HasMorePages becomes false and the printing (viewing) of pages is stopped.

The above handler algorithm does not take into account the text output beyond the page borders in width. The algorithm is implemented for demonstration purposes. If desired, you can finish this property.

 

6.4. Programming the click event handler on the “Page Setup” button

If the user clicked on the “Page Setup” button, the window for setting page parameters should open.

// The "Page Setup" command
private void button1_Click(object sender, EventArgs e)
{
  pageSetupDialog1.ShowDialog(); // display the window
}

 

6.5. Programming the click event handler on the “Print” button

The document is directly printed using the Print() method, which is called from the printDocument1 instance. The print dialog box is preliminarily displayed.

// Command Print()
private void button2_Click(object sender, EventArgs e)
{
  if (printDialog1.ShowDialog() == DialogResult.OK)
    printDocument1.Print();
}

 

6.6. Programming the click event handler on the “Print Preview” button
// Command PrintPreviewDialog()
private void button3_Click(object sender, EventArgs e)
{
  printPreviewDialog1.ShowDialog();
}

 

7. Run the program for execution

After the performed actions, you can run the program for execution. In order to print a document with richTextBox1, a printer must be installed in the system.

This program is a demo. Optionally, the process of forming a document for printing can be supplemented with its own fonts, colors, etc.

 


Related topics