65.9K
CodeProject is changing. Read more.
Home

Silently Printing PDF Documents in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Sep 29, 2016

CPOL
viewsIcon

54029

How to silently print PDF documents in C#

This simple class below will print a PDF document, using Adobe silently.

Get Printer Name

This gets the default printer name from the Printer dialog:

private static void getPrinterName()
{
    PrintDialog pt = new PrintDialog();
    printerName = pt.PrinterSettings.PrinterName;
}

Get Document Title

This logic was designed around PDF and this method will get the Title of the PDF document.

private static void getDocumentTitle()
{
    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(printFileName);            
    documentTitle = reader.Info["Title"];
}

Set Start Process

This will put the main element of the process together and set the start process to use Adobe and pass the document location and printer as an argument.

This is meant to run Adobe silently, but now Adobe shows for a few seconds and then closes, once the print command is completed.

private static void setProcess()
{
    string flagNoSplashScreen = "/s /o";
    string flagOpenMinimized = "/h";
    var flagPrintFileToPrinter = string.Format("/t \"{0}\" \"{1}\"", printFileName, printerName);
    var args = string.Format("{0} {1} {2}", 
               flagNoSplashScreen, flagOpenMinimized, flagPrintFileToPrinter);
            
    startInfo = new ProcessStartInfo
    {
        FileName = applicationPath,
        Arguments = args,
        CreateNoWindow = true,
        ErrorDialog = false,
        UseShellExecute = false,
        Verb = "print",
        WindowStyle = ProcessWindowStyle.Minimized,
        RedirectStandardInput = true,
        RedirectStandardOutput = false
    };            
}

Get EXE Application Path from Registration

Get the application path from the system registry. So Adobe needs to be installed and this logic will return nothing if not installed.

private static Liststring,string>> RegistrationKey;
private static string allocatedPath;

public static string Allocate()
{
createRegistrationKey();
getInstalledApplicationPath();

return allocatedPath;
}

//This will set a list of different keys
private static void createRegistrationKey()
{

RegistrationKey = new Liststring, string>>();
RegistrationKey.Add(new Tuple<string, string>("Adobe", 
@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Acrobat.EXE"));
RegistrationKey.Add(new Tuple<string, string>("Adobe32", 
@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRD32.EXE"));
}

//This checks the registry for a path and if found it wont look for any other
private static void getInstalledApplicationPath()
{
allocatedPath = string.Empty;
foreach (var s in RegistrationKey)
{
allocatedPath = getRegistryApplicationPath(s.Item2);
if (!string.IsNullOrEmpty(allocatedPath))
{
break;
}
}
}

//This method will look within the registry for a path, using the key provided
private static string getRegistryApplicationPath(string applicationKey)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(applicationKey);
if (key != null)
{
return key.GetValue("").ToString();
}

return String.Empty;
}

Run Process

This is the main method, with run the logic.

public static void Print(string path)
        {
            printFileName = path;
            getDocumentTitle();
            getPrinterName();
            setTracking();
            applicationPath = PDFLibrary.ApplicationEXEPath.Allocate();
            if(!String.IsNullOrEmpty(applicationPath))
            {
                setProcess();
                using (var process = Process.Start(startInfo))
                {
                    process.CloseMainWindow();
                    process.Kill();
                }
            }        
        }