How to determine what "Ne" port the Adobe PDF printer is on?
c#, excel-interop, interop, pdf, printing
Solution
Here's what I ended up doing
using Microsoft.Win32;
...
var devices = Registry.CurrentUser.OpenSubKey( @"Software\Microsoft\Windows NT\CurrentVersion\Devices" ); //Read-accessible even when using a locked-down account
string printerName = "Adobe PDF";
try
{
foreach ( string name in devices.GetValueNames() )
{
if ( Regex.IsMatch( name, printerName, RegexOptions.IgnoreCase ) )
{
var value = (String)devices.GetValue( name );
var port = Regex.Match( value, @"(Ne\d+:)", RegexOptions.IgnoreCase ).Value;
return printerName + " on " + port;
}
}
}
catch
{
throw;
}
Problem
How can I detect what port (Ne01:, Ne02:, Ne99: etc) the printer is on? Computers (WinXP) here at BigCorp have Adobe Acrobat (version 7.0 Pro) installed which gives a virtual printer named "Adobe PDF". If you print an Excel (2003) workbook to pdf while recording a macro, the printer's full name is "Adobe PDF on Nexx:" where xx is a double digit.... and differs depending on what computer you try. I have written a C# console app using the Excel.Interop (I strongly discourage anyone else from starting down this road to hell) that opens a series of spreadsheets. It runs a macro in each one, saves, prints is as a pdf, then moves the pdf to a reports folder on a shared drive. The problem I face is that every install of Acrobat seems to pick a random port number for the PDF printer... and I can't figure out how to get it. So far I have tried using the Win32_Printer class like so ``` var searcher = new ManagementObjectSearcher( @"SELECT * FROM Win32_Printer" ); foreach ( ManagementObject printer in searcher.Get() ) { if ( Regex.IsMatch( printer["Name"].ToString(), @"(adobe|pdf)", RegexOptions.IgnoreCase ) ) { //printer["Name"]; => "Adobe PDF" //printer["PortName"] => "my documents/*.pdf" foreach ( PropertyData pd in printer.Properties ) { Console.WriteLine(string.Format("{0}, {1}", pd.Name, pd.Value)); } break; } } ``` I also poked around in the System.Drawing.Printing class. The PrinterSettings.InstalledPrinters will give you the name of the printer "Adobe PDF" but I can't figure out how to get the port info. If I pass just "Adobe PDF" to the excel interop PrintOut() method it sometimes works and sometimes fails with "Document failed to print"... I cannot figure out why. If I pass a hardcoded "Adobe PDF on Ne0x:" with an appropriate x value it works every time. If I try every possible variation, Excel helpfully prints to the default printer. I do not have the option of changing the default printer (security policy restriction) Can anyone point me to code that correctly pulls the printer port?