一个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条码打印

最新文章

  1. C#中分割字符串输出字符数组
  2. Win 10 UWP开发系列:设置AppBarButton的图标
  3. C#中Dictionary&lt;TKey,TValue&gt;排序方式
  4. SAP (ABAP) 常用的数学函数
  5. 简述oracle视图
  6. asp.net实现通用水晶报表
  7. vc调用BCB的dll 参数传递 报错
  8. 【IOS学习基础】weak和strong、懒加载、循环引用
  9. 利用宏定义令iOS项目当中的NSLog不执行
  10. java.lang.Math类,方法学习笔记
  11. 用golang写的 分解x86 intel boot/recovery工具
  12. 在JBuilder8中使用ANT
  13. 接口调用 GET方式
  14. MVC框架中,遇到 [程序集清单定义与程序集引用不匹配]怎么办?
  15. [Python Study Notes]电池信息
  16. 『性能』ServiceStack.Redis 和 StackExchange.Redis 性能比较
  17. VS2013 密钥– 所有版本
  18. Favorite Donut(HDU 5442)最小表示法+二分
  19. cmd快速设置本机ip和dns【转】
  20. js 模拟css3 动画1

热门文章

  1. Android Studio 之 NDK篇
  2. ISP图像调试工程师——自动白平衡(熟悉3A算法)
  3. 字符编码,pyton中的encode,decode,unicode()
  4. 小凡带你搭建本地的光盘yum源
  5. 用好Git 和 SVN,轻松驾驭版本管理
  6. elasticsearch java客户端api使用(一)
  7. 《大话操作系统——做坚实的project实践派》(5)
  8. 疯狂java学习路线图
  9. LightOj 1221 - Travel Company(spfa判负环)
  10. mui ajax方法