Print using Visual Studio

Using Visual Studio, we can print:

– directly using print method
– insert a generated image with the content and then print
– a combination of both

Form preview

Code for Form

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Print_Etiquetas
{
    public partial class Form1 : Form
    {
        GenerateImage gImage = new GenerateImage();

        int nPages = 1;
        int Page = 0;
        Bitmap bitmap;
        
        int dpi = 203;
        Size size_mm = new Size(100, 40);

        public Form1()
        {
            InitializeComponent();

            //Fonte            
            comboBox1.Items.Add("Arial");
            comboBox1.Items.Add("Arial Black");
            comboBox1.Items.Add("Arial Narrow");
            comboBox1.Items.Add("Calibri");
            comboBox1.Items.Add("Lucida Console");
            comboBox1.SelectedIndex = 2;

            textBox7.Text = "14"; //default font size

            textBox0.Text = "Dear Sir(s)";

            //print
            System.Drawing.Printing.PaperSize custom = new System.Drawing.Printing.PaperSize("custom", 100, 40);
            printDocument1.DefaultPageSettings.PaperSize = custom;            
            printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);

            //exit control
            this.FormClosing += Form1_FormClosing;

            //preview
            updateImage(textBox0.Text, new string[] { "Name", "To", "Address", "State", "Postal Code" });
        }

        //controls if the user wants to exit/close the application
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dialog = MessageBox.Show("Are you sure?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialog == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
        }       

        //generate image
        private void updateImage(string line0, string[] text)
        {
            bitmap = gImage.ImageFromData(line0, text, size_mm, dpi, new Font(comboBox1.SelectedItem.ToString(), int.Parse(textBox7.Text)));

            pictureBox1.BackColor = Color.White;
            pictureBox1.BorderStyle = BorderStyle.FixedSingle;

            //resize
            Bitmap bitmapResized = new Bitmap(bitmap, new Size(pictureBox1.Width, pictureBox1.Height));

            //show image
            pictureBox1.BackgroundImage = (Image)bitmapResized;
        }

        //print
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("preview label before print", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            //PrintDialog associate with PrintDocument;
            printDialog1.Document = printDocument1;
            //----------------------------------------------------
            // Show Print selection menu and then print
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocument1.DocumentName = "label";
                Page = 0; //reset number of page
                int num;
                bool isNum = int.TryParse(nCopies.Text, out num);
                if (!isNum)
                {
                    MessageBox.Show("You need to insert a valid number for copies");
                    return;
                }
                nPages = num;
                printDocument1.Print();
            }
        }
        void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.PageUnit = GraphicsUnit.Millimeter;
            
            //prints bitmap
            e.Graphics.DrawImageUnscaled(bitmap, new Point(0, 0));            

            //controls number copies
            Page++;
            if (Page < nPages)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
            }            
        }        

        //update preview
        private void button3_Click(object sender, EventArgs e)
        {
            updateImage(textBox0.Text, new string[] { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text});
        }

        //exit/close application
        private void button5_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

 

Code for Class (GenerateImage)

using System.Drawing;

namespace Print_Etiquetas
{
    class GenerateImage
    {
        public GenerateImage()
        {

        }

        public Bitmap ImageFromData(string line0, string[] data, Size size_mm, int dpi, Font font)
        {
            double inWidth = (size_mm.Width / 25.4) * dpi;
            double inHeight = (size_mm.Height / 25.4) * dpi;

            var bitmap = new Bitmap((int)(inWidth), (int)(inHeight));
            int inc = (bitmap.Height / 6) - 1;
            bitmap.SetResolution(dpi, dpi);
            using (var g = System.Drawing.Graphics.FromImage(bitmap))
            {
                g.Clear(Color.White);
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                //process Label
                int yPos = 1;
                g.DrawString(line0, font, Brushes.Black, new Point(2, yPos));
                yPos += inc;

                for (int i = 0; i < data.GetLongLength(0); i++)
                {
                    g.DrawString(data[i], font, Brushes.Black, new Point(2, yPos));
                    yPos += inc;
                }
            }
            return bitmap;
        }
    }
}

 

The result

One fact we need to understand when generating an image for print is the size, which is defined by the size in millimeters or inches, multiplied by the dpi (dots per inch)

Let’s take the example of the code, if we need to print a label with 100 x 40mm (width x height):

– Size: 100x40mm (to inch: divide by 25.4) = 100/25.4 by 40/25.4

– Dpi: in my case the printer has a dpi of 203, it’s a TSC TA210 printer, link: TSC TA210

– So the image needs to be (Width by Height) 203*3.937 by 203*1.575

When printing using the code e.Graphics.DrawImageUnscaled(…) the program will use the real size mm/in for the print, even if the dpi for the printer is different, but it’s advised to use the correct or higher dpi if possible.

Leave a Reply

Your email address will not be published. Required fields are marked *