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);

}

操作代码:

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打印的资料请关注我们其它相关文章!

(0)

相关推荐

  • C#操作excel打印的示例

    using System; using System.Data; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using Microsoft.Office.Core; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsApplication1

  • C#打印日志的方法总结

    在我们对程序进行操作过程中,一般都需要有一个操作流程的记录显示.用C#进行编程时可以很容易实现这个功能.本经验提供案例仅供参考 下面小编就来介绍一下如何使用textbox控件实现日志功能. 打开Visual Studio 2010,建立一个新的C#程序.在工具箱中双击[textbox]控件. 在界面上放置一个[textbox]控件作为日志显示,同时添加一个按钮控件. 添加日志显示的方法[displaylog],在textbox控件中输入信息. 在load方法中调用[displaylog]方法,输

  • C#实现扫描枪扫描二维码并打印(实例代码)

    1.使用usb口输入的扫描枪,这里实现使用了winform 首先创建一个CS文件 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; namespace am_sign { class BardCodeHooK { public delegate voi

  • C# 打印网页不显示页眉页脚的实现方法

    1.在IE浏览器点"打印"-"页面设置",IE的默认设置如下图 2.设置在注册表里 3.C#代码实现 4.Javascript代码实现 5.法二,使用JS修改注册表,但是失败,有机会研究一下 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们.

  • C# winform打印excel的方法

    前言 c#做winform程序要求生成并打印Excel报告,为了不安装Office相应组件,我选择了NPOI来生成Excel报告,用winform的PrintDocument控件来触发打印操作,而难点在于如何将excel转换成Graphics对象,在NPOI中我只找到了excel打印的设置(如横向/纵向),还需要打开excel去触发打印操作,但项目要求是一次性直接实现打印,要用PrintDocument控件而不是再去操作excel.不得已重新搜索,发现了类库Spire.xls,最终实现了要求.有

  • C# TSC打印二维码和条形码的实现方法

    效果图 开发.使用环境说明 安装TSC_7.3.8_M-3.exe打印机驱动,安装时选择对应的ttp 244 pro 将TSCLIB.dll复制到C:\Windows\system 驱动安装说明 选择下一步 选择安装路径,默认即可,选择下一步 选择安装打印机,选择下一步 选择其他,点击下一步 选择对应的打印机型号,点击下一步 选择USB端口,点击下一步 直接默认即可,点击下一步 驱动安装完成! TSCLIB.cs代码: using System; using System.Collections

  • C#条码生成及打印实例代码

    本文实例为大家分享了C#条码生成及打印的方法,供大家参考,具体内容如下 string BarcodeString = "13043404455";//条码 int ImgWidth = 520; int ImgHeight = 120; //打印按钮 private void button1_Click(object sender, EventArgs e) { //实例化打印对象 PrintDocument printDocument1 = new PrintDocument();

  • c# 获取已安装的打印机并调用打印文件

    C# 获取所有安装了的打印机代码如下: using System.Drawing.Printing; var printers = PrinterSettings.InstalledPrinters; foreach (var item in printers) { Console.WriteLine(item.ToString()); } C# 调用打印机打印文件,通常情况下,例如Word.Excel.PDF等可以使用一些对应的组件进行打印,另一个通用的方式是直接启用一个打印的进程进行打印.示

  • C#操作Word打印的示例

    话不多说,解释在代码注释中-- class PrintClass { #region 全局变量 private DataGridView datagrid;//需要打印的数据来源 private PageSetupDialog pagesetupdialog; private PrintPreviewDialog printpreviewdialog; int currentpageindex = 0;//当前页的编号 int rowcount = 0;//数据的行数 public Size P

  • C#操作word的方法示例

    本文实例讲述了C#操作word的方法.分享给大家供大家参考,具体如下: #region 读取word /// <summary> /// 读取word所有文字内容(不包含表格) /// </summary> /// <returns>word中的字符内容(纯文本)</returns> public string ReadAllFromWord() { Word.ApplicationClass app = null; Word.Document doc =

  • Python操作word常见方法示例【win32com与docx模块】

    本文实例讲述了Python操作word常见方法.分享给大家供大家参考,具体如下: 这里介绍两种方式: 使用win32com 使用docx 1. 使用win32com扩展包 只对windows平台有效 代码: # coding=utf-8 import win32com from win32com.client import Dispatch, DispatchEx word = Dispatch('Word.Application') # 打开word应用程序 # word = Dispatch

  • 比较全的一个C#操作word文档示例

    最近两天研究了一下如何使用VS2008(C#语言)输出Word文档.以下是几点总结: 1.非常简单. 2.开发及运行环境要求.操作系统为:WindowsXP(安装.net framework2.0)/Vista/Win7:在操作系统必须安装Word2003完全安装版.这里必须要强调是Word2003完全安装版,因为软件开发及运行都需要一个com组件:Microsoft word 11.0 Object Library.如果不是Word2003完全安装版,可以下载这个com组件,并手动的安装这个c

  • Python操作Word批量生成合同的实现示例

    背景:大约有3K家商家需要重新确认信息并签订合同.合同是统一的Word版本.每个供应商需要修改合同内的金额部分.人工处理方式需要每个复制粘贴且金额要生成大写金额.基于重复工作可偷懒.用Python解救一下. #导入对应数据库 import numpy as np import pandas as pd import os import docx from docx.shared import Pt from docx.oxml.ns import qn #修改项目文件地址 os.chdir(r'

  • Python操作word文档的示例详解

    目录 写在前面 创建一个文档 先实现第一步,写入一个标题 添加文字段落 列表的添加 图片的添加 表格添加 相关样式设置 页眉和页脚 写在前面 python-docx 不支持 doc 文档,一定要注意该点,如果使用 doc 文档,需要提前将其用 Word 相关软件转换为 docx 格式. doc 和 docx 是存在本质差异的,一个是二进制,另一个 XML 格式的文件. 模块的安装 pip install python-docx . 以下网址首先准备好 官方手册:https://python-do

  • Java编程实现调用com操作Word方法实例代码

    实例代码如下: import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; /** * jacob操作MSword类 * @author */ public class WordBean { // word文档 private Dispatch doc; // word运行程序对象 private ActiveXComponent word; //

  • python实现在windows下操作word的方法

    本文实例讲述了python实现在windows下操作word的方法.分享给大家供大家参考.具体实现方法如下: import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.Application') # 或者使用下面的方法,使用启动独立的进程: # w = win32com.client.DispatchEx('Word.Application') # 后台运行

  • Python操作Word批量生成文章的方法

    下面通过COM让Python与Word建立连接实现Python操作Word批量生成文章,具体介绍请看下文: 需要做一些会议记录.总共有多少呢?五个地点x7个月份x每月4篇=140篇.虽然不很重要,但是140篇记录完全雷同也不好.大体看了一下,此类的记录大致分为四段.于是决定每段提供四种选项,每段从四选项里随机选一项,拼凑成四段文字,存成一个文件.而且要打印出来,所以准备生成一个140页的Word文档,每页一篇. 需要用到win32com模块(下载链接: http://sourceforge.ne

随机推荐