Windows Form Printing Service

Today we are going to focus on printing from Windows Form application silently to the printer using C# graphics object. Graphics objects are defined from:

  • Namespace: System.Drawing
  • Assembly: System.Drawing.dll

Get More on 

Let’s get started by creating a new sample windows form application. Here is how we have structured the application.

Form:

public partial class FrmPrint : Form
{
    private List data = null;
    private PrintTemplate objPrintTemp = null;

    public FrmPrint()
    {
        InitializeComponent();
    }

    private void FrmPrint_Load(object sender, EventArgs e)
    {
        chkPrintPrv.Text = "Print Preview";
    }

    private void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            data = new List();
            data = CartData.GetData();
            new Print(data).PrintDoc();
        }
        catch (Exception)
        {
            throw;
        }
    }

    private void chkPrintPrv_CheckedChanged(object sender, EventArgs e)
    {
        try
        {
            if (chkPrintPrv.Checked)
            {
                chkPrintPrv.Text = "Generated Preview";

                PrintPreviewControl ppc;
                PrintDocument docToPrint = new PrintDocument();
                PaperSize psize = new PaperSize("Custom", 280, 300);

                ppc = new PrintPreviewControl();
                ppc.Name = "PrintPreviewControl1";
                ppc.Dock = DockStyle.Fill;
                ppc.Location = new Point(0, 0);
                ppc.Document = docToPrint;
                ppc.Zoom = 1;
                ppc.Document.DocumentName = "c:\\";
                ppc.UseAntiAlias = true;
                ppc.Margin = new Padding(0);
                ppc.BackColor = Color.White;
                ppc.Document.DefaultPageSettings.PaperSize = psize;
                ppc.Document.PrintController = new StandardPrintController();

                tpanelRptPrev.Controls.Clear();
                tpanelRptPrev.Controls.Add(ppc, 0, 0);

                objPrintTemp = new PrintTemplate();
                new PrintTemplate(CartData.GetData());
                docToPrint.PrintPage += new PrintPageEventHandler(objPrintTemp.Default_Receipt);
                docToPrint.Dispose();
            }
            else
            {
                chkPrintPrv.Text = "Print Preview";
                tpanelRptPrev.Controls.Clear();
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}

Models:

public class vmItems
{
    public int ItemId { get; set; }
    public int ItemQty { get; set; }
    public string ItemName { get; set; }
    public double ItemPrice { get; set; }
    public double ItemTotal { get; set; }
    public List vmChildItems { get; private set; }

    public vmItems(int id, int qty, string name, double price, double total)
    {
        ItemId = id;
        ItemQty = qty;
        ItemName = name;
        ItemPrice = price;
        ItemTotal = total;
        vmChildItems = new List();
    }
}

Data:

public class CartData
{
    public static List GetData()
    {
        List data = null;
        try
        {
            var Item1 = new vmItems(1, 2, "Chicken Tikka", 3.50, 7.00);
            var Item2 = new vmItems(2, 1, "Kebab", 3.50, 3.50); Item2.vmChildItems.Add(new vmItems(1, 2, "Extra Hot", 1.50, 1.50));
            var Item3 = new vmItems(3, 3, "Chicken Masala", 3.50, 3.50);
            var Item4 = new vmItems(4, 1, "Faluda", 3.50, 3.50);
            data = new List { Item1, Item2, Item3, Item4 };
        }
        catch (Exception)
        {
            throw;
        }

        return data;
    }
}

Print:

public class Print
{
    private PrintDocument pdoc = null;
    private PrintTemplate objPrintTemp = null;
    private static List cartData = null;

    public Print()
    {
    }

    public Print(List data) : this()
    {
        cartData = data;
    }

    public void PrintDoc()
    {
        try
        {
            objPrintTemp = new PrintTemplate();
            using (pdoc = new PrintDocument())
            {
                PrintDialog pd = new PrintDialog();
                PrinterSettings ps = new PrinterSettings();
                PaperSize psize = new PaperSize("Custom", 280, 900);
                pd.Document = pdoc;
                pd.Document.PrintController = new StandardPrintController();
                pd.Document.PrinterSettings.PrinterName = Printer.GetDefaultPrinter();
                pd.Document.PrinterSettings.Copies = 1;
                pd.Document.DefaultPageSettings.PaperSize = psize;
                pdoc.DefaultPageSettings.PaperSize.Height = 900;
                pdoc.DefaultPageSettings.PaperSize.Width = 280;

                new PrintTemplate(cartData);
                pdoc.PrintPage += new PrintPageEventHandler(objPrintTemp.Default_Receipt);

                //Print to Printer
                PrintPreviewDialog pp = new PrintPreviewDialog();
                pp.Document = pdoc;
                pdoc.Print();
                pdoc.Dispose();
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}

Print Templating:

public class PrintTemplate
{
    private static List cartData = null;

    public PrintTemplate()
    {
    }

    public PrintTemplate(List data) : this()
    {
        cartData = data;
    }

    public void Default_Receipt(object sender, PrintPageEventArgs e)
    {
        try
        {
            #region #Decleration
            Font drawFontTiny = new Font("Courier New", 1, GraphicsUnit.Pixel);
            Font drawFontSmall = new Font("Courier New", 13, GraphicsUnit.Pixel);
            Font drawFontSmallIta = new Font("Courier New", 13, FontStyle.Italic, GraphicsUnit.Pixel);

            // Create brush.
            SolidBrush drawBrushBlack = new SolidBrush(Color.Black);
            SolidBrush drawBrushWhite = new SolidBrush(Color.WhiteSmoke);

            // Create rectangle for drawing.
            float startX = 0.0F; //Left
            float startY = 0.0F; //Top
            float width = 275.0F;
            float height = 0.0F;

            RectangleF drawRect = new RectangleF();

            // Draw rectangle to screen.
            Pen blackPen = new Pen(Color.Black);
            Pen whitePen = new Pen(Color.White);
            Pen whitesmokePen = new Pen(Color.WhiteSmoke);
            Pen blackPenThin = new Pen(Color.Black, 1);
            Pen blackPenThik = new Pen(Color.Black, 3);

            // Set format of string.
            StringFormat drawFormat = new StringFormat();

            // Set gap of string.
            float Offset = 0F;
            #endregion

            using (Graphics graphics = e.Graphics)
            {
                foreach (var item in cartData)
                {
                    //Next Gap
                    Offset = (startY + Offset + 20.0F);

                    //Left QTY
                    startX = 5.0F;
                    width = 25.0F;
                    height = 20.0F;
                    drawFormat.Alignment = StringAlignment.Near;
                    drawRect = new RectangleF(startX, Offset, width, height);
                    graphics.DrawString(item.ItemQty + "x", drawFontSmall, drawBrushBlack, drawRect, drawFormat);
                    //graphics.DrawRectangle(blackPen, startX, Offset, width, height);

                    //Middle Item Name
                    startX = 30.0F;
                    width = 190.0F;
                    //height = 20.0F;
                    drawFormat.Alignment = StringAlignment.Near;
                    drawRect = new RectangleF(startX, Offset, width, height);
                    drawRect.Size = new Size(190, ((int)e.Graphics.MeasureString(item.ItemName.ToUpper(), drawFontSmall, 190, StringFormat.GenericTypographic).Height));
                    graphics.DrawString(item.ItemName.ToUpper(), drawFontSmall, drawBrushBlack, drawRect);
                    //graphics.DrawRectangle(blackPen, startX, Offset, width, height);

                    Offset = (startY + Offset + drawRect.Size.Height);

                    //Right Price
                    startX = 220.0F;
                    width = 50.0F;
                    //height = 20.0F;
                    drawFormat.Alignment = StringAlignment.Far;
                    Offset = Offset - 13;
                    drawRect = new RectangleF(startX, Offset, width, height);
                    graphics.DrawString(item.ItemTotal.ToString("0.00"), drawFontSmall, drawBrushBlack, drawRect, drawFormat);
                    //graphics.DrawRectangle(blackPen, startX, Offset, width, drawRect.Size.Height);

                    //Child Item
                    foreach (var citem in item.vmChildItems)
                    {
                        //Next Gap
                        Offset = (startY + Offset + 15.0F);

                        //Left QTY
                        startX = 30.0F;
                        width = 40.0F;
                        height = 20.0F;
                        drawFormat.Alignment = StringAlignment.Near;
                        drawRect = new RectangleF(startX, Offset, width, height);
                        graphics.DrawString("-" + citem.ItemQty + "x", drawFontSmallIta, drawBrushBlack, drawRect, drawFormat);
                        //graphics.DrawRectangle(blackPen, startX, Offset, width, height);

                        //Middle Item Name
                        startX = 60.0F;
                        width = 200.0F;
                        //height = 20.0F;
                        drawFormat.Alignment = StringAlignment.Near;
                        drawRect = new RectangleF(startX, Offset, width, height);
                        drawRect.Size = new Size(200, ((int)e.Graphics.MeasureString(citem.ItemName.ToUpper(), drawFontSmallIta, 200, StringFormat.GenericTypographic).Height));
                        graphics.DrawString(citem.ItemName.ToUpper(), drawFontSmallIta, drawBrushBlack, drawRect);
                        //graphics.DrawRectangle(blackPen, startX, Offset, width, height);

                        Offset = (startY + Offset + drawRect.Size.Height);

                        //Right Price
                        startX = 220.0F;
                        width = 50.0F;
                        //height = 20.0F;
                        drawFormat.Alignment = StringAlignment.Far;
                        Offset = Offset - 13;
                        drawRect = new RectangleF(startX, Offset, width, height);
                        graphics.DrawString(citem.ItemTotal.ToString("0.00"), drawFontSmallIta, drawBrushBlack, drawRect, drawFormat);
                        //graphics.DrawRectangle(blackPen, startX, Offset, width, drawRect.Size.Height);

                    }
                }

                //Last Gap
                Offset = (startY + Offset + 50.0F);
                //======================END=====================
                startX = 5.0F;
                startY = 10.0F;
                width = 275.0F;
                height = 20.0F;
                drawFormat.Alignment = StringAlignment.Center;
                drawRect = new RectangleF(startX, Offset, width, height);
                graphics.DrawString("_", drawFontTiny, drawBrushWhite, drawRect, drawFormat);
                //graphics.DrawRectangle(whitePen, startX, Offset, width, height);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}

OutPut:

Source Code: I’ve uploaded the full source code to download/clone , Hope this will help 🙂

References:

  • http://www.c-sharpcorner.com/uploadfile/mahesh/printpreviewcontrol-in-C-Sharp/
  • http://www.techotopia.com/index.php/Drawing_Graphics_in_C_Sharp
  • https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-create-graphics-objects-for-drawing

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply