C# 实现自己画内容并打印

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shenshendeai/article/details/72876237


1. 首先在界面中拉入三个控件,右边为panel


2. 界面初始化添加自打印事件,PrintEveryPage函数中添加打印内容

 public FrmPrinter()
        {
            InitializeComponent();
            this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.PrintEveryPage);
        }


 private void PrintEveryPage(object sender, PrintPageEventArgs e)
        {
  int tmpCount = 0;
            int pageHeight = paperSize.Height;
            int pageWidth = paperSize.Width;
            int textStartX = pageMergin.Left;
            int textStartY =pageMergin.Top;
            int txtWidth = pageWidth - pageMergin.Left - pageMergin.Right;
            e.HasMorePages = false;
            Graphics gh = e.Graphics;//获取绘图对象  

    string myStr;
            Pen myPen = new Pen(Color.Black);
            gh.DrawLine(myPen, pageMergin.Left / 2, 40, pageWidth - pageMergin.Right, 40);
            RectangleF rec = new RectangleF(0, 0, pageWidth, pageMergin.Top);
            Font titleFont = new System.Drawing.Font("宋体", (float)15.0, FontStyle.Bold);
            Brush titleBrush = new SolidBrush(Color.Black);
            myStr = "自己画的字符串";
            StringFormat fmt = new StringFormat();
            fmt.LineAlignment = StringAlignment.Center;
            fmt.Alignment = StringAlignment.Center;
            gh.DrawString(myStr, titleFont, titleBrush, rec, fmt);

        }


3.打开预览


 private void bt_scanReport_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printPreviewDialog1;
            printPreviewDialog1 = new PrintPreviewDialog();
            printPreviewDialog1.TopLevel = false;
            printPreviewDialog1.AllowTransparency = true;
            printPreviewDialog1.Document = this.printDocument1;


            panel1.Controls.Add(printPreviewDialog1);
            Form f = (Form)printPreviewDialog1;
            f.WindowState = FormWindowState.Maximized;
            f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            printPreviewDialog1.Show();
        }


4. 打印函数

   private void bt_printReport_Click(object sender, EventArgs e)
        {
            printDialog1.AllowCurrentPage = true;
            printDialog1.AllowSomePages = true;
            printDialog1.AllowPrintToFile = true;
            if (this.printDialog1.ShowDialog() == DialogResult.OK)
            {
                this.printDocument1.Print();
            }
        }

展开阅读全文

没有更多推荐了,返回首页