简体   繁体   中英

c# Print PDF with Adobe Reader and close

I didnt found a good (free) and simple Solution for printing PDFs (for eg from a "Hot"-Folder (FileSystemWatcher) on a Server) with Acrobat and close Acrobat Reader. So i wrote my own and i hope it will help someone. (Yes, u can use a old free Foxit Reader Version, but we had too much trouble with it, sometimes stuck in Memory without printing)

The Point was, after printing, the file must be moved to a archive dir, but Adobe did not close. So i never knowed when its done, or wait 30+ Seconds and kill (not so fine if the Server needs longer and takes to much time).

Here my Solution, i run the Process and wait until one of the subprocesses of my Adobe Process shows the recent open Window.

Thanks to mtijn for his "Process Searcher" solution https://stackoverflow.com/a/7189381/480982

var prz = Process.Start("C:\\Program Files (x86)\\Adobe\\Acrobat Reader DC\\Reader\\AcroRd32.exe", "/h /t \"" + YOURPDFFILE + "\" \"" + YOURPRINTER + "\"");

            bool loop = true;
            while (loop)
            {
//u can use Thread.Sleep(x) too;
                prz.WaitForExit(500);

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(
       "SELECT * " +
       "FROM Win32_Process " +
       "WHERE ParentProcessId=" + prz.Id);
                ManagementObjectCollection collection = searcher.Get();
                if (collection.Count > 0)
                {

                    foreach (var item in collection)
                    {
                        UInt32 childProcessId = (UInt32)item["ProcessId"];
                        if ((int)childProcessId != Process.GetCurrentProcess().Id)
                        {

                            Process childProcess = Process.GetProcessById((int)childProcessId);

//If a File is open the Title begins with "Filename - Adobe ...", but after print/closing the recent window starts with "Adobe Acr..."
           if(childProcess.MainWindowTitle.StartsWith("Adobe Acrobat"))
                                {
                                loop = false;
                                break;
                            }


                        }
                    }
                }


            }



           //"Recent" Window found, lets kill the Process
            prz.Kill();


// Now here u can move or Delete the pdf file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM