C # generate a barcode

Source: Internet
Author: User

C # generate a barcode

C # Use Zxing.net to generate barcode and QR code and print them

Opening part:Zxing.net is a tool for compiling bar codes and QR codes on the. net platform.

:Http://pan.baidu.com/s/1i3BXPLN

Step 1: Use VS2010 to create a form program project:

Step 2: add three classes: BarCodeClass. cs, DocementBase. cs, and imageDocument. cs. (Paste the code of these classes in the Next Step); Add the downloaded referenceZxing. dll.

Note:

1 BarCodeClass. cs is mainly used to generate and parse barcode and QR code.

DocementBase. cs and imageDocument. cs are used to print the generated barcode and QR code.

Step 3: write the code for the three classes in the previous step:

"BarCodeClass. cs

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using ZXing. Common;

Using ZXing;

Using System. Windows. Forms;

Using System. Drawing;

Using System. Text. RegularExpressions;

Using ZXing. QrCode;

Namespace BarCode

{

Class BarCodeClass

{

///

/// Generate a barcode

///

///

///

Public void CreateBarCode (PictureBoxpictureBox1, string Contents)

{

Regexrg = new Regex ("^ [0-9] {12} $ ");

If (! Rg. IsMatch (Contents ))

{

MessageBox. Show ("this example uses EAN_13 encoding and requires 12 digits ");

Return;

}

EncodingOptionsoptions = null;

BarcodeWriterwriter = null;

Options = newEncodingOptions

{

Width = pictureBox1.Width,

Height = pictureBox1.Height

};

Writer = newBarcodeWriter ();

Writer. Format = BarcodeFormat. ITF;

Writer. Options = options;

Bitmapbitmap = writer. Write (Contents );

PictureBox1.Image = bitmap;

}

///

/// Generate a QR code

///

///

///

Public void CreateQuickMark (PictureBoxpictureBox1, string Contents)

{

If (Contents = string. Empty)

{

MessageBox. Show ("the input content cannot be blank! ");

Return;

}

EncodingOptionsoptions = null;

BarcodeWriterwriter = null;

Options = newQrCodeEncodingOptions

{

DisableECI = true,

CharacterSet = "UTF-8 ",

Width = pictureBox1.Width,

Height = pictureBox1.Height

};

Writer = newBarcodeWriter ();

Writer. Format = BarcodeFormat. QR_CODE;

Writer. Options = options;

Bitmapbitmap = writer. Write (Contents );

PictureBox1.Image = bitmap;

}

///

/// Decoding

///

///

Public void Decode (PictureBoxpictureBox1)

{

BarcodeReaderreader = new BarcodeReader ();

Resultresult = reader. Decode (Bitmap) pictureBox1.Image );

}

}

}

DocementBase. cs

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Drawing. Printing;

Using System. Drawing;

Using System. Windows. Forms;

Namespace BarCode

{

Class DocementBase: PrintDocument

{

// Fields

Public Font = new Font ("Verdana", 10, GraphicsUnit. Point );

// Preview and print

Public DialogResult showPrintPreviewDialog ()

{

PrintPreviewDialogdialog = new PrintPreviewDialog ();

Dialog. Document = this;

Returndialog. ShowDialog ();

}

// Set and print

Public DialogResult ShowPageSettingsDialog ()

{

PageSetupDialogdialog = new PageSetupDialog ();

Dialog. Document = this;

Returndialog. ShowDialog ();

}

}

}

"ImageDocument. cs

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Drawing;

Using System. Drawing. Printing;

Namespace BarCode

