Advanced
15 min read
Control #19
PrintDocument Control
PrintDocument is the core control for printing in Windows Forms. It defines what gets printed through the PrintPage event.
What is a PrintDocument?
PrintDocument is a component that handles the printing process. It raises the PrintPage event where you draw the content using Graphics. It works with PrintDialog, PrintPreviewDialog, and PageSetupDialog.
Code Example
// The PrintPage event does the actual drawing
private void printDocument1_PrintPage(object sender,
PrintPageEventArgs e)
{
Graphics g = e.Graphics;
Rectangle printArea = e.MarginBounds;
// Draw a header
using (var font = new Font("Arial", 16, FontStyle.Bold))
{
g.DrawString("My Document", font,
Brushes.Black, printArea.X, printArea.Y);
}
// Draw content
string content = "This is the content of the document.";
using (var font = new Font("Arial", 12))
{
g.DrawString(content, font,
Brushes.Black, printArea.X,
printArea.Y + 40);
}
// Draw a footer
string footer = $"Page {e.PageNumber}";
using (var font = new Font("Arial", 10))
{
var size = g.MeasureString(footer, font);
g.DrawString(footer, font,
Brushes.Gray,
printArea.Right - size.Width,
printArea.Bottom - 20);
}
// Set HasMorePages for multi-page documents
e.HasMorePages = false;
}
Exercise
Task: Create a document printing app.
- Add a PrintDocument component.
- Write the PrintPage event to draw content.
- Add a Button to print the document.
- Add a Button to show print preview.
- Add a Button for page setup.
- Add support for multi-page documents.
Key Takeaway
PrintDocument is the foundation of printing. Use the PrintPage event to draw content using the Graphics object.