C#操作Word打印的示例

编辑: admin 分类: c#语言 发布时间: 2022-01-18 来源:互联网

话不多说,解释在代码注释中……

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
      {
        printdocumen【文章出处:http://www.nextecloud.cn/sin.html欢迎留下您的宝贵建议】t.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);

}

操作代码:

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

以上就是C#操作Word打印的示例的详细内容,更多关于C#操作Word打印的资料请关注海外IDC网其它相关文章!