Link Search Menu Expand Document

Print Labels - C#

BarCode SDK sample in C# demonstrating ‘Print Labels’

Form1.Designer.cs
namespace PrintLabels
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
			this.buttonPrint = new System.Windows.Forms.Button();
			this.printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();
			this.printDocument1 = new System.Drawing.Printing.PrintDocument();
			this.printDialog1 = new System.Windows.Forms.PrintDialog();
			this.SuspendLayout();
			// 
			// buttonPrint
			// 
			this.buttonPrint.Location = new System.Drawing.Point(12, 12);
			this.buttonPrint.Name = "buttonPrint";
			this.buttonPrint.Size = new System.Drawing.Size(260, 57);
			this.buttonPrint.TabIndex = 0;
			this.buttonPrint.Text = "Draw And Print Cards";
			this.buttonPrint.UseVisualStyleBackColor = true;
			this.buttonPrint.Click += new System.EventHandler(this.buttonPrint_Click);
			// 
			// printPreviewDialog1
			// 
			this.printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);
			this.printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);
			this.printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);
			this.printPreviewDialog1.Document = this.printDocument1;
			this.printPreviewDialog1.Enabled = true;
			this.printPreviewDialog1.Icon = ((System.Drawing.Icon)(resources.GetObject("printPreviewDialog1.Icon")));
			this.printPreviewDialog1.Name = "printPreviewDialog1";
			this.printPreviewDialog1.UseAntiAlias = true;
			this.printPreviewDialog1.Visible = false;
			// 
			// printDocument1
			// 
			this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
			// 
			// printDialog1
			// 
			this.printDialog1.Document = this.printDocument1;
			this.printDialog1.UseEXDialog = true;
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(284, 156);
			this.Controls.Add(this.buttonPrint);
			this.Name = "Form1";
			this.Text = "Form1";
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.Button buttonPrint;
		private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;
		private System.Drawing.Printing.PrintDocument printDocument1;
		private System.Windows.Forms.PrintDialog printDialog1;
	}
}


Form1.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Windows.Forms;
using Bytescout.BarCode;

namespace PrintLabels
{
	/// <summary>
	/// This example demonstrates drawing and printing of mutiple cards (e.g. stickers) on a single page.
	/// Cards contain variable labels and barcodes.
	/// </summary>
	public partial class Form1 : Form
	{
		SizeF PaperSize = new SizeF(5.5f, 8.75f); // 5.5 x 8.75 inches
		const int PrintingResolution = 300; // 300 dots per inch
		
		public Form1()
		{
			InitializeComponent();

			// Make the print preview dialog larger by default
			printPreviewDialog1.MinimumSize = new Size(800, 600);
		}

		private void buttonPrint_Click(object sender, EventArgs e)
		{
			// Show print setup dialog, then print preview
			if (printDialog1.ShowDialog() == DialogResult.OK)
				printPreviewDialog1.ShowDialog();
		}

		private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
		{
			// Draw page on the printer device context
			Bitmap pageBitmap = DrawPage();
			e.Graphics.DrawImage(pageBitmap, 0, 0);
		}

