使用c#打印word文档

时间:2014-08-25 10:21:48

标签: c# ms-word office-interop

我有这个代码来打开一个word文件

int num = 0;
object fileName = FD.FileName;
object readOnly = false;
object isVisible = false;
object missing = System.Reflection.Missing.Value;

Word.Application WordApp = new Word.Application();
Word.Document aDoc = null;
WordApp.Visible = false;

aDoc = WordApp.Documents.Open(ref fileName,
                              ref missing, 
                              ref readOnly,
                              ref missing,
                              ref missing, 
                              ref missing, 
                              ref missing,
                              ref missing, 
                              ref missing,
                              ref missing,
                              ref missing, 
                              ref isVisible,
                              ref missing,
                              ref missing, 
                              ref missing, 
                              ref missing);

Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
num = aDoc.ComputeStatistics(stat, ref missing);

label3.Text = "Page Count :"+aDoc.ComputeStatistics(stat, ref missing).ToString();
GC.Collect();

现在,我想在按钮的点击事件上打印已打开的word文件,不知道吗?

2 个答案:

答案 0 :(得分:10)

快速提示(与您的主题无关,但实际上与C#相关):您无需像上面那样写出可选参数,您可以使用ParameterName: parameter为a指定参数可选参数。

快速回答:使用Document.PrintOut()方法打印当前文档。有关参数的更多详细信息,您可以查看MSDN sitethis site以获取实用教程。

这是一个简单的演示:

public class YourClass : Form
{
    private Word.Application word = new Word.Application {Visible = false};
    private Word.Document doc;
    // where did you get this file name?
    private string fileName;

    private void Count()
    {
        // as you mentioned, you open your word document here
        doc = word.Documents.Open(fileName, ReadOnly : readOnly, Visible: isVisible);
    }

    // in your button click handler, just call PrintOut() function
    private void ButtonClickHandler(object sender, EventArgs e)
    {
        // if doc == null, open the document
        if (doc == null)
        {
            // here i assume fileName has been assigned
            doc = word.Documents.Open(fileName, ReadOnly : readOnly, Visible: isVisible);
        }

        doc.PrintOut();
    }
}

答案 1 :(得分:1)

使用RawPrintHelper。请点击以下链接:

http://support.microsoft.com/kb/322091

下面是将文件发送到打印机进行打印的代码:

//Send file for Printing
RawPrinterHelper.SendFileToPrinter(PrinterName, FileName);

//Send string to print
RawPrinterHelper.SendStringToPrinter(PrinterName, sData);