使用 System.Drawing.Printing 发送文件打印不工作

Sending file to print not working using System.Drawing.Printing

我正在尝试按照此处几个答案的建议,在不通过 Adob​​e 打开文件的情况下发送文件进行打印;相反,我正在使用 PrintQueue 库(来自 System.Drawing.Printing)。

到目前为止我取得的成就:

我有正确的 PrintQueue 引用为 pq:

PrintQueue pq; //Assume it's correct. The way to get here it isn't easy and it is not needed for the question.

// Call AddJob
PrintSystemJobInfo myPrintJob = pq.AddJob();

// Write a Byte buffer to the JobStream and close the stream
Stream myStream = myPrintJob.JobStream;
Byte[] myByteBuffer = ObjectIHave.ToArray(); //Ignore the ObjectIhave, it actually is Linq object which is correct as well.
myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
myStream.Close();

正如我从 Microsoft Library 了解到的那样,它已正确完成,但无法正常工作。有什么想法吗?

编辑:调试代码我可以看到有东西正在发送到打印机,但似乎文件没有发送。

您不能只将 PDF 字节写入打印作业。打印机不知道如何处理它。您发送到打印机的 RAW 数据必须以打印机特定的打印机语言描述文档。这就是打印机驱动程序所做的。

您无法通过仅将 PDF 发送到打印机来打印它。您需要一些软件来呈现 PDF,然后将呈现的图像发送到打印机。

documentation 所述:

Use this method to write device specific information, to a spool file, that is not automatically included by the Microsoft Windows spooler.

我加强了这个信息的重要部分。

您需要将 PDF 渲染到打印机。调用文件上的 shell print 动词是实现此目的的理想方式。如果您坚持自己进行低级渲染,那么我建议您使用像 Ghostscript.NET and choose the mswinpr2 device as output.

这样的库

The mswinpr2 device uses MS Windows printer drivers, and thus should work with any printer with device-independent bitmap (DIB) raster capabilities. The printer resolution cannot be selected directly using PostScript commands from Ghostscript: use the printer setup in the Control Panel instead.

参见 SendToPrinterSample.cs 例如:

        string printerName = "YourPrinterName";
        string inputFile = @"E:\__test_data\test.pdf";

        using (GhostscriptProcessor processor = new GhostscriptProcessor())
        {
            List<string> switches = new List<string>();
            switches.Add("-empty");
            switches.Add("-dPrinted");
            switches.Add("-dBATCH");
            switches.Add("-dNOPAUSE");
            switches.Add("-dNOSAFER");
            switches.Add("-dNumCopies=1");
            switches.Add("-sDEVICE=mswinpr2");
            switches.Add("-sOutputFile=%printer%" + printerName);
            switches.Add("-f");
            switches.Add(inputFile);

            processor.StartProcessing(switches.ToArray(), null);
        }

如果文件必须双面打印,您只需添加:

switches.Add("-dDuplex");
switches.Add("-dTumble=0");