How to print a document using C# code?

后端 未结 1 1917
小蘑菇
小蘑菇 2021-01-07 07: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? No

相关标签:
1条回答
  • 2021-01-07 07:36

    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());
     }
    
    0 讨论(0)
提交回复
热议问题