【问题标题】:How to print a document using C# code?如何使用 C# 代码打印文档?
【发布时间】:2014-01-08 16:06:03
【问题描述】:

我想使用 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();
}

【问题讨论】:

标签: c# winforms printing


【解决方案1】:

你需要处理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());
 }

【讨论】:

  • 如果我要打印的文件是PDF,并且有表格、格式化文本、图像等图形,如何在打印页面上绘制?我在谷歌上搜索了很多,没有解决方案。
猜你喜欢
  • 2011-05-14
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 2019-04-13
相关资源
最近更新 更多