大家好我正在尝试打印pdf文件。为此我创建了一个Windows窗体应用程序。如果我使用系统的默认打印机,我的应用程序将打印pdf。但问题是,当我尝试从下拉列表中选择打印机打印PDF文件时,我的代码不起作用。
private bool SendToPrinter(string filePath, string filename)
{
bool Status = false;
string PrinterName;
string PaperName;
PrinterName = "";
try
{
PrinterName = Convert.ToString(cmbPrinterList.SelectedItem);
// Set the printer.
AddPrinterConnection(PrinterName);
SetDefaultPrinter(PrinterName);
//Print the file with number of copies sent.
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.Arguments = "\"" + PrinterName + "\"";
info.FileName = @filePath + @"\" + filename;
info.CreateNoWindow = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(2);
if (false == p.CloseMainWindow())
p.Kill();
Status = true;
}
catch (Exception ex)
{
}
return Status;
}
//Set the added printer as default printer.
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);
//Add the printer connection for specified pName.
[DllImport("winspool.drv")]
public static extern bool AddPrinterConnection(string pName);
public bool viewTabOrder = true;
答案 0 :(得分:1)
尝试以下代码 这适用于我的不同打印机。希望它也能帮助你:)。
public void SendToPrinter(string filePath, string Printer)
{
try
{
Process proc = new Process();
proc.Refresh();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.Verb = "printto";
proc.StartInfo.FileName = ConfigurationManager.AppSettings["ReaderPath"].ToString();
proc.StartInfo.Arguments = String.Format("/t \"{0}\" \"{1}\"", filePath, Printer);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (proc.HasExited == false)
{
proc.WaitForExit(20000);
}
proc.EnableRaisingEvents = true;
proc.Close();
}
catch (Exception e)
{
}
}
将打印机绑定到下拉列表的代码。
cmbPrinter.Items.Insert(0, "--Select Printer--");
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
var pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
cmbPrinter.Items.Insert(i + 1, pkInstalledPrinters);
}
并传递参数如下
SendToPrinter(FilePath,cmbPrinter.SelectedItem.ToString());