在日常工作中,我們可能常常需要打印各種文件資料,比如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:\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(); } } } }
有興趣的朋友自己也可以試一下, 謝謝瀏覽!