2014-04-05 45 views
1

我制作了Windows窗体应用程序,我想用条形码生成交货单。我嵌入了条形码字体,但出现错误。看到这个问题:Embed Barcode in C# PDF Library图像上的C#条形码太厚

现在,我想从条形码制作图像并将此图像嵌入到我的送货单上。我已经搜索在谷歌这样做,我发现下面的代码:

private Image DrawBarcodeAfleverbonImage(String text) 
    { 
     Font barcodeFont = new Font("Bar-Code 39", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); 
     //Font barcodeFont = new Font("Arial", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); 

     //first, create a dummy bitmap just to get a graphics object 
     Image img = new Bitmap(1, 1); 
     Graphics drawing = Graphics.FromImage(img); 

     //measure the string to see how big the image needs to be 
     SizeF textSize = drawing.MeasureString(text, barcodeFont); 

     //free up the dummy image and old graphics object 
     img.Dispose(); 
     drawing.Dispose(); 

     //create a new image of the right size 
     img = new Bitmap((int)textSize.Width, (int)textSize.Height); 

     drawing = Graphics.FromImage(img); 

     //create a brush for the text 
     Brush textBrush = new SolidBrush(Color.Black); 
     drawing.DrawString(text, barcodeFont, textBrush, 0, 0); 

     drawing.Save(); 
     img.Save(@"C:\Users\Marten\Documents\test.png"); 

     textBrush.Dispose(); 
     drawing.Dispose(); 

     return img; 

如果我跑我的程序中的图像将被创建。只是有一个问题:条形码字体过厚,所以我不能扫描:

enter image description here

有什么不对?

+0

减小字体大小,它会工作... 31到10可能吗? – fixagon

+0

我试过了,但是不行。现在我有一个小图像,全黑。 – Marten

回答

1

您需要绘制文本之前,设置背景颜色:

drawing.Clear(Color.White); 
drawing.DrawString(text, barcodeFont, textBrush, 0, 0); 

或者,如果你想有一个透明背景,你需要关闭字体平滑。

drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel; 
drawing.DrawString(text, barcodeFont, textBrush, 0, 0); 
+0

对不起,我迟到的回应,但它的作品!谢谢 ;) – Marten