使用C#代码打印文档

时间:2013-12-23 14:10:20

标签: c# asp.net winforms

到目前为止,我正在使用以下代码。使用btnUpload我可以上传文件。使用btnPrint我可以将文件发送到打印机。当我上传记事本时它打印得很好。但是当我上传word文档时它也给我打印文件。但它不包含字母。一些符号很少的字符。如何解决这个问题?

String content = "";

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

       var application = new Microsoft.Office.Interop.Word.Application();
       //read all text into content

       try
       {
          content = System.IO.File.ReadAllText(fileName);
       }
       catch (Exception ex)
       {
          MessageBox.Show(ex.Message);

       }

       var document = application.Documents.Open(@fileName);
       numberOfPages = document.ComputeStatistics(WdStatistic.wdStatisticPages, false);
       MessageBox.Show("Total Pages"+ numberOfPages);
    }
}

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, new System.Drawing.Font(new FontFamily("Times new Roman"), 12f), Brushes.Black,
                        ev.MarginBounds.Left, 0, new StringFormat());
}

2 个答案:

答案 0 :(得分:1)

您无法打印二进制文件,因为它是纯文本,为了打印Word文档,您必须使用Microsoft.Office.Interop。

答案 1 :(得分:1)

确保您引用Microsoft.Office.Interop;

   Word.Application _app = new  Word.Application();
   Word.Document doc = _app.Documents.Open(refer fileName, ...);
   doc.PrintOut(/* refer options */);