Generate barcode with Free 3 of 9 font - c#

public Bitmap CreateBarcode(string data)
{
data = "55536";
string barcodeData = "*" + data + "*";
Bitmap barcode = new Bitmap(1, 1);
Font threeOfNine = new Font("Free 3 of 9 Extended", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
Font arial = new Font("Arial", 13,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point);
Graphics graphics = Graphics.FromImage(barcode);
SizeF dataSize = graphics.MeasureString(barcodeData, threeOfNine);
dataSize.Height = 70;
barcode = new Bitmap(barcode, dataSize.ToSize());
graphics = Graphics.FromImage(barcode);
graphics.Clear(Color.White);
graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(barcodeData, threeOfNine, new SolidBrush(Color.Black), 0, 0);
graphics.DrawString(data, arial, new SolidBrush(Color.Black), 50, 40);
graphics.Flush();
threeOfNine.Dispose();
graphics.Dispose();
return barcode;
}
I generate barcode with the above code, but my scanner can not read the barcode generated (for 55536).
BUT if I switch the data value to "1111" or "2222", then the barcode be read very well.
so I think it is not a scanner problem, anybody know, what's the wrong with that code?
please advice.

If you are using only numbers, you could try the 3 of 9 basic font (without the extended). Print the same barcode from Write and compare them to see if your solution is building the complete barcode or if it is getting truncated.

1.If you're using the supported characters surrounded by the "*" stop and start characters, chances are the problem is either the size of the barcode or the resolution of the printing.
2.Make sure that the size of each character is the same font size. Mixed sizes will not work.
3.When experimenting with changing the color of the bars, remember that darker colors are better. Pastels are not so good. Red is a no-no.
Here's a reference for you: asp.net barcode generator using 3 of 9 font.

try to prefix and suffix :
why are you passing the data within the
public Bitmap CreateBarcode(string data)
{
data="55536"; //dont pass the data from here pass it from outside method for eg. call it from the button click or whatever control you are using.
}

Related

Graphics drawstring UTF8 Chinese Characters

Preface: We sell machines that tell you the quality of the air. We have a touch screen display that we recently upgraded to support Chinese. I wrote a C# application that connects to the device serially and attempts to draw the screen so users can connect to their device remotely and control it. This works great until you put the device into Chinese, then my C# app draws all the symbols as their ASCII equivalent (not Chinese symbols).
I use the Graphics library to do all my drawing, in which I call the DrawString method to draw text on the screen. I have a picturebox in which I am doing the graphics drawing on. How do I draw the Chinese correctly?
Code:
private Bitmap image;
private Color gForeColor;
private Color gBackColor;
private Font gFont;
private int gTextsize;
private int gLineSize;
private StringFormat gTextAlign;
private void Initialize()
{
gForeColor = Color.Black;
gTextsize = 14;
gLineSize = 1;
gFont = new Font("Microsoft Sans Serif", gTextsize, FontStyle.Regular);
gTextAlign = new StringFormat();
gTextAlign.LineAlignment = StringAlignment.Center;
gTextAlign.Alignment = StringAlignment.Near;
gTextAlign.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
image = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}
private void DrawText(string Text, int X1, int Y1)
{
using (Graphics g = Graphics.FromImage(image))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
SolidBrush sb = new SolidBrush(gForeColor); //Foreground
SolidBrush bb = new SolidBrush(gBackColor); //Background
g.DrawString(Text, gFont, sb, X1, Y1, gTextAlign);
pictureBox1.Invalidate(); //refresh
gTextAlign.Alignment = StringAlignment.Near; //horizontal alignment reverts to Left after a text display command is issued
}
}
I tried adding this line
Text = Encoding.UTF8.GetString(Encoding.Default.GetBytes(Text)); To try and decode the text properly but now it prints '??????' instead of the ASCII letters or Chinese symbols.
Example:
English
Chinese
Edit: It seems the ReadExisting() from the SerialPort was converting all the bytes into '??????'. I stopped using ReadExisting and switched to Read which keeps the raw bytes. So now I'm getting the correct ASCII, but still not Chinese. I re-added my line Text = Encoding.UTF8.GetString(Encoding.Default.GetBytes(Text)); and now I'm getting Chinese with some extra symbols that aren't correct. Am I using the wrong encoding?
Are you sure, that you can use Microsoft Sans Serif with Chinese? I highly doubt.

Bold Font is Rendered Wrong