{

Class imageDocument: DocementBase

{

PrivateImage _ Image;

Public Image

{

Get

{

Return_Image;

}

Set

{

_ Image = value;

If (_ Image! = Null)

{

If (_ Image. Size. Width> _ Image. Size. Height)

DefaultPageSettings. Landscape = true;

Else

DefaultPageSettings. Landscape = false;

}

}

}

PublicimageDocument ()

{

}

PublicimageDocument (Image image)

{

This. Image = image;

}

Protectedoverrisponidonprintpage (PrintPageEventArgs e)

{

If (Image = null)

{

ThrownewInvalidOperationException ();

}

RectanglebestFit = GetBestFitRectangle (e. MarginBounds, Image. Size );

E. Graphics. DrawImage (Image, bestFit );

E. Graphics. DrawRectangle (Pens. Black, bestFit );

E. Graphics. DrawRectangle (Pens. Black, e. MarginBounds );

}

// Keep height ratio: the parameter is (the Rectangularle object of the print boundary and the Size object of the image Size)

ProtectedRectangle GetBestFitRectangle (Rectangle toContain, SizeobjectSize)

{

// Check whether the page is horizontal or vertical.

BoolcontainerLandscape = false;

If (toContain. Width> toContain. Height)

ContainerLandscape = true;

// Height ratio = Image Height/Image Width

FloataspectRatio = (float) objectSize. Height/(float) objectSize. Width;

// Obtain the coordinates in the upper left corner of the page.

IntmidContainerX = toContain. Left + (toContain. Width/2 );

IntmidContainerY = toContain. Top + (toContain. Height/2 );

Intx1 = 0, x2 = 0, y1 = 0, y2 = 0;

If (containerLandscape = false)

{

// Vertical image

X1 = toContain. Left;

X2 = toContain. Right;

// Adjusted height

IntadjustedHeight = (int) (float) toContain. Width * aspectRatio );

Y1 = midContainerY-(adjustedHeight/2 );

Y2 = y1 + adjustedHeight;

}

Else

{

Y1 = toContain. Top;

Y2 = toContain. Bottom;

// Adjusted height

IntadjustedWidth = (int) (float) toContain. Height/aspectRatio );

X1 = midContainerX-(adjustedWidth/2 );

X2 = x1 + adjustedWidth;

}

ReturnnewRectangle (x1, y1, x2-x1, y2-y1 );

}

}

}

Step 4: Modify the interface.

Step 5: Double-Click Generate barcode, generate QR code, decode, and print To Go To The Click Event and write background code. Here we will not describe how to implement it one by one. For the code, refer to the next step:


Step 6: paste all the code of the form.

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Drawing;

Using System. Linq;

Using System. Text;

Using System. Windows. Forms;

Using System. Text. RegularExpressions;

Using ZXing;

Using ZXing. QrCode. Internal;

Using ZXing. Common;

Using System. IO;

Using ZXing. QrCode;

Namespace BarCode

{

Public partial class Main: Form

{

PublicMain ()

{

InitializeComponent ();

}

Private BarCodeClass bcc = newBarCodeClass ();

Private DocementBase _ docement;

// Generate a barcode

Privatevoid button#click (objectsender, EventArgs e)

{

Bcc. CreateBarCode (pictureBox1, txtMsg. Text );

}

// Generate a QR code

Privatevoid button2_Click (objectsender, EventArgs e)

{

Bcc. CreateQuickMark (pictureBox1, txtMsg. Text );

}

Privatevoid Form1_Load (objectsender, EventArgs e)

{

TxtMsg. Text = System. DateTime. Now. ToString ("yyyyMMddhhmmss"). Substring (0, 12 );

}

// Decoding

Privatevoid button4_Click (objectsender, EventArgs e)

{

If (pictureBox1.Image = null)

{

MessageBox. Show ("Enter the image before decoding! ");

Return;

}

BarcodeReaderreader = new BarcodeReader ();

Resultresult = reader. Decode (Bitmap) pictureBox1.Image );

MessageBox. Show (result. Text );

}

// Print

Privatevoid button3_Click (objectsender, EventArgs e)

{

If (pictureBox1.Image = null)

{

MessageBox. Show ("You Must Load an Image first! ");

Return;

}

Else

{

_ Docement = new imageDocument (pictureBox1.Image );

}

_ Docement. showPrintPreviewDialog ();

}

}

}

Step 7: The rest is the demonstration: The local demonstration result is as follows:

Run the program: Click Generate barcode. The result is as follows:

Click "decoding". The result is as follows:

Click print. The result is as follows:

Click Generate QR code. The result is as follows:

Click "decoding". The result is as follows:


Click print. The result is as follows:

Conclusion: If you have any shortcomings, please criticize them.

(Share happiness !!!)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.