C# - Simple PrintDocument Example

This code snippet shows how to use the PrintDocument class to print documents. It uses the PrintPreviewDialog to show the preview of the document a button to print the document.
  1. // Place 2 buttons on the form (PrintPreview, Print)
  2. // PLace a textbox control on the form (TextData)
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Drawing.Printing;
  9. using System.Text;
  10. using System.Windows.Forms;
  11. namespace PrintPreviewDialogExample
  12. {
  13.     public partial class Form1 : Form
  14.     {
  15.         private PrintDocument Document;
  16.         public Form1()
  17.         {
  18.             InitializeComponent();
  19.         }
  20.         private void PrintPreview_Click(object sender, EventArgs e)
  21.         {
  22.             Document = new PrintDocument();
  23.             PrintPreviewDialog PrintPreviewDlg = new PrintPreviewDialog();
  24.             PrintPreviewDlg.Document = Document;
  25.             PrintPreviewDlg.Show();
  26.             Document.PrintPage += new PrintPageEventHandler(Document_PrintPage);
  27.         }
  28.         private void Print_Click(object sender, EventArgs e)
  29.         {
  30.             Document.Print();
  31.         }
  32.         void Document_PrintPage(object sender, PrintPageEventArgs e)
  33.         {
  34.             Graphics g = e.Graphics;
  35.             SolidBrush Brush = new SolidBrush(Color.Black);
  36.             g.DrawString(this.TextData.Text, new Font("arial", 9), Brush, 10, 10);
  37.         }
  38.     }
  39. }

Related Snippets

No comments:

Post a Comment