Print word document using c#

2020-07-27 03:58发布

I have this code to open a word file

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();

Now, I want to print the opened word file on the click event of a button, Any idea?

2条回答
冷血范
2楼-- · 2020-07-27 04:28

Quick tip (not relevant to your topic but actually C#): there's no need to write out optional parameters as you did above, you can use ParameterName: parameter to specify a parameter to a optional parameter.

Quick answer: use Document.PrintOut() method to print the current document. For more details about the parameters, you can take a look at MSDN site and this site for a hand-on tutorial.

Here is a simple demo:

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();
    }
}
查看更多
Melony?
3楼-- · 2020-07-27 04:28

Use the RawPrintHelper. Follow the link below:

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

below is the code to send file to the printer for printing:

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

//Send string to print
RawPrinterHelper.SendStringToPrinter(PrinterName, sData);
查看更多
登录 后发表回答