Printing pdf without preview in c #

2020-08-04 04:16发布

问题:

I am trying to print .pdf and .tif files using C# in windows application.

Printing is done successfully, but my problem is Adobe reader is opening in background for pdf files and windows print dialogue opens for tif files.

Actually i will run my method using a service, so these process should occur silently. What can I do to avoid this?

Here is my code

public void PrintDocument(string filepath)
        {

            //PrintDialog pd = new PrintDialog();            
            printProcess.StartInfo.FileName = filepath; 
            //Also tried usecellexcecution=false;
            //Redirect=true; something like this
            printProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            printProcess.StartInfo.Verb = "Print";
            printProcess.StartInfo.CreateNoWindow = true;
            PrinterSettings setting = new PrinterSettings();
            setting.DefaultPageSettings.Landscape = true; 
            printProcess.Start();
            printProcess.CloseMainWindow(); 
        }

I have tried to use RawprinterHelper suggested in MSDN, but it prints junk characters.

回答1:

Get the window handle of the pdf process and then hide it or use process class's windowstyle to minimize it.

Yes it gets launched because you are using Process.Start.



回答2:

If your printer is on a network and you know it's IP address it might be possible to send the file directly to the printer using TcpClient. I've got this to work for my printer, but have only tried it for PDFs so I don't know how well it will work for other printers/file types.

You will have to change your printer settings so that it is using a tcp port (In devices and printers select your printer (single click), then click print server properties, in the wizard that opens you can add a new TCP port). You will also have to set the printer to raw rather than lpc settings

I then used something similar to the following method;

        public void SilentPrint(string filePath, string printerIPAddress)
    {
        byte[] bytes = System.IO.File.ReadAllBytes(filePath);

        var client = new TcpClient(printerIPAddress, 9100);//9100 is the default print port for raw data

        using (var stream = client.GetStream())
        {
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
        }
    }


回答3:

If you want to print a PDF silently then you will need to use the right tool for the job. In this case it isn't Adobe Reader because it will always launch the application window, it doesn't load in silent mode.

Find a a PDF library that will silently let you print PDFs.



回答4:

try "PrintTo" as your Verb. This should disable the 'print preview' stage.



标签: c# pdf printing