【发布时间】:2020-08-04 11:54:23
【问题描述】:
我正在使用 Zen Barcode Rendering Framework 在 C# windows 窗体应用程序中创建条形码。我有两个文本框(一个用于条形码本身,一个用于我希望将其打印在条形码标签上的相关文本)。同样,我将生成的条形码图像加载到图片框并尝试打印,但每次按下打印按钮时,结果都不合适(有时打印机会打印一个白色的空标签,有时条形码打印不完整。有趣的是,我不得不说,为了让条形码即使看起来不完整也能出现在标签上,我不得不选择非常大的纸张尺寸)。这是我的代码:
我的生成条码按钮的点击事件代码:
private void Button1_Click(object sender, EventArgs e)
{
string barcode = textBox1.Text;
Zen.Barcode.Code128BarcodeDraw brcd = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
var barcodeImage = brcd.Draw(barcode, 50);
int resultImageWidth;
if(barcodeImage.Width >= textBox2.Text.Length*8)
{
resultImageWidth = barcodeImage.Width;
}
else
{
resultImageWidth = textBox2.Text.Length*8;
}
var resultImage = new Bitmap(resultImageWidth, barcodeImage.Height + 60); // 20 is bottom padding, adjust to your text
using (var graphics = Graphics.FromImage(resultImage))
using (var font = new Font("IranYekan", 10))
using (var brush = new SolidBrush(Color.Black))
using (var format = new StringFormat()
{
Alignment = StringAlignment.Center, // Also, horizontally centered text, as in your example of the expected output
LineAlignment = StringAlignment.Far
})
{
graphics.Clear(Color.White);
graphics.DrawImage(barcodeImage, (resultImageWidth - barcodeImage.Width)/2, 0);
graphics.DrawString(textBox1.Text, font, brush, resultImage.Width / 2, resultImage.Height-30, format);
graphics.DrawString(textBox2.Text, font, brush, resultImage.Width / 2, resultImage.Height, format);
}
pictureBox1.Image = resultImage;
}
我的打印按钮点击事件的代码:
private void Button2_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
PrintDocument doc = new PrintDocument();
doc.PrintPage += Doc_PrintPage;
pd.Document = doc;
if (pd.ShowDialog() == DialogResult.OK)
{
doc.Print();
}
}
还有我的 Doc_PrintPage() 函数:
private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(bm, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
e.Graphics.DrawImage(bm, 0, 0);
bm.Dispose();
}
我的主要目标是在打印对话框出现时将其相关文本完全打印在纸张边界内。
【问题讨论】:
-
确保您安装了供应商的最新驱动程序。您是连接到打印机 IP 还是使用打印驱动程序?您应该始终使用初始化打印机并配置选项的打印驱动程序。
-
@jdweng 因为我已经安装了打印驱动程序,我只需从可用打印机列表中选择我的打印机,然后在设置适当的纸张尺寸后,我点击打印对话框上的确定。
-
驱动程序是否有适合纸张大小的选项。我会创建一个面板,然后将图片框和文本放入面板并打印面板。
-
据我所知,没有。
标签: c# winforms barcode picturebox barcode-printing