		// Draw cards on a bitmap of custom size
		private Bitmap DrawPage()
		{
			SizeF cardSize = new SizeF(PaperSize.Width / 4, PaperSize.Height / 4); // 4 x 4 cards on a page

			// Prepare constant and variable labels
			string strBrand = "CJ SHOES";
			string strModel = "ARTHUR-1N";
			string strColor = "BLK";
			float shoeSizeStart = 5.5f;
			float shoeSizeStep = 0.5f;
			long barcodeStartValue = 4611030000;
			int barcodeValueStep = 1;

			// Prepare fonts
			Font font1 = new Font("Arial", 0.12f, GraphicsUnit.Inch);
			Font font2 = new Font("Arial", 0.10f, GraphicsUnit.Inch);
			Font font3 = new Font("Arial", 0.09f, GraphicsUnit.Inch);
			Font font4 = new Font("Arial", 0.15f, GraphicsUnit.Inch);

			// Prepare barcode generator
			Barcode barcode = new Barcode("demo", "demo");
			barcode.Symbology = SymbologyType.I2of5;
			barcode.NarrowBarWidth = 2;
			barcode.DrawCaption = false;

			int cardIndex = 0;

			// Create bitmap for the page
			Bitmap pageBitmap = new Bitmap((int) (PaperSize.Width * PrintingResolution), (int) (PaperSize.Height * PrintingResolution));
			pageBitmap.SetResolution(PrintingResolution, PrintingResolution);

			using (Graphics pageCanvas = Graphics.FromImage(pageBitmap))
			{
				pageCanvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
				pageCanvas.CompositingQuality = CompositingQuality.HighQuality;

				// Setup page units to inches
				pageCanvas.PageUnit = GraphicsUnit.Inch;
				// Fill background with white color
				pageCanvas.Clear(Color.White);

				// Draw cards
				for (int row = 0; row < 4; row++)
				{
					for (int column = 0; column < 4; column++)
					{
						// Create bitmap for card
						Bitmap cardBitmap = new Bitmap((int) (cardSize.Width * PrintingResolution), (int) cardSize.Height * PrintingResolution);
						cardBitmap.SetResolution(PrintingResolution, PrintingResolution);

						using (Graphics cardCanvas = Graphics.FromImage(cardBitmap))
						{
							// Setup page units to inches
							cardCanvas.PageUnit = GraphicsUnit.Inch;

							// Setup drawing quality
							cardCanvas.SmoothingMode = SmoothingMode.HighQuality;
							cardCanvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
							cardCanvas.CompositingQuality = CompositingQuality.HighQuality;

							StringFormat stringFormat = new StringFormat();
							stringFormat.Alignment = StringAlignment.Center;

							// Draw static labels
							cardCanvas.DrawString(strBrand, font1, Brushes.Black, cardSize.Width / 2, 0.1f, stringFormat);
							cardCanvas.DrawString(strModel, font2, Brushes.Black, cardSize.Width / 2, 0.4f, stringFormat);
							cardCanvas.DrawString(strColor, font1, Brushes.Black, cardSize.Width / 2, 0.7f, stringFormat);

							// Generate barcode image
							barcode.Value = (barcodeStartValue + cardIndex * barcodeValueStep).ToString();
							barcode.PreserveMinReadableSize = false;
							barcode.ResolutionX = barcode.ResolutionY = PrintingResolution;
							barcode.FitInto(cardSize.Width, 0.5f, UnitOfMeasure.Inch);
							Image barcodeImage = barcode.GetImage();
							// Draw barcode
							cardCanvas.DrawImage(barcodeImage, 0, 1.0f);
							// Draw barcode label
							cardCanvas.DrawString(barcode.Value, font3, Brushes.Black, cardSize.Width / 2, 1.4f, stringFormat);

							// Draw shoe size label
							cardCanvas.DrawString((shoeSizeStart + cardIndex * shoeSizeStep).ToString(), font4, Brushes.Black,
								cardSize.Width / 2, 1.7f, stringFormat);
						}

						// Draw card on the page
						pageCanvas.DrawImage(cardBitmap, column * cardSize.Width, row * cardSize.Height);

						cardIndex++;
					}
				}
			}

			return pageBitmap;
		}
	}
}

Program.cs
using System;
using System.Windows.Forms;

namespace PrintLabels
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Form1());
		}
	}
}

Resources.Designer.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PrintLabels.Properties {
    using System;
    
    
    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {
        
        private static global::System.Resources.ResourceManager resourceMan;
        
        private static global::System.Globalization.CultureInfo resourceCulture;
        
        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }
        
        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PrintLabels.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }
        
        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }
    }
}

Settings.Designer.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PrintLabels.Properties {
    
    
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
    }
}

Download Source Code (.zip)

Return to the previous page Explore BarCode SDK


Copyright © 2016 - 2021 ByteScout