Saturday, January 14, 2012

Printing With C#

In this post I want to show you, how to control printers in C#. Therefor are multiple possibilites, I use the Graphics property of the print event, the result to be printed then has to be printed in this.

First System.Drawing.Printing has to be included. The following line initializes the needed object, which represents the document which is to be printed:

PrintDocument PrintDoc = new PrintDocument();


Installed printers are saved in PrinterSettings.InstalledPrinters. In this list the names of the printers are saved as strings, to set the printer we want to use, we set PrintDoc.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[Index].
The document is printed with the command PrintDoc.Print().
Before though we add the document an event handler for its print event:
PrintDoc.PrintPage += new PrintPageEventHandler(PrintPage).
Here PrintPage is an arbitraty function with the following signature: void PrintPage(object sender, PrintPageEventArgs e).
This is now called, whenever a document is printed.
In this function we can also create the desired print result by drawing it into e.Graphics. Images for example can also be read-in there and printed.
Finally the complete code, which prints a line and a string:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Drawing.Printing;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Print()
        {
            PrintDocument PrintDoc = new PrintDocument();

            List<string> Printers = new List<string>();
            foreach (string p in PrinterSettings.InstalledPrinters)
                Printers.Add(p);

            // in Printers all available printers are saved, chose one
            PrintDoc.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[0];

            PrintDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            PrintDoc.Print();
        }

        void PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawLine(new Pen(Color.Black), new Point(0, 0), new Point(100, 100));
            e.Graphics.DrawString("Ich kann jetzt mit C# drucken", new Font("Times New Roman", 12), new SolidBrush(Color.Black), new Point(45, 45));

        }
    }


}

Thursday, January 5, 2012

Fill String With Characters

There is a nice little trick, with which a string can quickly be filled with arbitrary characters.
The class string provides therefor the following constructor:
new string(meinzeichen, anzahl).
With this a new string is created, containing anzahl many characters with the value meinzeichen.
The following example creates a string consisting of 30 "-":

string filled = new string('-', 30);