How to print a document using C# code?

僤鯓⒐⒋嵵緔 提交于 2019-12-30 07:43:08

问题


I want to print out a document using C#. I have two buttons. btnUpload uploads or selects a word file. btnPrinthave to send uploaded file to a printer. How can I do this? Now using:

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:


you need to hadle PrintPage event

Try This:

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


来源:https://stackoverflow.com/questions/20692697/how-to-print-a-document-using-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!