一个winform打印功能的示例

操作步骤:
1、新建winform项目及创建窗体
2、拖取 打印 相关控件
PageSetupDialog 、 PrintDialog 、 PrintDocument 、PrintPreviewDialog
3、设置上述控件的Document属性为相应的PrintDocument
4、设置按钮等控件 及 添加相应按钮事件

public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
this.printDocument1.OriginAtMargins = true;//启用页边距
this.pageSetupDialog1.EnableMetric = true; //以毫米为单位 } //打印设置
private void btnSetPrint_Click(object sender, EventArgs e)
{
this.pageSetupDialog1.ShowDialog();
} //打印预览
private void btnPrePrint_Click(object sender, EventArgs e)
{
this.printPreviewDialog1.ShowDialog();
} //打印
private void btnPrint_Click(object sender, EventArgs e)
{
if (this.printDialog1.ShowDialog() == DialogResult.OK)
{
this.printDocument1.Print();
}
} //打印内容的设置
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
////打印内容 为 整个Form
//Image myFormImage;
//myFormImage = new Bitmap(this.Width, this.Height);
//Graphics g = Graphics.FromImage(myFormImage);
//g.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size);
//e.Graphics.DrawImage(myFormImage, 0, 0); ////打印内容 为 局部的 this.groupBox1
//Bitmap _NewBitmap = new Bitmap(groupBox1.Width, groupBox1.Height);
//groupBox1.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
//e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height); //打印内容 为 自定义文本内容
Font font = new Font("宋体", );
Brush bru = Brushes.Blue;
for (int i = ; i <= ; i++)
{
e.Graphics.DrawString("Hello world ", font, bru, i*, i*);
}
}
}

winForm打印功能示例

几种条码打印方法:

