I create a barcode with the value entered in the Winforms application and print it with the printer. Afterwards, when I want to scan it with a barcode reader, I cannot scan it. This is my code:
private void GenerateBarcodeButton_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(textBox1.Text))
{
pictureBox1.Image = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum.Draw(textBox1.Text, 50, 2);
}
else
{
MessageBox.Show("Please enter the barcode number you want to generate.");
}
}
public void PrintPicture(object sender, PrintPageEventArgs e)
{
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
// bmp.SetResolution(203, 203);
pictureBox1.DrawToBitmap(bmp, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
e.Graphics.DrawImage(bmp, 20, 20, new System.Drawing.RectangleF(0, 0, bmp.Width, bmp.Height), System.Drawing.GraphicsUnit.Pixel);
}
private void Print_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
PrintDocument pDoc = new PrintDocument();
pDoc.PrintPage = PrintPicture;
pd.Document = pDoc;
if (pd.ShowDialog() == DialogResult.OK)
{
pDoc.Print();
}
}
The printer model I use for printing is Godex G300. Where did I go wrong?
CodePudding user response:
There is at least one major issue in your code, refer to this Microsoft documentation page to understand how exactly it's done.
When you assign an event handler for PrintPage()
, you should wrap it inside a PrintPageEventHandler
like this:
pDoc.PrintPage = new PrintPageEventHandler (this.PrintPicture);
Try doing the above and if it doesn't work, debug it by putting an actual breakpoint inside the PrintPicture()
method.
CodePudding user response:
The problem was that I didn't set the DPI. I added this line to the code.
bmp.SetResolution(203, 203);
This is the new method:
private void PrintPicture(object sender, PrintPageEventArgs e)
{
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
bmp.SetResolution(203, 203);
pictureBox1.DrawToBitmap(bmp, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
e.Graphics.DrawImage(bmp, 38, 10);
bmp.Dispose();
}