C#中5步完成word文档打印的方法

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

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

 详细步骤

这是原来的word文档截图:

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

1
2
3
using System;
using Spire.Doc;
using System.Windows.Forms;

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

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

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

1
2
3
4
5
6
PrintDialog dialog = new PrintDialog();
dialog.AllowPrintToFile = true;
dialog.AllowCurrentPage = true;
dialog.AllowSomePages = true;
dialog.UseEXDialog = true;                    
doc.PrintDialog = dialog;

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

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

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

1
2
3
4
if (dialog.ShowDialog() == DialogResult.OK)
{              
printDoc.Print();
}

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

全部代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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:\Users\Administrator\Desktop\示例文档.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();
            }
 
        }
    }
}

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

 

posted @   E-iceblue  阅读(12781)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示