2

我试图使用控制台应用程序在后台打印 pdf 文档。我使用了这个过程。控制台应用程序将 pdf 文件发送到打印机,但是以最小化模式在后台打开的 adobe reader 抛出以下错误“打开此文档时出错。找不到此文件”。因此,在多次打印时,我无法终止该进程。有没有可能摆脱这个错误?我的要求是使用进程打印 pdf 文件,同时必须以最小化模式打开 pdf 文件,打印完成后需要自动关闭阅读器。我已经尝试了以下代码,但仍然抛出错误..

string file = "D:\\hat.pdf"; 
PrinterSettings ps = new PrinterSettings();
string printer = ps.PrinterName;
Process.Start(Registry.LocalMachine.OpenSubKe(@"SOFTWARE\Microsoft\Windows\CurrentVersion"+@"\App Paths\AcroRd32.exe").GetValue("").ToString(),string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
4

1 回答 1

0

由于您希望在打印文档时在后台打开 Acrobat 阅读器,因此可以使用以下内容:

private static void RunExecutable(string executable, string arguments) 
{
   ProcessStartInfo starter = new ProcessStartInfo(executable, arguments);
   starter.CreateNoWindow = true;
   starter.RedirectStandardOutput = true;
   starter.UseShellExecute = false;

   Process process = new Process();
   process.StartInfo = starter;
   process.Start();

  StringBuilder buffer = new StringBuilder();
  using (StreamReader reader = process.StandardOutput) 
  {
    string line = reader.ReadLine();
    while (line != null) 
    {
      buffer.Append(line);
      buffer.Append(Environment.NewLine);
      line = reader.ReadLine();
      Thread.Sleep(100);
    }
  }
  if (process.ExitCode != 0) 
 {
    throw new Exception(string.Format(@"""{0}"" exited with ExitCode {1}. Output: {2}", 
executable, process.ExitCode, buffer.ToString());  
 }

}

您可以通过将上述代码合并到您的项目中并按如下方式使用它来打印您的 PDF:

string pathToExecutable = "c:\...\acrord32.exe";
RunExecutable(pathToExecutable, @"/t ""mytest.pdf"" ""My Windows PrinterName""");

此代码取自http://aspalliance.com/514_CodeSnip_Printing_PDF_from_NET.all

如果您不需要在后台打开 Acrobat Reader,只需像打印任何其他文档一样打印 pdf,您可以查看 PrintDocument 类:

http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.print.aspx

于 2012-10-04T08:22:22.447 回答