⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs

📁 csharp 实现datagridview的打印功能
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;//找不到类型或命名空间名称margins

namespace Print
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataGridViewPrinter print;

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SetupThePrinting())
                printDocument.Print();

        }
        private bool SetupThePrinting()  //企业基本信息打印设置
        {
            PrintDialog MyPrintDialog = new PrintDialog();
                MyPrintDialog.AllowCurrentPage = false;
                MyPrintDialog.AllowPrintToFile = false;
                MyPrintDialog.AllowSelection = false;
                MyPrintDialog.AllowSomePages = false;
                MyPrintDialog.PrintToFile = false;
                MyPrintDialog.ShowHelp = false;
                MyPrintDialog.ShowNetwork = false;

                if (MyPrintDialog.ShowDialog() != DialogResult.OK)
                    return false;

               printDocument.DocumentName = "企业基本信息";//获取或设置打印文档时要显示的文档名
                printDocument.PrinterSettings = MyPrintDialog.PrinterSettings;//设置打印机
                printDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;//获取或设置页面设置,是默认的
                printDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);//获取或设置页边距
                print = new DataGridViewPrinter(dataGridView1 , printDocument, true, true, "企业基本信息", new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);

            return true;
        }

        private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {

                bool more =print.DrawDataGridView(e.Graphics);
                if (more == true)
                    e.HasMorePages = true;//是否打印附加页
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void printviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SetupThePrinting())
            {
                PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
                MyPrintPreviewDialog.Document = printDocument; //获取或设置要预览的的文档
                MyPrintPreviewDialog.ShowDialog();
            }
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -