C#操作Word打印


話不多說,解釋在代碼注釋中……

class PrintClass
{
    #region  全局變量
    private DataGridView datagrid;//需要打印的數據來源

    private PageSetupDialog pagesetupdialog;
    private PrintPreviewDialog printpreviewdialog;
    int currentpageindex = 0;//當前頁的編號
    int rowcount = 0;//數據的行數
    public Size PaperSize = new Size(827, 1169);//答應的紙張大小
    public int headerheight = 30;//標題高度
    Margins margins = new Margins(50, 60, 50, 80);
    public int celltopmargin = 6;//單元格頂邊距 
    public int pagerowcount = 7;//每頁行數 
    public int rowgap = 23;//行高 
    public int colgap = 5;//每列間隔 
    public Font headerfont = new Font("Arial", 9, FontStyle.Bold);//列名標題字體
    public Brush brushHeaderFont = new SolidBrush(Color.Black);//列名字體畫刷
    public Font Cellfont = new Font("Arial", 9);//單元格字體
    public bool isautopagerowcount = true;//是否自動計算行數
    public bool PageAspect = false;//打印的方向
    public static bool PageScape = false;//打印方向
    public string paperName = string.Empty;
    #endregion

    #region  打印信息的初始化
    /// <summary>
    /// 打印信息的初始化
    /// </summary>
    /// <param datagrid="DataGridView">打印數據</param>
    /// <param PageS="int">紙張大小</param>
    /// <param lendscape="bool">是否橫向打印</param>
    public PrintClass(DataGridView datagrid, string paperName, bool lendscape)
    {
        this.datagrid = datagrid;//獲取打印數據
        this.paperName = paperName;
        PrintDocument printdocument = new PrintDocument();//實例化PrintDocument類
        printpreviewdialog = new PrintPreviewDialog();//實例化PrintPreviewDialog類
        printpreviewdialog.Document = printdocument;//獲取預覽文檔的信息
        printpreviewdialog.FormBorderStyle = FormBorderStyle.Fixed3D;//設置窗體的邊框樣式
        //橫向打印的設置
        if (!string.IsNullOrEmpty(paperName) )
        {
            if (lendscape == true)
            {
                printdocument.DefaultPageSettings.Landscape = lendscape;//橫向打印
            }
            else
            {
                printdocument.DefaultPageSettings.Landscape = lendscape;//縱向打印
            }
        }
        pagesetupdialog = new PageSetupDialog();//實例化PageSetupDialog類
        pagesetupdialog.Document = printdocument;//獲取當前頁的設置
        printdocument.PrintPage += new PrintPageEventHandler(this.printdocument_printpage);//事件的重載
    }
    #endregion
    
    #region  頁的打印事件
    /// <summary>
    ///  頁的打印事件(主要用於繪制打印報表)
    /// </summary>
    private void printdocument_printpage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        if (this.isautopagerowcount)//自動計算頁的行數
        {
            double countHeight = e.PageBounds.Height - this.margins.Top - this.headerfont.Height - this.headerheight - this.margins.Bottom;
            pagerowcount = (int)Math.Ceiling(countHeight / this.rowgap);//獲取每頁的行數
        }
        int pagecount = (int)(rowcount / pagerowcount);//獲取打印多少頁
        pagesetupdialog.AllowOrientation = true;//啟動打印頁面對話框的方向部分
        int colcount = 0;//記錄數據的列數
        int y = margins.Top;//獲取表格的頂邊距
        string cellvalue = "";//記錄文本信息(單元格的文本信息)
        int startrow = currentpageindex * pagerowcount;//設置打印的初始頁數
        int endrow = startrow + this.pagerowcount < rowcount ? startrow + pagerowcount : rowcount;//設置打印的最大頁數
        int currentpagerowcount = endrow - startrow;//獲取打印頁數
        colcount = datagrid.ColumnCount;//獲取打印數據的列數

        int x =  margins.Left;//獲取表格的左邊距   繪畫時的x軸位置
        //獲取報表的寬度
        int cwidth = 0;
        for (int j = 0; j < colcount; j++)//循環數據的列數
        {
            if (datagrid.Columns[j].Width > 0)//如果列的寬大於0
            {
                cwidth += datagrid.Columns[j].Width + colgap;//累加每列的寬度
            }
        }
        y += rowgap;//設置表格的上邊線的位置
        //設置標題欄中的文字
        for (int j = 0; j < colcount; j++)//遍歷列數據
        {
            int colwidth = datagrid.Columns[j].Width;//獲取列的寬度
            if (colwidth > 0)//如果列的寬度大於0
            {
                cellvalue = datagrid.Columns[j].HeaderText;//獲取列標題
                //繪制標題欄文字
                e.Graphics.DrawString(cellvalue, headerfont, brushHeaderFont, x, y + celltopmargin);//繪制列標題
                x += colwidth + colgap;//橫向,下一個單元格的位置
                int nnp = y + currentpagerowcount * rowgap + this.headerheight;//下一行線的位置
            }
        }
        //打印所有的行信息
        for (int i = startrow; i < endrow; i++) //對行進行循環
        {
            x = margins.Left; //獲取線的X坐標點
            for (int j = 0; j < colcount; j++)//對列進行循環
            {
                if (datagrid.Columns[j].Width > 0)//如果列的寬度大於0
                {
                    cellvalue = datagrid.Rows[i].Cells[j].Value.ToString();//獲取單元格的值
                    e.Graphics.DrawString(cellvalue, Cellfont, brushHeaderFont, x, y + celltopmargin+rowgap);//繪制單元格信息
                    x += datagrid.Columns[j].Width + colgap;//單元格信息的X坐標
                    y = y + rowgap * (cellvalue.Split(new char[] { '\r', '\n' }).Length - 1);//單元格信息的Y坐標
                }
            }
            y += rowgap;//設置下行的位置
        }
        currentpageindex++;//下一頁的頁碼
        if (currentpageindex < pagecount)//如果當前頁不是最后一頁
        {
            e.HasMorePages = true;//打印副頁
        }
        else
        {
            e.HasMorePages = false;//不打印副頁
            this.currentpageindex = 0;//當前打印的頁編號設為0
        }
    }
    #endregion

    #region 顯示打印預覽窗體
    /// <summary>
    ///  顯示打印預覽窗體
    /// </summary>
    public void print()
    {
        rowcount = 0;//記錄數據的行數
        PageSettings storePageSetting = new PageSettings();//實列化一個對PageSettings對象
        PrintDocument printdocument = pagesetupdialog.Document;
        foreach (PaperSize ps in printdocument.PrinterSettings.PaperSizes)//查找當前設置紙張
        {
            if (paperName == ps.PaperName)//如果找到當前紙張的名稱
            {
                printdocument.DefaultPageSettings.PaperSize = ps;//獲取當前紙張的信息
            }
        }
        if (datagrid.DataSource is System.Data.DataTable)//判斷數據類型
        {
            rowcount = ((DataTable)datagrid.DataSource).Rows.Count;//獲取數據的行數
        }
        else if (datagrid.DataSource is System.Collections.ArrayList)//判斷數據類型
        {
            rowcount = ((ArrayList)datagrid.DataSource).Count;//獲取數據的行數
        }
        try
        {
            printdocument.DefaultPageSettings.Landscape = PageScape;//設置橫向打印
            printpreviewdialog.ShowDialog();//顯示打印預覽窗體
        }
        catch (Exception e)
        {
            throw new Exception("printer error." + e.Message);
        }
    }
    #endregion
}

創建一個打印窗體

設計頁面代碼:

/// <summary>
/// 設計器支持所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內容。
/// </summary>
private void InitializeComponent()
{
    this.dataGridView1 = new System.Windows.Forms.DataGridView();
    this.groupBox1 = new System.Windows.Forms.GroupBox();
    this.label8 = new System.Windows.Forms.Label();
    this.comboBox_PageSize = new System.Windows.Forms.ComboBox();
    this.button_Preview = new System.Windows.Forms.Button();
    this.checkBox_Aspect = new System.Windows.Forms.CheckBox();
    this.panel_Line = new System.Windows.Forms.Panel();
    ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
    this.groupBox1.SuspendLayout();
    this.SuspendLayout();
    // 
    // dataGridView1
    // 
    this.dataGridView1.AllowUserToOrderColumns = true;
    this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    this.dataGridView1.Location = new System.Drawing.Point(3, 4);
    this.dataGridView1.Name = "dataGridView1";
    this.dataGridView1.RowTemplate.Height = 23;
    this.dataGridView1.Size = new System.Drawing.Size(1079, 578);
    this.dataGridView1.TabIndex = 0;
    // 
    // groupBox1
    // 
    this.groupBox1.Controls.Add(this.label8);
    this.groupBox1.Controls.Add(this.comboBox_PageSize);
    this.groupBox1.Controls.Add(this.button_Preview);
    this.groupBox1.Controls.Add(this.checkBox_Aspect);
    this.groupBox1.Controls.Add(this.panel_Line);
    this.groupBox1.Location = new System.Drawing.Point(1088, 4);
    this.groupBox1.Name = "groupBox1";
    this.groupBox1.Size = new System.Drawing.Size(144, 287);
    this.groupBox1.TabIndex = 1;
    this.groupBox1.TabStop = false;
    this.groupBox1.Text = "打印設置";
    // 
    // label8
    // 
    this.label8.AutoSize = true;
    this.label8.Location = new System.Drawing.Point(2, 232);
    this.label8.Name = "label8";
    this.label8.Size = new System.Drawing.Size(65, 12);
    this.label8.TabIndex = 19;
    this.label8.Text = "紙張大小:";
    // 
    // comboBox_PageSize
    // 
    this.comboBox_PageSize.FormattingEnabled = true;
    this.comboBox_PageSize.Items.AddRange(new object[] {
    "A4",
    "A5",
    "A6",
    "B5 (JIS)",
    "B5",
    "16K"});
    this.comboBox_PageSize.Location = new System.Drawing.Point(67, 229);
    this.comboBox_PageSize.Name = "comboBox_PageSize";
    this.comboBox_PageSize.Size = new System.Drawing.Size(71, 20);
    this.comboBox_PageSize.TabIndex = 18;
    // 
    // button_Preview
    // 
    this.button_Preview.Location = new System.Drawing.Point(34, 254);
    this.button_Preview.Name = "button_Preview";
    this.button_Preview.Size = new System.Drawing.Size(70, 23);
    this.button_Preview.TabIndex = 17;
    this.button_Preview.Text = "打印預覽";
    this.button_Preview.UseVisualStyleBackColor = true;
    this.button_Preview.Click += new System.EventHandler(this.button_Preview_Click);
    // 
    // checkBox_Aspect
    // 
    this.checkBox_Aspect.AutoSize = true;
    this.checkBox_Aspect.Location = new System.Drawing.Point(34, 211);
    this.checkBox_Aspect.Name = "checkBox_Aspect";
    this.checkBox_Aspect.Size = new System.Drawing.Size(72, 16);
    this.checkBox_Aspect.TabIndex = 15;
    this.checkBox_Aspect.Text = "橫向打印";
    this.checkBox_Aspect.UseVisualStyleBackColor = true;
    this.checkBox_Aspect.MouseDown += new System.Windows.Forms.MouseEventHandler(this.checkBox_Aspect_MouseDown);
    // 
    // panel_Line
    // 
    this.panel_Line.BackColor = System.Drawing.SystemColors.ButtonHighlight;
    this.panel_Line.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
    this.panel_Line.Location = new System.Drawing.Point(23, 74);
    this.panel_Line.Name = "panel_Line";
    this.panel_Line.Size = new System.Drawing.Size(100, 116);
    this.panel_Line.TabIndex = 6;
    // 
    // Form1
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(1234, 594);
    this.Controls.Add(this.groupBox1);
    this.Controls.Add(this.dataGridView1);
    this.MaximizeBox = false;
    this.Name = "Form1";
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    this.Text = "自定義橫向或縱向打印";
    this.Activated += new System.EventHandler(this.Form1_Activated);
    this.Load += new System.EventHandler(this.Form1_Load);
    ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
    this.groupBox1.ResumeLayout(false);
    this.groupBox1.PerformLayout();
    this.ResumeLayout(false);

}
View Code

