zoukankan      html  css  js  c++  java
  • C#中5步完成word文档打印的方法

    在日常工作中,我们可能常常需要打印各种文件资料,比如word文档。对于编程员,应用程序中文档的打印是一项非常重要的功能,也一直是一个非常复杂的工作。特别是提到Web打印,这的确会很棘手。一般如果要想选择非默认打印机或者说想显示打印设置对话框时,我们也需要对代码进行一定的设置。

    针对这样的问题,今天这篇文章我就来分享一下如何利用第三方组件 Spire.Doc来实现Word文档打印。

     详细步骤

    这是原来的word文档截图:

    第一步:组件安装后,创建一个C#控制台项目,添加引用及命名空间如下:

    using System;
    using Spire.Doc;
    using System.Windows.Forms;
    

    第二步:实例化一个word文档对象,调用LoadFromFile方法加载待打印的word文档:

    Document doc = new Document(); 
    doc.LoadFromFile("sample.doc");
    

    第三步:实例化一个PrintDialog的对象,设置相关属性。关联doc.PrintDialog属性和PrintDialog对象:

    PrintDialog dialog = new PrintDialog();
    dialog.AllowPrintToFile = true; 
    dialog.AllowCurrentPage = true;
    dialog.AllowSomePages = true;
    dialog.UseEXDialog = true;                     
    doc.PrintDialog = dialog; 
    

     第四步: 后台打印。使用默认打印机打印出所有页面。这段代码也可以用于网页后台打印:

    PrintDocument printDoc = doc.PrintDocument;
    printDoc.Print();
    

     第五步:  如要显示打印对话框,就调用ShowDialog方法,根据打印预览设置选项,打印word文档:

    if (dialog.ShowDialog() == DialogResult.OK)
    {               
    printDoc.Print();
    }
    

     这是打印文档过后XPS格式的屏幕截图:

    全部代码:

    using System;
    using Spire.Doc;
    using System.Windows.Forms;
    
    namespace Doc_Print
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                // 实例化一个word文档对象
                Document doc = new Document();
                // 加载文档
                doc.LoadFromFile(@"C:UsersAdministratorDesktop示例文档.doc");
                // 实例化System.Windows.Forms.PrintDialog对象
                PrintDialog dialog = new PrintDialog();
                dialog.AllowPrintToFile = true;
                dialog.AllowCurrentPage = true;
                dialog.AllowSomePages = true;
                dialog.UseEXDialog = true;
                // 关联doc.PrintDialog属性和PrintDialog对象 
                doc.PrintDialog = dialog;
                // 后台打印
                // PrintDocument printDoc = doc.PrintDocument;        
                // printDoc.Print();
                // 显示打印对话框并打印
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    //printDoc.Print();
                }
    
            }
        }
    }
    

    有兴趣的朋友自己也可以试一下, 谢谢浏览!

  • 相关阅读:
    shell 的多进程
    shell 按行读取文件的内容
    2>&1的意思
    >/dev/null 2>&1
    js 变量作用域
    Premiere Pro 中的键盘快捷键
    premiere pro 2019 mac 破解
    js 空语句
    js 数组原型
    js 奇偶判断
  • 原文地址:https://www.cnblogs.com/Yesi/p/6000247.html
Copyright © 2011-2022 走看看