Click here to Skip to main content
15,127,095 members
Articles / Programming Languages / C#
Technical Blog
Posted 28 Sep 2016

Tagged as

Stats

41.2K views
10 bookmarked

Silently Printing PDF Documents in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
29 Sep 2016CPOL
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.

C#
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.

C#
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.

C#
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();
                }
            }        
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Thomas Cooper
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
BugCan't figure this out SetTracking is missing and not reference for PDFLibrary Pin
Member 1313860813-Mar-19 5:20
MemberMember 1313860813-Mar-19 5:20 
QuestionSetTracking method missed and PDF file could be not printed Pin
Member 81001806-Jan-18 2:26
MemberMember 81001806-Jan-18 2:26 
What does setTracking()? could you provide its implementation. Also, if you open adobe acrobat to print the PDF file, it can happen that you open adobe acrobat and just you just closd it before adobe acrobat can send the PDF file to the printer. So in this case, PDF file is not printed. I think you will need to wait a few seconds before closing adobe acrobat.
QuestionsetTracking Pin
Member 127734333-Oct-16 6:55
MemberMember 127734333-Oct-16 6:55 
QuestionCan you explain private static Liststring,string>> RegistrationKey; Pin
Member 127734333-Oct-16 6:26
MemberMember 127734333-Oct-16 6:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.