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.Drawing.Printing; using ThoughtWorks.QRCode.Codec; using ThoughtWorks.QRCode.Codec.Data; using ThoughtWorks.QRCode.Codec.Util; namespace TwoDimensionCodePrint { public partial class Print : Form { private int left = 0, top = 0, width = 150, height = 150; private string fileName = "d:\\二维码电子票\\红河谷大门票\\20141025111316红河谷大门票共30张.jpg"; public Print() { InitializeComponent(); } //打印 private void btnPrint_Click(object sender, EventArgs e) { if (pictureBox1.Image == null) { MessageBox.Show("请选择二维码图片"); return; } //打印预览 PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog(); PrintDocument printDocument = new PrintDocument(); //设置边距 try { left = int.Parse(txtLeft.Text); top = int.Parse(txtTop.Text); width = int.Parse(txtWidth.Text); height = int.Parse(txtHeight.Text); } catch { MessageBox.Show("请输入正确的数字"); } Margins margin = new Margins(left, left + width, top, top + height); printDocument.DefaultPageSettings.Margins = margin; //打印事件设置 printDocument.PrintPage += new PrintPageEventHandler(this.PrintPageEvent); // 打印预览 //printPreviewDialog.Document = printDocument; //printPreviewDialog.ShowDialog(); try { printDocument.Print(); } catch (Exception ex) { MessageBox.Show(ex.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error); printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs()); } } //打印事件处理 private void PrintPageEvent(object sender, PrintPageEventArgs e) { //读取图片 // 1 根据路径获取 // Bitmap image = new Bitmap(fileName); // 2 从PictureBox获取 // Image image = pictureBox1.Image; // 3 直接根据生成的二维码打印 Image image = ProduceQRcode("司吉峰"); //在指定区域打印二维码 Rectangle destRect = new Rectangle(left, top, width, height); e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel); } // 将结果填充到图片 private void GetResultIntoImage(ref Image temp, string name, string date) { //读取图片 Graphics g = Graphics.FromImage(temp); Font f = new Font("宋体", 12); Brush b = new SolidBrush(System.Drawing.Color.Black); //填充数据到图片 g.DrawImage(temp, 0, 0, temp.Width, temp.Height); g.DrawString(name, f, b, 168, 105); g.DrawString(date, f, b, 176, 269); g.Dispose(); } //生成二维码 public Image ProduceQRcode(string TicketCodeContent) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeScale = 7; qrCodeEncoder.QRCodeVersion = 0; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L; qrCodeEncoder.QRCodeBackgroundColor = System.Drawing.Color.White; qrCodeEncoder.QRCodeForegroundColor = System.Drawing.Color.Black; return qrCodeEncoder.Encode(TicketCodeContent); } } }
运行界面:
完整代码下载:点击打开链接
时间: 2024-11-15 20:31:55