When I try to render a Chinese string like 试标记好不好 Graphics.DrawString draws it
even if I change the Font Linking to SimSun. On the other hand TextRenderer works but it fails to render readable strings when bold fonts are used. It seems there is no correct way to render bold strings.
The issue is described in greater detail here. Am I doing something wrong or does Windows not support professional looking localizable applications with some bold strings in the UI?
The code to repro the issue is for a Windows Forms application with two PictureBoxes:
const string combined = "测试标记好不好This is a aber long";
private void cFontSize_ValueChanged(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(750, 140);
Font f = new Font("Arial", (float)cFontSize.Value, IsBold ? FontStyle.Bold : FontStyle.Regular);
using (var g = Graphics.FromImage(bmp))
{
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
// Rendering with a Background Color solves the issue but
// this would produce boxes of white or black color in the displayed image which looks even worse
TextRenderer.DrawText(g, combined, f, new Point(0, 0), FontColor);
}
cPictureBox.Image = bmp;
Bitmap bmp2 = new Bitmap(750, 140);
using (var g = Graphics.FromImage(bmp2))
{
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
g.DrawString(combined, f, FontBrush, 0, 0);
}
cPicture2.Image = bmp2;
}
Update 1:
When I add as Font Link Setting to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink
Arial Bold
SIMSUNB.TTC,SimSun Bold
MSGOTHIC.TTC,MS UI Gothic
then Graphics.DrawString looks ok now althogh TextRender now gets problems. After restarting the application now both outputs look font wise ok although TextRenderer still has the problem that bold fonts become unreadable due to anti aliasing with black. I will restart the machine to check out any caching effects.

GraphicsUnit.Point or Pixel or world for printer?

i am making a desktop application using c# with VS2010 , the purpose of the app is to fill in a form (the form is a physical paper that has spaces in it) so my program has to print the text that i want in the exact place that i need it to be printed on.
my code goes like this:
private void urinePrintDocument_PrintPage(object sender,System.Drawing.Printing.PrintPageEventArgs e)
{
//## event handler for urine printing
string FieldValue = ""; // to hold the current text to be printed
SolidBrush BlackBrush = new SolidBrush(Color.Black);
Font MyFont = new Font("Arial", 12, GraphicsUnit.Point); //the font to be used
int myFontHeight = (int)(MyFont.GetHeight(e.Graphics));
int CurrentX, CurrentY;
//millimeter XXXX
//inch XXXXX
//display - error
//Document - very small
// 100 Pixel = 1 inch
//100 Point - 1 inch
// 100 world - 1 inch
CurrentX = 0;
CurrentY = 0;
FieldValue = ptName;
e.Graphics.DrawString(FieldValue, MyFont, BlackBrush, CurrentX, CurrentY);
CurrentX = 100;
CurrentY = 100;
FieldValue = ptFileNumber;
e.Graphics.DrawString(FieldValue, MyFont, BlackBrush, CurrentX, CurrentY);
}
my question is regarding the line
Font MyFont = new Font("Arial", 12, GraphicsUnit.Point); //the font to be used
specifically the GraphicsUnit.Point enumerator. we have got GraphicsUnit.Point ,millimeter ,inch,display ,Document,Pixel ,Point and world . i have tried them all and found that the last 3 print the text as expected and seem to "displace" the text one inch for each 100 units. i need my code to produce the same result on all type of printers is there any difference between the 3 ? and which one i should use to print on a printer?
Everything you draw to paper is automatically scaled to fit the printer resolution, it is not affected by font sizes at all. The default scaling is GraphUnit.Display, a scaling that maps 100 pixels to an inch, you already discovered it. It is a handy scaling mode since monitors are usually set to 96 dots per inch so everything you print will (almost) be the same size as it it shows on the screen.
The size of the font you create is only relevant to exactly where you draw text on paper. In other words, the PointF.Y value you pass to Graphics.DrawString(). You need to know the line spacing of the font in pixels, not points, use MyFont.Height.

Point of Sale Application Receipt Printing

