如何使用C#代码打印文档?

时间:2013-12-19 22:12:31

标签: c# winforms printing

我想用C#打印出一份文件。我有两个按钮。 btnUpload上传或选择一个word文件。 btnPrint将要上传的文件发送到打印机。我怎样才能做到这一点?现在使用:

private void btnUpload_Click(object sender, EventArgs e)
{
    string fileName;
    // Show the dialog and get result.
    OpenFileDialog ofd = new OpenFileDialog();
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK) // Test result.
    {
        fileName = ofd.FileName;

        var application = new Microsoft.Office.Interop.Word.Application();
        //var document = application.Documents.Open(@"D:\ICT.docx");
        var document = application.Documents.Open(@fileName);
    }
}


private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDialog printDlg = new PrintDialog();
    PrintDocument printDoc = new PrintDocument();
    printDoc.DocumentName = "fileName";
    printDlg.Document = printDoc;
    printDlg.AllowSelection = true;
    printDlg.AllowSomePages = true;
    //Call ShowDialog
    if (printDlg.ShowDialog() == DialogResult.OK)
        printDoc.Print();
}

1 个答案:

答案 0 :(得分:5)

你需要处理PrintPage事件试试这个:

   String content="";
   private void btnUpload_Click(object sender, EventArgs e)
    {
        string fileName;
        // Show the dialog and get result.
        OpenFileDialog ofd = new OpenFileDialog();
        DialogResult result = openFileDialog1.ShowDialog();
        if (result == DialogResult.OK) // Test result.
        {
            fileName = ofd.FileName;

            var application = new Microsoft.Office.Interop.Word.Application();
            //var document = application.Documents.Open(@"D:\ICT.docx");
             //read all text into content
            content=System.IO.File.ReadAllText(fileName);
            //var document = application.Documents.Open(@fileName);
        }
    }
 private void btnPrint_Click(object sender, EventArgs e)
    {
        PrintDialog printDlg = new PrintDialog();
        PrintDocument printDoc = new PrintDocument();
        printDoc.DocumentName = "fileName";
        printDlg.Document = printDoc;
        printDlg.AllowSelection = true;
        printDlg.AllowSomePages = true;
        //Call ShowDialog
        if (printDlg.ShowDialog() == DialogResult.OK)
        {
             printDoc.PrintPage += new PrintPageEventHandler(pd_PrintPage);            
             printDoc.Print(); 
        }
    }
 private void pd_PrintPage(object sender, PrintPageEventArgs ev)
 {
   ev.Graphics.DrawString(content,printFont , Brushes.Black,
                   ev.MarginBounds.Left, 0, new StringFormat());
 }