操作代碼:

 public bool Aspect = true;//打印方向
 public bool boundary = false;//是否打印分割線

 private void Form1_Activated(object sender, EventArgs e)
 {
     //在窗體中繪制一個預覽表格
     Graphics g = panel_Line.CreateGraphics();
     int paneW = panel_Line.Width;//設置表格的寬度
     int paneH = panel_Line.Height;//設置表格的高度
     g.DrawRectangle(new Pen(Color.WhiteSmoke, paneW), 0, 0, paneW, paneH);//繪制一個矩形
 }

 private void Form1_Load(object sender, EventArgs e)
 {
     comboBox_PageSize.SelectedIndex = 0;
     OleDbConnection oledbCon = new OleDbConnection(" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Lenovo\\Desktop\\SnapShot.mdb;");
     OleDbDataAdapter oledbDa = new OleDbDataAdapter("select * from RegionInfo", oledbCon);
     DataSet myds = new DataSet();
     oledbDa.Fill(myds);
     dataGridView1.DataSource = myds.Tables[0];
 }

 private void checkBox_Aspect_MouseDown(object sender, MouseEventArgs e)
 {
     //改變窗體中預覽表格的方向
     int aspX = 0;//寬度
     int aspY = 0;//高度
     if (((CheckBox)sender).Checked == false)//如果不是縱向打印
     {
         aspX = 136;//設置大小
         aspY = 98;
         PrintClass.PageScape = true;//橫向打印
     }
     else
     {
         aspX = 100;//設置大小
         aspY = 116;
         PrintClass.PageScape = false;//縱向打印
     }
     panel_Line.Width = aspX;//設置控件的寬度
     panel_Line.Height = aspY;//設置控件的高度
     aspX = (int)((groupBox1.Width - aspX) / 2);//設置控件的Top
     panel_Line.Location = new Point(aspX, 90);//設置控件的位置
     Form1_Activated(sender, e);//設用Activated事件
 }

 private void button_Preview_Click(object sender, EventArgs e)
 {
     //對打印信息進行設置
     PrintClass dgp = new PrintClass(this.dataGridView1, comboBox_PageSize.Text, checkBox_Aspect.Checked);
     MSetUp(dgp);//記錄窗體中打印信息的相關設置
     string[] header = new string[dataGridView1.ColumnCount];//創建一個與數據列相等的字符串數組
     for (int p = 0; p < dataGridView1.ColumnCount; p++)//記錄所有列標題的名列
     {
         header[p] = dataGridView1.Columns[p].HeaderCell.Value.ToString();
     }
     dgp.print();//顯示打印預覽窗體
 }

 #region  設置打印數據的相關信息
 /// <summary>
 /// 設置打印數據的相關信息
 /// </summary>
 /// <param dgp="PrintClass">公共類PrintClass</param>
 private void MSetUp(PrintClass dgp)
 {
     dgp.PageAspect = Aspect;//設置橫向打印
 }
 #endregion

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM