C# 如何将文件文档发送到打印机并进行打印?

C# 如何将文件文档发送到打印机并进行打印?,c#,winforms,pdf,.net-4.0,printing,C#,Winforms,Pdf,.net 4.0,Printing,以下是基本前提: 我的用户点击一些小发明,一个PDF文件被吐到他的桌面上。我是否有办法将此文件发送到打印机队列并将其打印到本地连接的打印机 string filePath = "filepathisalreadysethere"; SendToPrinter(filePath); //Something like this? 这个过程他会做很多次。教室里的每个学生都必须打印一张小成绩单。所以我为每个学生生成一个PDF,我想自动化打印过程,而不是让用户生成PDF,打印,生成PDF,打印,生成PD

以下是基本前提:

我的用户点击一些小发明,一个PDF文件被吐到他的桌面上。我是否有办法将此文件发送到打印机队列并将其打印到本地连接的打印机

string filePath = "filepathisalreadysethere";
SendToPrinter(filePath); //Something like this?
这个过程他会做很多次。教室里的每个学生都必须打印一张小成绩单。所以我为每个学生生成一个PDF,我想自动化打印过程,而不是让用户生成PDF,打印,生成PDF,打印,生成PDF,打印

关于如何处理这个问题有什么建议吗?我正在使用Windows窗体.NET 4运行Windows XP

我发现这个问题的答案表明:

创建文件后,您可以 可以通过命令行打印它们(您可以 可以使用在中找到的命令类 的System.Diagnostics命名空间 (即)


如何完成此操作?

可用于打印文档。将UseShellExecute设置为True,并将谓词设置为“打印”。

您可以尝试使用GhostScript,如本文所述:


您可以告诉Acrobat Reader使用“打印”动词打印文件(这里有人已经提到过)。在此之后,您还需要以编程方式关闭Acrobat Reader:

private void SendToPrinter()
{
   ProcessStartInfo info = new ProcessStartInfo();
   info.Verb = "print";
   info.FileName = @"c:\output.pdf";
   info.CreateNoWindow = true;
   info.WindowStyle = ProcessWindowStyle.Hidden;

   Process p = new Process();
   p.StartInfo = info;
   p.Start();

   p.WaitForInputIdle();
   System.Threading.Thread.Sleep(3000);
   if (false == p.CloseMainWindow())
      p.Kill();
}
这将打开Acrobat Reader并告诉它将PDF发送到默认打印机,然后在三秒后关闭Acrobat

如果您愿意在应用程序中附带其他产品,则可以使用GhostScript(免费)或命令行PDF打印机,如(商用)


注意:示例代码在当前注册为打印PDF的应用程序中打开PDF,该应用程序是大多数人机器上的Adobe Acrobat Reader。但是,他们可能使用不同的PDF查看器,如Foxit()。不过,示例代码应该仍然可以工作。

这是一个稍加修改的解决方案。当进程空闲至少1秒时,它将被终止。也许您应该添加一个X秒的时间,并从一个单独的线程调用该函数

private void SendToPrinter()
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"c:\output.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Hidden;

  Process p = new Process();
  p.StartInfo = info;
  p.Start();

  long ticks = -1;
  while (ticks != p.TotalProcessorTime.Ticks)
  {
    ticks = p.TotalProcessorTime.Ticks;
    Thread.Sleep(1000);
  }

  if (false == p.CloseMainWindow())
    p.Kill();
}

我知道标签上写着“Windows窗体”。。。但是,如果有人对
WPF
应用程序方法感兴趣,
System.Printing
就像一种魅力

var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();

using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
    stream.Write(file, 0, file.Length);
}
只要记住包含
系统。打印
参考,如果尚未包含。
现在,这种方法在
ASP.NET
Windows服务中不起作用。它不应与Windows窗体一起使用,因为它具有系统.Drawing.Printing
。我没有一个问题与我的PDF打印使用上述代码

但是,我要提到的是,如果您的打印机不支持PDF文件格式的直接打印,那么使用这种方法就不走运了。

简单方法:

var pi=new ProcessStartInfo("C:\file.docx");
pi.UseShellExecute = true;
pi.Verb = "print";
var process =  System.Diagnostics.Process.Start(pi);

这是一个迟来的答案,但您也可以使用System.IO命名空间top的File.Copy方法将文件发送到打印机:

System.IO.File.Copy(filename, printerName);

这很好

我知道Edwin回答了上面的问题,但他只打印了一份文档。我使用此代码打印给定目录中的所有文件

public void PrintAllFiles()
{
    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
    info.Verb = "print";
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    //Load Files in Selected Folder
    string[] allFiles = System.IO.Directory.GetFiles(Directory);
    foreach (string file in allFiles)
    {
        info.FileName = @file;
        info.CreateNoWindow = true;
        info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         p.StartInfo = info;
        p.Start();
    }
    //p.Kill(); Can Create A Kill Statement Here... but I found I don't need one
    MessageBox.Show("Print Complete");
}

它基本上在给定目录变量directory->中的每个文件中循环运行,对我来说,它是@“C:\Users\Owner\Documents\SalesVaultTesting\”并将这些文件打印到您的默认打印机上

添加一个新的答案,因为在.net中打印PDF的问题已经存在很长时间了,而且大多数答案都是在Google Pdfium库之前,该库现在有一个.net包装器。对我来说,我自己也在研究这个问题,但一直一无所获,试图找到黑客解决方案,比如生成Acrobat或其他PDF阅读器,或者进入昂贵且没有非常兼容的许可条款的商业图书馆。但是GooglePdfium库和PdfiumViewer.net包装器都是开源的,所以对于包括我在内的许多开发人员来说都是一个很好的解决方案。PdfiumViewer是根据Apache 2.0许可证获得许可的

您可以在此处获得NuGet软件包:

您可以在这里找到源代码:

下面是一些简单的代码,它将以静默方式从文件名打印任意数量的PDF文件副本。您也可以从流中加载PDF(这是我们通常的做法),通过查看代码或示例,您可以轻松了解这一点。还有一个WinForm PDF文件视图,因此您也可以将PDF文件渲染到视图中,或对其进行打印预览。对于我们来说,我只是需要一种方法,可以根据需要将PDF文件以静默方式打印到特定的打印机上

public bool PrintPDF(
    string printer,
    string paperName,
    string filename,
    int copies)
{
    try {
        // Create the printer settings for our printer
        var printerSettings = new PrinterSettings {
            PrinterName = printer,
            Copies = (short)copies,
        };

        // Create our page settings for the paper size selected
        var pageSettings = new PageSettings(printerSettings) {
            Margins = new Margins(0, 0, 0, 0),
        };
        foreach (PaperSize paperSize in printerSettings.PaperSizes) {
            if (paperSize.PaperName == paperName) {
                pageSettings.PaperSize = paperSize;
                break;
            }
        }

        // Now print the PDF document
        using (var document = PdfDocument.Load(filename)) {
            using (var printDocument = document.CreatePrintDocument()) {
                printDocument.PrinterSettings = printerSettings;
                printDocument.DefaultPageSettings = pageSettings;
                printDocument.PrintController = new StandardPrintController();
                printDocument.Print();
            }
        }
        return true;
    } catch {
        return false;
    }
}

下面的代码片段是对使用PdfiumViewer库打印pdf文件的代码的改编。主要区别在于使用的是流而不是文件

public bool PrintPDF(
    string printer,
    string paperName,
    int copies, Stream stream)
        {
            try
            {
                // Create the printer settings for our printer
                var printerSettings = new PrinterSettings
                {
                    PrinterName = printer,
                    Copies = (short)copies,
                };

            // Create our page settings for the paper size selected
            var pageSettings = new PageSettings(printerSettings)
            {
                Margins = new Margins(0, 0, 0, 0),
            };
            foreach (PaperSize paperSize in printerSettings.PaperSizes)
            {
                if (paperSize.PaperName == paperName)
                {
                    pageSettings.PaperSize = paperSize;
                    break;
                }
            }

            // Now print the PDF document
            using (var document = PdfiumViewer.PdfDocument.Load(stream))
            {
                using (var printDocument = document.CreatePrintDocument())
                {
                    printDocument.PrinterSettings = printerSettings;
                    printDocument.DefaultPageSettings = pageSettings;
                    printDocument.PrintController = new StandardPrintController();
                    printDocument.Print();
                }
            }
            return true;
        }
        catch (System.Exception e)
        {
            return false;
        }
    }
在我的例子中,我使用一个名为PdfSharp的库生成PDF文件,然后将文档保存到一个流中,如下所示:

        PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
        pdf.AddPage();

        MemoryStream stream = new MemoryStream();
        pdf.Save(stream);
        MemoryStream stream2 = new MemoryStream(stream.ToArray());
我想指出的一件事可能对其他开发人员有所帮助,那就是我必须安装32位版本的pdfuim本机dll,以便打印工作正常,即使我运行的是64位Windows 10。我使用Visual Studio中的NuGet软件包管理器安装了以下两个NuGet软件包:

  • PdfiumViewer
  • PdfiumViewer.Native.x86.v8-xfa

您可以使用DevExpress方法

public void打印(字符串pdfFilePath)
{
如果(!File.Exists(pdfFilePath))
抛出新的FileNotFoundException(“不存在这样的文件!”,pdfFilePath);
//创建Pdf文档处理器实例并将Pdf加载到其中。
PdfDocumentProcessor documentProcessor=新的PdfDocumentProcessor();
documentProcessor.LoadDocument(pdfFilePath);
如果(documentProcessor!=null)
{
PrinterSettings设置=新的PrinterSettings();
//var paperSizes=settings.paperSizes.Cast().ToList();
//PaperSize sizeCustom=paperSizes.FirstOrDefault(大小=>size.Kind==PaperKind.Custom);//查找纸张大小
settings.DefaultPageSettings.PaperSize=新纸张
public void Print(string pdfFilePath)
{
      if (!File.Exists(pdfFilePath))
          throw new FileNotFoundException("No such file exists!", pdfFilePath);

      // Create a Pdf Document Processor instance and load a PDF into it.
      PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
      documentProcessor.LoadDocument(pdfFilePath);

      if (documentProcessor != null)
      {
          PrinterSettings settings = new PrinterSettings();

          //var paperSizes = settings.PaperSizes.Cast<PaperSize>().ToList();
          //PaperSize sizeCustom = paperSizes.FirstOrDefault<PaperSize>(size => size.Kind == PaperKind.Custom); // finding paper size

          settings.DefaultPageSettings.PaperSize = new PaperSize("Label", 400, 600);

          // Print pdf
          documentProcessor.Print(settings);
      }
}
    public static void PrintFileToDefaultPrinter(string FilePath)
    {
        try
        {
            var file = File.ReadAllBytes(FilePath);
            var printQueue = LocalPrintServer.GetDefaultPrintQueue();

            using (var job = printQueue.AddJob())
            using (var stream = job.JobStream)
            {
                stream.Write(file, 0, file.Length);
            }
        }
        catch (Exception)
        {

            throw;
        }
    }