>> itf14条码打印:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging; namespace Frm.Common
{
class ITF14
{ private string Raw_Data; private string[] ITF14_Code = { "NNWWN", "WNNNW", "NWNNW", "WWNNN", "NNWNW", "WNWNN", "NWWNN", "NNNWW", "WNNWN", "NWNWN" }; public ITF14(string input)
{
Raw_Data = input; CheckDigit();
}
/// <summary>
/// Encode the raw data using the ITF-14 algorithm.
/// </summary>
public string Encode_ITF14()
{
//check length of input
string result = ""; for (int i = ; i < Raw_Data.Length; i += )
{
bool bars = true;
string patternbars = ITF14_Code[Int32.Parse(Raw_Data[i].ToString())];//码图
string patternspaces = ITF14_Code[Int32.Parse(Raw_Data[i + ].ToString())];//空格图
string patternmixed = "";// 混合图 //interleave
while (patternbars.Length > )
{
patternmixed += patternbars[].ToString() + patternspaces[].ToString();
patternbars = patternbars.Substring();
patternspaces = patternspaces.Substring();
}//while foreach (char c1 in patternmixed)
{
if (bars)
{
if (c1 == 'N')
result += "";
else
result += "";
}//if
else
{
if (c1 == 'N')
result += "";
else
result += "";
}//else
bars = !bars;
}//foreach
}//foreach //add ending bars
result += "";
return result;
}//Encode_ITF14 private void CheckDigit()
{
//calculate and include checksum if it is necessary
if (Raw_Data.Length == )
{
int total = ; for (int i = ; i <= Raw_Data.Length - ; i++)
{
int temp = Int32.Parse(Raw_Data.Substring(i, ));
total += temp * ((i == || i % == ) ? : );
}//for int cs = total % ;
cs = - cs;
if (cs == )
cs = ; Raw_Data += cs.ToString();
}//if
} public Bitmap getFile(string Code)
{
if (Code != null)
{
Bitmap saved = Generate_Image(Code);
return saved;
}
else
{
return null;
}
} //保存文件
public void saveFile(string Code, string strFile)
{
if (Code != null)
{
Bitmap saved = Generate_Image(Code);
saved.Save("D:\\1.jpg", ImageFormat.Jpeg);
saved.Dispose();
}
} private Bitmap Generate_Image(string strBar)
{
Bitmap b = null; int width = ;
int height = ;
b = new Bitmap(width, height); //调整条形码的边距
int bearerwidth = (int)((b.Width) / 12.05);
int iquietzone = Convert.ToInt32(b.Width * 0.05);
int iBarWidth = (b.Width - (bearerwidth * ) - (iquietzone * )) / strBar.Length;
int shiftAdjustment = ((b.Width - (bearerwidth * ) - (iquietzone * )) % strBar.Length) / ; if (iBarWidth <= || iquietzone <= )
throw new Exception("EGENERATE_IMAGE-3: Image size specified not large enough to draw image. (Bar size determined to be less than 1 pixel or quiet zone determined to be less than 1 pixel)"); //draw image
int pos = ; using (Graphics g = Graphics.FromImage(b))
{
//fill background
g.Clear(Color.White); //lines are fBarWidth wide so draw the appropriate color line vertically
using (Pen pen = new Pen(Color.Black, iBarWidth))
{
pen.Alignment = PenAlignment.Right; while (pos < strBar.Length)
{
//draw the appropriate color line vertically
if (strBar[pos] == '')
g.DrawLine(pen, new Point((pos * iBarWidth) + shiftAdjustment + bearerwidth + iquietzone, ), new Point((pos * iBarWidth) + shiftAdjustment + bearerwidth + iquietzone, height)); pos++;
}//while }//using }//using return b;
}//Generate_Image
}
}

itf14打印

Common.ITF14 itf14 = new Common.ITF14("");

             string strBar = itf14.Encode_ITF14();
Bitmap bmp= itf14.getFile(strBar);
if (bmp == null)
{
MessageBox.Show("生成打印条码时发生错误。");
return;
}
else
{
e.Graphics.DrawImage(bmp, new Point(, )); }

itf14打印调用

说明:输入要的条码可以是13位或者14位(13位的情况系统会自动补齐校验码)

>> ean13条码打印:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing; namespace Frm.Common
{
public class BarCode_EAN13
{
#region 生成条码  EAN13码 public static string getEAN13(string s, int width, int height)
{ int checkcode_input = -;//输入的校验码 if (!Regex.IsMatch(s, @"^\d{12}$"))
{ if (!Regex.IsMatch(s, @"^\d{13}$"))
{ return "存在不允许的字符!"; } else
{ checkcode_input = int.Parse(s[].ToString()); s = s.Substring(, ); } } int sum_even = ;//偶数位之和 int sum_odd = ;//奇数位之和 for (int i = ; i < ; i++)
{ if (i % == )
{ sum_odd += int.Parse(s[i].ToString()); } else
{ sum_even += int.Parse(s[i].ToString()); } } int checkcode = ( - (sum_even * + sum_odd) % ) % ;//校验码 if (checkcode_input > && checkcode_input != checkcode)
{ return "输入的校验码错误!"; } s += checkcode;//变成13位 // 000000000101左侧42个01010右侧35个校验7个101000000000 // 6 101左侧6位 01010右侧5位 校验1位101000000000 string result_bin = "";//二进制串 result_bin += ""; string type = ean13type(s[]); for (int i = ; i < ; i++)
{ result_bin += ean13(s[i], type[i - ]); } result_bin += ""; for (int i = ; i < ; i++)
{ result_bin += ean13(s[i], 'C'); } result_bin += ""; string result_html = "";//HTML代码 string color = "";//颜色 int height_bottom = width * ; foreach (char c in result_bin)
{ color = c == '' ? "#FFFFFF" : "#000000"; result_html += "<div style=\"width:" + width + "px;height:" + height + "px;float:left;background:" + color + ";\"></div>"; } result_html += "<div style=\"clear:both\"></div>"; result_html += "<div style=\"float:left;color:#000000;width:" + (width * ) + "px;text-align:center;\">" + s[] + "</div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#000000;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#FFFFFF;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#000000;\"></div>"; for (int i = ; i < ; i++)
{ result_html += "<div style=\"float:left;width:" + (width * ) + "px;color:#000000;text-align:center;\">" + s[i] + "</div>"; } result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#FFFFFF;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#000000;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#FFFFFF;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#000000;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#FFFFFF;\"></div>"; for (int i = ; i < ; i++)
{ result_html += "<div style=\"float:left;width:" + (width * ) + "px;color:#000000;text-align:center;\">" + s[i] + "</div>"; } result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#000000;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#FFFFFF;\"></div>"; result_html += "<div style=\"float:left;width:" + width + "px;height:" + height_bottom + "px;background:#000000;\"></div>"; result_html += "<div style=\"float:left;color:#000000;width:" + (width * ) + "px;\"></div>"; result_html += "<div style=\"clear:both\"></div>"; return "<div style=\"background:#FFFFFF;padding:0px;font-size:" + (width * ) + "px;font-family:'楷体';\">" + result_html + "</div>"; } private static string ean13(char c, char type)
{ switch (type)
{ case 'A':
{ switch (c)
{ case '': return ""; case '': return ""; case '': return ""; case '': return "";// case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; default: return "Error!"; } } case 'B':
{ switch (c)
{ case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return "";// case '': return ""; case '': return ""; case '': return ""; default: return "Error!"; } } case 'C':
{ switch (c)
{ case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; case '': return ""; default: return "Error!"; } } default: return "Error!"; } } private static string ean13type(char c)
{ switch (c)
{ case '': return "AAAAAA"; case '': return "AABABB"; case '': return "AABBAB"; case '': return "AABBBA"; case '': return "ABAABB"; case '': return "ABBAAB"; case '': return "ABBBAA";//中国 case '': return "ABABAB"; case '': return "ABABBA"; case '': return "ABBABA"; default: return "Error!"; } }
#endregion public static void Paint_EAN13(string ean13, Graphics g, Rectangle drawBounds)
{
string barCode = ean13; char[] symbols = barCode.ToCharArray(); //--- Validate barCode -------------------------------------------------------------------//
if (barCode.Length != )
{
return;
}
foreach (char c in symbols)
{
if (!Char.IsDigit(c))
{
return;
}
} //--- Check barcode checksum ------------------------//
int checkSum = Convert.ToInt32(symbols[].ToString());
int calcSum = ;
bool one_three = true;
for (int i = ; i < ; i++)
{
if (one_three)
{
calcSum += (Convert.ToInt32(symbols[i].ToString()) * );
one_three = false;
}
else
{
calcSum += (Convert.ToInt32(symbols[i].ToString()) * );
one_three = true;
}
} char[] calcSumChar = calcSum.ToString().ToCharArray();
if (checkSum != && checkSum != ( - Convert.ToInt32(calcSumChar[calcSumChar.Length - ].ToString())))
{
return;
}
//--------------------------------------------------//
//---------------------------------------------------------------------------------------// Font font = new Font("Microsoft Sans Serif", ); // Fill backround with white color
// g.Clear(Color.White); int lineWidth = ;
int x = drawBounds.X; // Paint human readable 1 system symbol code
g.DrawString(symbols[].ToString(), font, new SolidBrush(Color.Black), x, drawBounds.Y + drawBounds.Height - );
x += ; // Paint left 'guard bars', always same '101'
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth; // First number of barcode specifies how to encode each character in the left-hand
// side of the barcode should be encoded.
bool[] leftSideParity = new bool[];
switch (symbols[])
{
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = true; // Odd
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
break;
case '':
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
leftSideParity[] = false; // Even
leftSideParity[] = true; // Odd
break;
} // second number system digit + 5 symbol manufacter code
string lines = "";
for (int i = ; i < ; i++)
{
bool oddParity = leftSideParity[i];
if (oddParity)
{
switch (symbols[i + ])
{
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
}
}
// Even parity
else
{
switch (symbols[i + ])
{
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
}
}
} // Paint human readable left-side 6 symbol code
// g.DrawString(barCode.Substring(1, 6), font, new SolidBrush(Color.Black), x, drawBounds.Y + drawBounds.Height - 12); char[] xxx = lines.ToCharArray();
for (int i = ; i < xxx.Length; i++)
{
if (xxx[i] == '')
{
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height - );
}
else
{
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height - );
}
x += lineWidth;
} // Paint center 'guard bars', always same '01010'
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth; // 5 symbol product code + 1 symbol parity
lines = "";
for (int i = ; i < ; i++)
{
switch (symbols[i])
{
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
case '':
lines += "";
break;
}
} // Paint human readable left-side 6 symbol code
// g.DrawString(barCode.Substring(7, 6), font, new SolidBrush(Color.Black), x, drawBounds.Y + drawBounds.Height - 12); xxx = lines.ToCharArray();
for (int i = ; i < xxx.Length; i++)
{
if (xxx[i] == '')
{
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height - );
}
else
{
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height - );
}
x += lineWidth;
} // Paint right 'guard bars', always same '101'
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.White, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
x += lineWidth;
g.DrawLine(new Pen(Color.Black, lineWidth), x, drawBounds.Y, x, drawBounds.Y + drawBounds.Height);
} } }

ean-13条码打印

说明:输入条码必须是13位,且最后一位的校验码正确

>> 128条码打印:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing; namespace Frm.Common
{
class BarCode
{
public class Code128
{
private DataTable m_Code128 = new DataTable();
private uint m_Height = ;
/// <summary>
/// 高度
/// </summary>
public uint Height { get { return m_Height; } set { m_Height = value; } }
private Font m_ValueFont = null;
/// <summary>
/// 是否显示可见号码 如果为NULL不显示号码
/// </summary>
public Font ValueFont { get { return m_ValueFont; } set { m_ValueFont = value; } }
private byte m_Magnify = ;
/// <summary>
/// 放大倍数
/// </summary>
public byte Magnify { get { return m_Magnify; } set { m_Magnify = value; } }
/// <summary>
/// 条码类别
/// </summary>
public enum Encode
{
Code128A,
Code128B,
Code128C,
EAN128
}
public Code128()
{
m_Code128.Columns.Add("ID");
m_Code128.Columns.Add("Code128A");
m_Code128.Columns.Add("Code128B");
m_Code128.Columns.Add("Code128C");
m_Code128.Columns.Add("BandCode");
m_Code128.CaseSensitive = true;
#region 数据表
m_Code128.Rows.Add("", " ", " ", "", "");
m_Code128.Rows.Add("", "!", "!", "", "");
m_Code128.Rows.Add("", "\"", "\"", "", "");
m_Code128.Rows.Add("", "#", "#", "", "");
m_Code128.Rows.Add("", "$", "$", "", "");
m_Code128.Rows.Add("", "%", "%", "", "");
m_Code128.Rows.Add("", "&", "&", "", "");
m_Code128.Rows.Add("", "'", "'", "", "");
m_Code128.Rows.Add("", "(", "(", "", "");
m_Code128.Rows.Add("", ")", ")", "", "");
m_Code128.Rows.Add("", "*", "*", "", "");
m_Code128.Rows.Add("", "+", "+", "", "");
m_Code128.Rows.Add("", ",", ",", "", "");
m_Code128.Rows.Add("", "-", "-", "", "");
m_Code128.Rows.Add("", ".", ".", "", "");
m_Code128.Rows.Add("", "/", "/", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", "", "", "", "");
m_Code128.Rows.Add("", ":", ":", "", "");
m_Code128.Rows.Add("", ";", ";", "", "");
m_Code128.Rows.Add("", "<", "<", "", "");
m_Code128.Rows.Add("", "=", "=", "", "");
m_Code128.Rows.Add("", ">", ">", "", "");
m_Code128.Rows.Add("", "?", "?", "", "");
m_Code128.Rows.Add("", "@", "@", "", "");
m_Code128.Rows.Add("", "A", "A", "", "");
m_Code128.Rows.Add("", "B", "B", "", "");
m_Code128.Rows.Add("", "C", "C", "", "");
m_Code128.Rows.Add("", "D", "D", "", "");
m_Code128.Rows.Add("", "E", "E", "", "");
m_Code128.Rows.Add("", "F", "F", "", "");
m_Code128.Rows.Add("", "G", "G", "", "");
m_Code128.Rows.Add("", "H", "H", "", "");
m_Code128.Rows.Add("", "I", "I", "", "");
m_Code128.Rows.Add("", "J", "J", "", "");
m_Code128.Rows.Add("", "K", "K", "", "");
m_Code128.Rows.Add("", "L", "L", "", "");
m_Code128.Rows.Add("", "M", "M", "", "");
m_Code128.Rows.Add("", "N", "N", "", "");
m_Code128.Rows.Add("", "O", "O", "", "");
m_Code128.Rows.Add("", "P", "P", "", "");
m_Code128.Rows.Add("", "Q", "Q", "", "");
m_Code128.Rows.Add("", "R", "R", "", "");
m_Code128.Rows.Add("", "S", "S", "", "");
m_Code128.Rows.Add("", "T", "T", "", "");
m_Code128.Rows.Add("", "U", "U", "", "");
m_Code128.Rows.Add("", "V", "V", "", "");
m_Code128.Rows.Add("", "W", "W", "", "");
m_Code128.Rows.Add("", "X", "X", "", "");
m_Code128.Rows.Add("", "Y", "Y", "", "");
m_Code128.Rows.Add("", "Z", "Z", "", "");
m_Code128.Rows.Add("", "[", "[", "", "");
m_Code128.Rows.Add("", "\\", "\\", "", "");
m_Code128.Rows.Add("", "]", "]", "", "");
m_Code128.Rows.Add("", "^", "^", "", "");
m_Code128.Rows.Add("", "_", "_", "", "");
m_Code128.Rows.Add("", "NUL", "`", "", "");
m_Code128.Rows.Add("", "SOH", "a", "", "");
m_Code128.Rows.Add("", "STX", "b", "", "");
m_Code128.Rows.Add("", "ETX", "c", "", "");
m_Code128.Rows.Add("", "EOT", "d", "", "");
m_Code128.Rows.Add("", "ENQ", "e", "", "");
m_Code128.Rows.Add("", "ACK", "f", "", "");
m_Code128.Rows.Add("", "BEL", "g", "", "");
m_Code128.Rows.Add("", "BS", "h", "", "");
m_Code128.Rows.Add("", "HT", "i", "", "");
m_Code128.Rows.Add("", "LF", "j", "", "");
m_Code128.Rows.Add("", "VT", "k", "", "");
m_Code128.Rows.Add("", "FF", "I", "", "");
m_Code128.Rows.Add("", "CR", "m", "", "");
m_Code128.Rows.Add("", "SO", "n", "", "");
m_Code128.Rows.Add("", "SI", "o", "", "");
m_Code128.Rows.Add("", "DLE", "p", "", "");
m_Code128.Rows.Add("", "DC1", "q", "", "");
m_Code128.Rows.Add("", "DC2", "r", "", "");
m_Code128.Rows.Add("", "DC3", "s", "", "");
m_Code128.Rows.Add("", "DC4", "t", "", "");
m_Code128.Rows.Add("", "NAK", "u", "", "");
m_Code128.Rows.Add("", "SYN", "v", "", "");
m_Code128.Rows.Add("", "ETB", "w", "", "");
m_Code128.Rows.Add("", "CAN", "x", "", "");
m_Code128.Rows.Add("", "EM", "y", "", "");
m_Code128.Rows.Add("", "SUB", "z", "", "");
m_Code128.Rows.Add("", "ESC", "{", "", "");
m_Code128.Rows.Add("", "FS", "|", "", "");
m_Code128.Rows.Add("", "GS", "}", "", "");
m_Code128.Rows.Add("", "RS", "~", "", "");
m_Code128.Rows.Add("", "US", "DEL", "", "");
m_Code128.Rows.Add("", "FNC3", "FNC3", "", "");
m_Code128.Rows.Add("", "FNC2", "FNC2", "", "");
m_Code128.Rows.Add("", "SHIFT", "SHIFT", "", "");
m_Code128.Rows.Add("", "CODEC", "CODEC", "", "");
m_Code128.Rows.Add("", "CODEB", "FNC4", "CODEB", "");
m_Code128.Rows.Add("", "FNC4", "CODEA", "CODEA", "");
m_Code128.Rows.Add("", "FNC1", "FNC1", "FNC1", "");
m_Code128.Rows.Add("", "StartA", "StartA", "StartA", "");
m_Code128.Rows.Add("", "StartB", "StartB", "StartB", "");
m_Code128.Rows.Add("", "StartC", "StartC", "StartC", "");
m_Code128.Rows.Add("", "Stop", "Stop", "Stop", "");
#endregion
}
/// <summary>
/// 获取128图形
/// </summary>
/// <param name="p_Text">文字</param>
/// <param name="p_Code">编码</param>
/// <returns>图形</returns>
public Bitmap GetCodeImage(string p_Text, Encode p_Code)
{
string _ViewText = p_Text;
string _Text = "";
IList<int> _TextNumb = new List<int>();
int _Examine = ; //首位
switch (p_Code)
{
case Encode.Code128C:
_Examine = ;
if (!((p_Text.Length & ) == )) throw new Exception("128C长度必须是偶数");
while (p_Text.Length != )
{
int _Temp = ;
try
{
int _CodeNumb128 = Int32.Parse(p_Text.Substring(, ));
}
catch
{
throw new Exception("128C必须是数字!");
}
_Text += GetValue(p_Code, p_Text.Substring(, ), ref _Temp);
_TextNumb.Add(_Temp);
p_Text = p_Text.Remove(, );
}
break;
case Encode.EAN128:
_Examine = ;
if (!((p_Text.Length & ) == )) throw new Exception("EAN128长度必须是偶数");
_TextNumb.Add();
_Text += "";
while (p_Text.Length != )
{
int _Temp = ;
try
{
int _CodeNumb128 = Int32.Parse(p_Text.Substring(, ));
}
catch
{
throw new Exception("128C必须是数字!");
}
_Text += GetValue(Encode.Code128C, p_Text.Substring(, ), ref _Temp);
_TextNumb.Add(_Temp);
p_Text = p_Text.Remove(, );
}
break;
default:
if (p_Code == Encode.Code128A)
{
_Examine = ;
}
else
{
_Examine = ;
} while (p_Text.Length != )
{
int _Temp = ;
string _ValueCode = GetValue(p_Code, p_Text.Substring(, ), ref _Temp);
if (_ValueCode.Length == ) throw new Exception("无效的字符集!" + p_Text.Substring(, ).ToString());
_Text += _ValueCode;
_TextNumb.Add(_Temp);
p_Text = p_Text.Remove(, );
}
break;
}
if (_TextNumb.Count == ) throw new Exception("错误的编码,无数据");
_Text = _Text.Insert(, GetValue(_Examine)); //获取开始位 for (int i = ; i != _TextNumb.Count; i++)
{
_Examine += _TextNumb[i] * (i + );
}
_Examine = _Examine % ; //获得严效位
_Text += GetValue(_Examine); //获取严效位
_Text += ""; //结束位
Bitmap _CodeImage = GetImage(_Text);
GetViewText(_CodeImage, _ViewText);
return _CodeImage;
}
/// <summary>
/// 获取目标对应的数据
/// </summary>
/// <param name="p_Code">编码</param>
/// <param name="p_Value">数值 A b 30</param>
/// <param name="p_SetID">返回编号</param>
/// <returns>编码</returns>
private string GetValue(Encode p_Code, string p_Value, ref int p_SetID)
{
if (m_Code128 == null) return "";
DataRow[] _Row = m_Code128.Select(p_Code.ToString() + "='" + p_Value + "'");
if (_Row.Length != ) throw new Exception("错误的编码" + p_Value.ToString());
p_SetID = Int32.Parse(_Row[]["ID"].ToString());
return _Row[]["BandCode"].ToString();
}
/// <summary>
/// 根据编号获得条纹
/// </summary>
/// <param name="p_CodeId"></param>
/// <returns></returns>
private string GetValue(int p_CodeId)
{
DataRow[] _Row = m_Code128.Select("ID='" + p_CodeId.ToString() + "'");
if (_Row.Length != ) throw new Exception("验效位的编码错误" + p_CodeId.ToString());
return _Row[]["BandCode"].ToString();
}
/// <summary>
/// 获得条码图形
/// </summary>
/// <param name="p_Text">文字</param>
/// <returns>图形</returns>
private Bitmap GetImage(string p_Text)
{
char[] _Value = p_Text.ToCharArray();
int _Width = ;
for (int i = ; i != _Value.Length; i++)
{
_Width += Int32.Parse(_Value[i].ToString()) * (m_Magnify + );
}
Bitmap _CodeImage = new Bitmap(_Width, (int)m_Height);
Graphics _Garphics = Graphics.FromImage(_CodeImage);
//Pen _Pen;
int _LenEx = ;
for (int i = ; i != _Value.Length; i++)
{
int _ValueNumb = Int32.Parse(_Value[i].ToString()) * (m_Magnify + ); //获取宽和放大系数
if (!((i & ) == ))
{
//_Pen = new Pen(Brushes.White, _ValueNumb);
_Garphics.FillRectangle(Brushes.White, new Rectangle(_LenEx, , _ValueNumb, (int)m_Height));
}
else
{
//_Pen = new Pen(Brushes.Black, _ValueNumb);
_Garphics.FillRectangle(Brushes.Black, new Rectangle(_LenEx, , _ValueNumb, (int)m_Height));
}
//_Garphics.(_Pen, new Point(_LenEx, 0), new Point(_LenEx, m_Height));
_LenEx += _ValueNumb;
}
_Garphics.Dispose();
return _CodeImage;
}
/// <summary>
/// 显示可见条码文字 如果小于40 不显示文字
/// </summary>
/// <param name="p_Bitmap">图形</param>
private void GetViewText(Bitmap p_Bitmap, string p_ViewText)
{
if (m_ValueFont == null) return; Graphics _Graphics = Graphics.FromImage(p_Bitmap);
SizeF _DrawSize = _Graphics.MeasureString(p_ViewText, m_ValueFont);
if (_DrawSize.Height > p_Bitmap.Height - || _DrawSize.Width > p_Bitmap.Width)
{
_Graphics.Dispose();
return;
} int _StarY = p_Bitmap.Height - (int)_DrawSize.Height;
_Graphics.FillRectangle(Brushes.White, new Rectangle(, _StarY, p_Bitmap.Width, (int)_DrawSize.Height));
_Graphics.DrawString(p_ViewText, m_ValueFont, Brushes.Black, , _StarY);
} //12345678
//(105 + (1 * 12 + 2 * 34 + 3 * 56 + 4 *78)) % 103 = 47
//结果为starc +12 +34 +56 +78 +47 +end internal Image GetCodeImage(string p)
{
throw new NotImplementedException();
}
} }
}

128条码打印

说明:128条码打印不需要校验位,但与ean-13条码相比,128条码长度过长,有时会降低扫描的准确度

>> 39条码打印:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
using System.Drawing; namespace Frm.Common
{
public class createcode
{
#region 条形码 2014年9月12日11:27:57加 //對應碼表
public Hashtable Decode;
public Hashtable CheckCode;
//每個字元間的間隔符
private string SPARATOR = "";
public int LineHeight = ;
public int xCoordinate = ;//75; //條碼起始座標
public int WidthCU = ; //粗線和寬間隙寬度
public int WidthXI = ; //細線和窄間隙寬度
private int Height = ;
private int Width = ; #region 碼表
public void Inits()
{
Decode = new Hashtable();
#region 添加值
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("", "");
Decode.Add("A", "");
Decode.Add("B", "");
Decode.Add("C", "");
Decode.Add("D", "");
Decode.Add("E", "");
Decode.Add("F", "");
Decode.Add("G", "");
Decode.Add("H", "");
Decode.Add("I", "");
Decode.Add("J", "");
Decode.Add("K", "");
Decode.Add("L", "");
Decode.Add("M", "");
Decode.Add("N", "");
Decode.Add("O", "");
Decode.Add("P", "");
Decode.Add("Q", "");
Decode.Add("R", "");
Decode.Add("S", "");
Decode.Add("T", "");
Decode.Add("U", "");
Decode.Add("V", "");
Decode.Add("W", "");
Decode.Add("X", "");
Decode.Add("Y", "");
Decode.Add("Z", "");
Decode.Add("-", "");
Decode.Add("%", "");
Decode.Add("$", "");
Decode.Add("*", "");
#endregion
CheckCode = new Hashtable();
#region 添加值
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("", "");
CheckCode.Add("A", "");
CheckCode.Add("B", "");
CheckCode.Add("C", "");
CheckCode.Add("D", "");
CheckCode.Add("E", "");
CheckCode.Add("F", "");
CheckCode.Add("G", "");
CheckCode.Add("H", "");
CheckCode.Add("I", "");
CheckCode.Add("J", "");
CheckCode.Add("K", "");
CheckCode.Add("L", "");
CheckCode.Add("M", "");
CheckCode.Add("N", "");
CheckCode.Add("O", "");
CheckCode.Add("P", "");
CheckCode.Add("Q", "");
CheckCode.Add("R", "");
CheckCode.Add("S", "");
CheckCode.Add("T", "");
CheckCode.Add("U", "");
CheckCode.Add("V", "");
CheckCode.Add("W", "");
CheckCode.Add("X", "");
CheckCode.Add("Y", "");
CheckCode.Add("Z", "");
CheckCode.Add("-", "");
CheckCode.Add(".", "");
CheckCode.Add(",", "");
CheckCode.Add("$", "");
CheckCode.Add("/", "");
CheckCode.Add("+", "");
CheckCode.Add("%", "");
#endregion
}
#endregion //保存檔
public Bitmap CreateBarImage(string Code, int UseCheck, int ValidateCode)
{
string code39 = Encode39(Code, UseCheck, ValidateCode);
if (code39 != null)
{
Bitmap saved = new Bitmap(, );
//Bitmap saved = new Bitmap(200, 80);
Graphics g = Graphics.FromImage(saved);
g.FillRectangle(new SolidBrush(Color.White), , , this.Width, this.Height);
this.DrawBarCode39(code39, g);
//string filename = Server.MapPath("\\DesktopModules\\HospitalCare\\Images\\" + Code + ".jpg");
string filename = "d:\\" + Code + ".jpg";
return saved; }
else
{
return null;
}
} ////保存檔
//public void saveFile(string Code, int UseCheck, int ValidateCode)
//{
// string code39 = Encode39(Code, UseCheck, ValidateCode);
// if (code39 != null)
// {
// Bitmap saved = new Bitmap(this.Width, this.Height);
// //Bitmap saved = new Bitmap(200, 80);
// Graphics g = Graphics.FromImage(saved);
// g.FillRectangle(new SolidBrush(Color.White), 0, 0, this.Width, this.Height);
// this.DrawBarCode39(code39, g);
// //string filename = Server.MapPath("\\DesktopModules\\HospitalCare\\Images\\" + Code + ".jpg");
// string filename = "d:\\" + Code + ".jpg";
// try
// {
// saved.Save(filename, ImageFormat.Jpeg);
// }
// catch
// {
// //Response.Write("<script>alert('错了!');</script>");
// MessageBox.Show("请在本机D盘下建立TXM目录", "错误提示", MessageBoxButtons.OK);
// }
// saved.Dispose();
// }
//} private string Encode39(string Code, int UseCheck, int ValidateCode)
{
int UseStand = ; //檢查輸入待編碼字元是否為標準格式(是否以*開始結束) //保存備份資料
string originalCode = Code; //為空不進行編碼
if (null == Code || Code.Trim().Equals(""))
{
return null;
}
//檢查錯誤字元
Code = Code.ToUpper(); //轉為大寫
Regex rule = new Regex(@"[^0-9A-Z%$\-*]");
if (rule.IsMatch(Code))
{
MessageBox.Show("編碼中包含非法字元,目前僅支援字母,數位及%$-*符號!!"); //MessageBox.Show("編碼中包含非法字元,目前僅支援字母,數位及%$-*符號!!");
return null;
}
//計算檢查碼
if (UseCheck == )
{
int Check = ;
//累計求和
for (int i = ; i < Code.Length; i++)
{
Check += int.Parse((string)CheckCode[Code.Substring(i, )]);
}
//取模
Check = Check % ;
//附加檢測碼
if (ValidateCode == )
{
foreach (DictionaryEntry de in CheckCode)
{
if ((string)de.Value == Check.ToString())
{
Code = Code + (string)de.Key;
break;
}
}
}
}
//標準化輸入字元,增加起始標記
if (UseStand == )
{
if (Code.Substring(, ) != "*")
{
Code = "*" + Code;
}
if (Code.Substring(Code.Length - , ) != "*")
{
Code = Code + "*";
}
}
//轉換成39編碼
string Code39 = string.Empty;
for (int i = ; i < Code.Length; i++)
{
Code39 = Code39 + (string)Decode[Code.Substring(i, )] + SPARATOR;
} int height = + LineHeight;//定義圖片高度
int width = xCoordinate;
for (int i = ; i < Code39.Length; i++)
{
if ("".Equals(Code39.Substring(i, )))
{
width += WidthXI;
}
else
{
width += WidthCU;
}
}
this.Width = width + xCoordinate;
this.Height = height; return Code39;
}
private void DrawBarCode39(string Code39, Graphics g)
{
//int UseTitle = 1; //條碼上端顯示標題
//int UseTTF = 1; //使用TTF字體,方便顯示中文,需要$UseTitle=1時才能生效
//if (Title.Trim().Equals(""))
//{
// UseTitle = 0;
//}
Pen pWhite = new Pen(Color.White, );
Pen pBlack = new Pen(Color.Black, );
int position = xCoordinate;
//顯示標題
//if (UseTitle == 1)
//{
// Font TitleFont = new Font("Arial", 8, FontStyle.Regular);
// SizeF sf = g.MeasureString(Title, TitleFont);
// g.DrawString(Title, TitleFont, Brushes.Black, (Width - sf.Width) / 2, 5);
//}
for (int i = ; i < Code39.Length; i++)
{
//繪製條線
if ("".Equals(Code39.Substring(i, )))
{
for (int j = ; j < WidthXI; j++)
{
g.DrawLine(pBlack, position + j, , position + j, + LineHeight);
}
position += WidthXI;
}
else
{
for (int j = ; j < WidthCU; j++)
{
g.DrawLine(pBlack, position + j, , position + j, + LineHeight);
}
position += WidthCU;
}
i++;
//繪製間隔線
if ("".Equals(Code39.Substring(i, )))
{
position += WidthXI;
}
else
{
position += WidthCU;
}
}
return;
}
#endregion }
}

39条码打印

winform 打印条码的更多相关文章

  1. C# WinForm程序打印条码 Code39码1

    做WinForm程序需要打印条码,为了偷懒不想自己写生成条码的程序在网上下载一个标准的39码的字体,在程序里面换上这个条码字体即可打印条码了. 最重要的一点作为记录: 如果想把“123456789”转 ...

  2. Navi.Soft30.框架.WinForm.开发手册

    阅读导航 Navi.Soft30.Core类库.开发手册 http://www.cnblogs.com/xiyang1011/p/5709489.html Navi.Soft30.框架.WinForm ...

  3. Navi.Soft31.WinForm框架(含下载地址)

    1概述 1.1应用场景 尽管互联网高速发展,互联网软件也随之越来越多,但桌面应用程序在某些领域中还是不可替代,如MIS,ERP,CRM等软件产品,同时,这类软件均包括一些通用的功能,如:与数据库操作, ...

  4. 使用 .NET WinForm 开发所见即所得的 IDE 开发环境,实现不写代码直接生成应用程序

    直接切入正题,这是我09年到11年左右业余时间编写的项目,最初的想法很简单,做一个能拖拖拽拽就直接生成应用程序的工具,不用写代码,把能想到的业务操作全部封装起来,通过配置的方式把这些业务操作组织起来运 ...

  5. 逆天通用水印支持Winform,WPF,Web,WP,Win10。支持位置选择(9个位置 ==》[X])

    常用技能:http://www.cnblogs.com/dunitian/p/4822808.html#skill 逆天博客:http://dnt.dkil.net 逆天通用水印扩展篇~新增剪贴板系列 ...

  6. 【基于WinForm+Access局域网共享数据库的项目总结】之篇一:WinForm开发总体概述与技术实现

    篇一:WinForm开发总体概述与技术实现 篇二:WinForm开发扇形图统计和Excel数据导出 篇三:Access远程连接数据库和窗体打包部署 [小记]:最近基于WinForm+Access数据库 ...

  7. winform 窗体圆角设计

    网上看到的很多winform窗体圆角设计代码都比较累赘,这里分享一个少量代码就可以实现的圆角.主要运用了System.Drawing.Drawing2D. 效果图 代码如下. private void ...

  8. WinForm设置控件焦点focus

    winform窗口打开后文本框的默认焦点设置,进入窗口后默认聚焦到某个文本框,两种方法: ①设置tabindex 把该文本框属性里的tabIndex设为0,焦点就默认在这个文本框里了. ②Winfor ...

  9. MVC还是MVVM?或许VMVC更适合WinForm客户端

    最近开始重构一个稍嫌古老的C/S项目,原先采用的技术栈是『WinForm』+『WCF』+『EF』.相对于现在铺天盖地的B/S架构来说,看上去似乎和Win95一样古老,很多新入行的,可能就没有见过经典的 ...

随机推荐

  1. iOS:多线程NSThread的详细使用

    NSThread具体使用:直接继承NSObject NSThread:. 优点:NSThread 是轻量级的,使用简单 缺点:需要自己管理线程的生命周期.线程同步.线程同步对数据的加锁会有一定的系统开 ...

  2. jQuery最佳实践:如何用好jQuery

    一.用对选择器 在jQuery中,你可以用多种选择器,选择同一个网页元素.每种选择器的性能是不一样的,你应该了解它们的性能差异. (1)最快的选择器:id选择器和元素标签选择器 举例来说,下面的语句性 ...

  3. 【笔记】探索js 的this 对象 (第三部分)

    了解完函数的调用区域是如何影响this 对象的,还有this 的各种绑定方式以及各种绑定方式的优先级后 最后一部分,来了解一下this 的一些例外情况 1.被忽略的this 例如在使用bind 方法时 ...

  4. PAAS云服务平台

    云计算是一种可以方便.按需从网络訪问的.可配置的.共享的资源池(如网络.server.存储.应用程序和服务)模型,且仅仅需最少的管理(服务提供方交互)就可以高速供应和公布该模型. 云计算平台的核心部分 ...

  5. 一个Tomcat配置参数引发的血案

    转载:https://mp.weixin.qq.com/s/3IuTcDCTB3yIovp6o_vuKA 一.现象 有用户反馈访问PC首页偶尔会出现白页情况,也偶尔会收到听云的报警短信 二.监控(听云 ...

  6. java实现快速排序算法

    1.算法概念. 快速排序(Quicksort)是对冒泡排序的一种改进.由C. A. R. Hoare在1962年提出.2.算法思想. 通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据 ...

  7. vector iterator not incrementable For information on how your program can cause an an assertion Failure, see the Visual c + + documentation on asserts

    #include <list> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { list<int> sl ...

  8. 在单进程单线程或单进程多线程下实现log4cplus写日志并按大小切割

    基于脚本配置来过滤log信息 除了通过程序实现对log环境的配置之外.log4cplus通过PropertyConfigurator类实现了基于脚本配置的功能.通过 脚本能够完毕对logger.app ...

  9. 如何使用WinDriver为PCIe采集卡装驱动

    如何使用WinDriver为PCIe采集卡装驱动 第一步:使用WinDriver生成驱动 1.运行Drier Wizard 2.点击New host driverproject 3.在列表中,选择待安 ...

  10. Linux配置虚拟主机后,只能访问到主页怎么办?

    Linux配置虚拟主机后,只能访问到主页怎么办? 今天配置了lamp后,添加了一个虚拟主机,配置http.conf后,增加虚拟主机,测试访问发现只有域名下能访问,ljt.com但是域名下所有的都访问不 ...