简单winform项目--实现打印功能(一)
作者:互联网
简单winform项目--实现打印功能(一)
新建项目
我用的是vs2019 .netframework4.5版本(用什么问题都不打)
在页面放置一个打印按钮
实现打印功能
添加引用
using System.Drawing.Printing;
using System.Drawing;
//按钮的点击事件
private void btnPrint_Click(object sender, EventArgs e)
{
string qd = "DASCOM DL-620Z";//打印机名称
var printDocument = new PrintDocument();
printDocument.PrinterSettings.PrinterName = qd;
printDocument.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
try
{
printDocument.Print();//打印功能关键
}
catch (InvalidPrinterException)
{
}
finally
{
printDocument.Dispose();
}
}
定义打印页面事件
这里主要是你打印页面的内容
using System.IO;
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Font titleFont = new Font("宋体", 9, FontStyle.Bold);//标题字体
Font fntTxt = new Font("宋体", 9, FontStyle.Regular);//正文文字
Brush brush = new SolidBrush(Color.Black);//画刷
Pen pen = new Pen(Color.Black);//线条颜色
Point po = new Point(1, 1);
Point poDraw = new Point(1, 60);
Graphics graphics = e.Graphics;//获取画布
Rectangle rectangle = new Rectangle(80, 10, 250, 175);
graphics.DrawRectangle(pen, rectangle);//打印一个正方形
//以下内容自定义(为了以后连接数据所用)
graphics.DrawString("winform测试标签", titleFont, brush, new Point(100, 8));
graphics.DrawString("编号:", fntTxt, brush, new Point(85,45));
graphics.DrawString("winform01", fntTxt, brush, new Point(170, 45));
graphics.DrawString("名称:", fntTxt, brush, new Point(85, 75));
graphics.DrawString("winform01", fntTxt, brush, new Point(170, 75));
graphics.DrawString("管理员:", fntTxt, brush, new Point(85, 105));
graphics.DrawString("winform01", fntTxt, brush, new Point(170, 105));
//此是为了释放打印的条码,之前是这届打印出来,但是没有关闭文件导致第二次打印的时候出现了问题。
using (var image = Image.FromFile(Application.StartupPath + CreateBarcode("winform1", 150, 55)))
{
e.Graphics.DrawImage(image, poDraw);
}
//打印结束删除本地存储的编码图片,避免本地存储图片过大。
File.Delete(Application.StartupPath + CreateBarcode(Barcode, 150, 55));
}
生成条形码的图片
生成条码需要安装NuGet包
搜索ZXing.Net安装即可
using using ZXing;
using ZXing.Common;
private string CreateBarcode(string content, int width, int height)
{
// 1.设置条形码规格
EncodingOptions encodeOption = new EncodingOptions();
encodeOption.Height = height; // 必须制定高度、宽度
encodeOption.Width = width;
// 2.生成条形码图片并保存
ZXing.BarcodeWriter wr = new BarcodeWriter();
wr.Options = encodeOption;
wr.Format = BarcodeFormat.CODE_128;
Bitmap img = wr.Write(content); // 生成图片
var dirpath = System.AppDomain.CurrentDomain.BaseDirectory + "barcode\\" + DateTime.Now.Year.ToString();
if (!Directory.Exists(dirpath))
Directory.CreateDirectory(dirpath);
string filePath = dirpath + "\\EAN_13-" + content + ".jpg";
string path = "/barcode/" + DateTime.Now.Year.ToString() + "/EAN_13-" + content + ".jpg";
using (Bitmap bitmap = img)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
return path;
}
}
}
完成这些就能实现简单的打印功能了下一章打算写的是使用Datagridview接受数据,选择数据内容进行打印。
下面是我打印的效果
标签:graphics,Point,--,打印,brush,using,new,winform 来源: https://www.cnblogs.com/stupidparsley/p/16531539.html