C# 如何打印用户选择的文档?
我想使用文件对话框选择一个文件,然后使用C# 如何打印用户选择的文档?,c#,.net,winforms,c#-4.0,C#,.net,Winforms,C# 4.0,我想使用文件对话框选择一个文件,然后使用PrintDocument.print方法打印所选文件 下面是一些代码,它是我试图实现的部分实现: using System; using System.Drawing.Printing; using System.IO; using System.Windows.Forms; namespace InstalledAndDefaultPrinters { class Program
PrintDocument.print
方法打印所选文件
下面是一些代码,它是我试图实现的部分实现:
using System;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
namespace InstalledAndDefaultPrinters
{
class Program
{
static void Main(string[] args)
{
string filename="";
foreach (string printer in PrinterSettings.InstalledPrinters)
Console.WriteLine(printer);
var printerSettings = new PrinterSettings();
Console.WriteLine(string.Format("The default printer is: {0}", printerSettings.PrinterName));
Console.WriteLine(printerSettings.PrintFileName);
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Open File Dialog";
fdlg.InitialDirectory = @"C:\ ";
fdlg.RestoreDirectory = true;
fdlg.ShowDialog();
Console.WriteLine(fdlg.Title);
if (fdlg.ShowDialog() == DialogResult.OK)
{
filename = String.Copy(fdlg.FileName);
}
Console.WriteLine(filename);
PrintDialog printdg = new PrintDialog();
PrintDocument pd_doc = new PrintDocument();
printdg.ShowDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
正是在这一点上,我想打印选定的文件
pd_doc.Print();
}
}
我上面的代码显然不能满足我的需要。有什么替代方法可以引导我走向正确的方向?您可以使用以下代码片段来解决这个问题。它可以根据您的需要工作
private void button1_Click(object sender, EventArgs e)
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\Users\therath\Desktop\372\a.jpg");
// You can replace your logic @ here to load the image or whatever you want
Point loc = new Point(100, 100);
e.Graphics.DrawImage(img, loc);
}
您可以使用下面的代码段来解决这个问题。它可以根据您的需要工作
private void button1_Click(object sender, EventArgs e)
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\Users\therath\Desktop\372\a.jpg");
// You can replace your logic @ here to load the image or whatever you want
Point loc = new Point(100, 100);
e.Graphics.DrawImage(img, loc);
}
是否应该将
pd
分配给选中的printdg
项目?@Crud嘿,你不认为system.drawing.image只用于图像吗???@MichaelJ.Gray我认为system.drawing.image只用于图像..你说什么兄弟?@UmairAmin,你想打印什么样的文档?@SuperPrograman word文件,pdf文件图像。。。excel..所有可以打印的内容都不应该分配给选中的项目吗?@Crud嘿,你不认为system.drawing.image只用于图像吗???@MichaelJ.Gray我想system.drawing.image只用于图像..你说什么兄弟?@UmairAmin,您要打印什么类型的文档?@SuperPrograman word文件、pdf文件和图像。。。出类拔萃..所有这些都是可以预测的