C#中5步完成word文档打印的方法
在日常工作中,我們可能常常需要打印各種文件資料,比如word文檔。對(duì)于編程員,應(yīng)用程序中文檔的打印是一項(xiàng)非常重要的功能,也一直是一個(gè)非常復(fù)雜的工作。特別是提到Web打印,這的確會(huì)很棘手。一般如果要想選擇非默認(rèn)打印機(jī)或者說(shuō)想顯示打印設(shè)置對(duì)話框時(shí),我們也需要對(duì)代碼進(jìn)行一定的設(shè)置。
針對(duì)這樣的問(wèn)題,今天這篇文章我就來(lái)分享一下如何利用第三方組件?Spire.Doc來(lái)實(shí)現(xiàn)Word文檔打印。
?詳細(xì)步驟
這是原來(lái)的word文檔截圖:
第一步:組件安裝后,創(chuàng)建一個(gè)C#控制臺(tái)項(xiàng)目,添加引用及命名空間如下:
| 1 2 3 | using?System; using?Spire.Doc; using?System.Windows.Forms; |
第二步:實(shí)例化一個(gè)word文檔對(duì)象,調(diào)用LoadFromFile方法加載待打印的word文檔:
| 1 2 | Document doc =?new?Document(); doc.LoadFromFile("sample.doc"); |
第三步:實(shí)例化一個(gè)PrintDialog的對(duì)象,設(shè)置相關(guān)屬性。關(guān)聯(lián)doc.PrintDialog屬性和PrintDialog對(duì)象:
| 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; |
?第四步:?后臺(tái)打印。使用默認(rèn)打印機(jī)打印出所有頁(yè)面。這段代碼也可以用于網(wǎng)頁(yè)后臺(tái)打印:
| 1 2 | PrintDocument printDoc = doc.PrintDocument; printDoc.Print(); |
?第五步: ?如要顯示打印對(duì)話框,就調(diào)用ShowDialog方法,根據(jù)打印預(yù)覽設(shè)置選項(xiàng),打印word文檔:
| 1 2 3 4 | if?(dialog.ShowDialog() == DialogResult.OK) {?????????????? printDoc.Print(); } |
?這是打印文檔過(guò)后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) ????????{ ????????????// 實(shí)例化一個(gè)word文檔對(duì)象 ????????????Document doc =?new?Document(); ????????????// 加載文檔 ????????????doc.LoadFromFile(@"C:\Users\Administrator\Desktop\示例文檔.doc"); ????????????// 實(shí)例化System.Windows.Forms.PrintDialog對(duì)象 ????????????PrintDialog dialog =?new?PrintDialog(); ????????????dialog.AllowPrintToFile =?true; ????????????dialog.AllowCurrentPage =?true; ????????????dialog.AllowSomePages =?true; ????????????dialog.UseEXDialog =?true; ????????????// 關(guān)聯(lián)doc.PrintDialog屬性和PrintDialog對(duì)象 ????????????doc.PrintDialog = dialog; ????????????// 后臺(tái)打印 ????????????// PrintDocument printDoc = doc.PrintDocument;??????? ????????????// printDoc.Print(); ????????????// 顯示打印對(duì)話框并打印 ????????????if?(dialog.ShowDialog() == DialogResult.OK) ????????????{ ????????????????//printDoc.Print(); ????????????} ? ????????} ????} } |
有興趣的朋友自己也可以試一下, 謝謝瀏覽!
總結(jié)
以上是生活随笔為你收集整理的C#中5步完成word文档打印的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JAVA中神奇的双刃剑--Unsafe
- 下一篇: 项目移植,项目环境问题