How to Print Text in a Windows Form Application Using C#

By FoxLearn 12/2/2024 2:35:00 PM   12.86K
Printing text in a Windows Forms application involves using the PrintDocument class and its associated events.

Printing is an essential feature in many applications, and Windows Forms provides a simple way to achieve this using the PrintDocument and PrintPreviewDialog components. This article demonstrates how to print text in a Windows Forms application.

How to Print Text in a Windows Form Application Using C#?

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PrintText" and then click OK

Drag and drop the Label, TextBox and Button from the Visual Toolbox onto your form designer, then design your form as shown below.

print text in windows form

You need to add a PrintDocument, PrintPreviewDialog to your form.

print preview dialog in c#

Set the PrintPage event of printDocument1 to printDocument1_PrintPage.

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    // Draw text to your document
    e.Graphics.DrawString(txtValue.Text, new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, new PointF(100, 100));
}

This method determines the content that will appear on the printed page. The e.Graphics.DrawString method is used to draw the text.

Assign the Click event of the print button (btnPrint) to Print_Click.

private void Print_Click(object sender, EventArgs e)
{
    // Open print preview dialog
    if (printPreviewDialog1.ShowDialog() == DialogResult.OK)
        printDocument1.Print();
}

This method displays a print preview dialog and sends the document to the printer if confirmed.

Enter text in the txtValue TextBox, then click the "Print" button to open the preview dialog. Confirm the dialog to print the text.

VIDEO TUTORIAL