I am working on a small project for a Retail Management Software, which will be using a POS printer (I think that's what we call it). I need a create a bill for it in the end. But i am stuck here, and not able to proceed. So suppose if I generate my bill in a separate form with appropriate dimensions (of width of POS bills), will i be able to print it properly?
I am using C# and .NET 4.0 framework. I don't have much knowledge about POS devices. I am working for really a small local client which needs a basic model of software. I am also a fresher so please help me out.
If my question is not clear, let me know i will try to elaborate my thought.
I know this is an old post, but for those still looking for a solution, I can tell you what I did.
After spending many hours messing with OPOS and POS for .Net, I ended up just abandoning those and just using the built-in System.Drawing.Printing libraries. The OPOS and POS for .Net ended up being a pain to get working and ultimately didn't work as well as the built-in libraries.
I'm using an Epson TM-T20II receipt printer.
Here's some code that worked well for me.
public static void PrintReceiptForTransaction()
{
PrintDocument recordDoc = new PrintDocument();
recordDoc.DocumentName = "Customer Receipt";
recordDoc.PrintPage += new PrintPageEventHandler(ReceiptPrinter.PrintReceiptPage); // function below
recordDoc.PrintController = new StandardPrintController(); // hides status dialog popup
// Comment if debugging
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "EPSON TM-T20II Receipt";
recordDoc.PrinterSettings = ps;
recordDoc.Print();
// --------------------------------------
// Uncomment if debugging - shows dialog instead
//PrintPreviewDialog printPrvDlg = new PrintPreviewDialog();
//printPrvDlg.Document = recordDoc;
//printPrvDlg.Width = 1200;
//printPrvDlg.Height = 800;
//printPrvDlg.ShowDialog();
// --------------------------------------
recordDoc.Dispose();
}
private static void PrintReceiptPage(object sender, PrintPageEventArgs e)
{
float x = 10;
float y = 5;
float width = 270.0F; // max width I found through trial and error
float height = 0F;
Font drawFontArial12Bold = new Font("Arial", 12, FontStyle.Bold);
Font drawFontArial10Regular = new Font("Arial", 10, FontStyle.Regular);
SolidBrush drawBrush = new SolidBrush(Color.Black);
// Set format of string.
StringFormat drawFormatCenter = new StringFormat();
drawFormatCenter.Alignment = StringAlignment.Center;
StringFormat drawFormatLeft = new StringFormat();
drawFormatLeft.Alignment = StringAlignment.Near;
StringFormat drawFormatRight = new StringFormat();
drawFormatRight.Alignment = StringAlignment.Far;
// Draw string to screen.
string text = "Company Name";
e.Graphics.DrawString(text, drawFontArial12Bold, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter);
y += e.Graphics.MeasureString(text, drawFontArial12Bold).Height;
text = "Address";
e.Graphics.DrawString(text, drawFontArial10Regular, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter);
y += e.Graphics.MeasureString(text, drawFontArial10Regular).Height;
// ... and so on
}
Hopefully it helps someone skip all the messing around with custom drivers. :)
Well I designed a POS application (in Delphi) and altough there are many little issues with printing a receipt or a bill it´s not rocket science. I just print a receipt by simply, well, printing like any other printer, the difference is that you send lines of 30-38 characters long (depending on the printer driver, font and size). To start, you could print using 2 methods: Sending Ascii characters and sending printer commands (to set the font style, color, etc) for that specific printer or the second method is to set the font, size, etc using C# like printing to any other normal/desktop printer.
You could try printing following the example of the page and my suggestions:
http://ondotnet.com/pub/a/dotnet/2002/06/24/printing.html

Huge Whitespace exists to right after drawing image. Want to get rid of it

I'm using the following codeproject to build an asp.net website and so far everything is good. My only problem is after the barcode is generated, a huge whitespace exist to the right of the barcode. I've been playing with this and am unable to resolve it.
Details below:
Link to Code Project Article: http://www.codeproject.com/KB/aspnet/AspBarCodes.aspx?msg=3543809
Copy of the Font is here: http://trussvillemethodist.web01.appliedi-labs.net/IDAutomationHC39M.ttf
//Working Path
string sWorkPath = "";
sWorkPath = this.Context.Server.MapPath("");
//Fonts
PrivateFontCollection fnts = new PrivateFontCollection();
fnts.AddFontFile(sWorkPath + #"\IDAutomationHC39M.ttf");
FontFamily fntfam = new FontFamily("IDAutomationHC39M", fnts);
Font oFont = new Font(fntfam, 18);
// Get the Requested code sent from the previous page.
string strCode = Request["code"].ToString();
//Graphics
//I don't know what to set the width to as I can't call the MeasureString without creating the Graphics object.
Bitmap oBitmaptemp = new Bitmap(40, 100);
Graphics oGraphicstemp = Graphics.FromImage(oBitmaptemp);
int w = (int)oGraphicstemp.MeasureString(strCode, oFont).Width + 4;
// Create a bitmap object of the width that we calculated and height of 100
Bitmap oBitmap = new Bitmap(w, 100);
// then create a Graphic object for the bitmap we just created.
Graphics oGraphics = Graphics.FromImage(oBitmap);
// Let's create the Point and Brushes for the barcode
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
// Now lets create the actual barcode image
// with a rectangle filled with white color
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
// We have to put prefix and sufix of an asterisk (*),
// in order to be a valid barcode
oGraphics.DrawString("*" + strCode + "*", oFont, oBrushWrite, oPoint);
// Then we send the Graphics with the actual barcode
Response.ContentType = "image/gif";
oBitmap.Save(Response.OutputStream, ImageFormat.Gif);
oBitmap.Dispose();
oGraphics.Dispose();
oBrush.Dispose();
oFont.Dispose();
The code just assumes 40 pixels per character, which is why you get a lot of image left on the right of the text. You can use the MeasureString method to measure the size of the text, and use that to create an image of the correct size:
int w = (int)oGraphics.MeasureString("*123$10.00*", oFont).Width + 4;
I noticed that you don't dispose any of the objects that you are using. The Graphics, Bitmap, SolidBrush and Font objects need to be disposed.
You might also want to consider using a GIF image instead of JPEG, it's more suited for this kind of graphics.

Categories