本文介绍了如何使用C#代码打印文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用C#打印文档.我有两个按钮.btnUpload上传或选择一个Word文件.btnPrint必须将上载的文件发送到打印机.我怎样才能做到这一点?现在使用:
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();
}
推荐答案
您需要处理 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());
}
这篇关于如何使用C#代码打印文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!