Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Silent Print Using C#

0.00/5 (No votes)
14 Mar 2012CPOL 34.6K  
Print you PDF silently using C#

Introduction

Most developers when they try to send jobs to a printer, they use Acrobat Reader via command line by setting the required parameters.

The problem is, that leaves Acrobat open if your client won't accept the pop-up window.

In this article I'll show you how to avoid this issue by using two useful utilities.

Background

In this solution, we'll use the suite of software Ghost Script developed by Artifex and Ghostgum (a graphical interface for GhostScript). Ghostscript is an interpreter for the PostScript page description language used by laser printers. In contrast, GSview allows you to preview and print your PDFs and other documents (.ps, .epi, and eps).

Using the code

To accomplish our task, we need to send the required paramaters to gsprint.exe under /GSView.

Note

GSview requires Ghostscript. GSview is available for Windows, Linux, and OS/2.

C#
private void Form1_Load(object sender, EventArgs e)
{
    ManagementObjectSearcher searcher;
    string Win32_Printer = "SELECT * FROM Win32_Printer";
    searcher = new ManagementObjectSearcher(Win32_Printer);
    foreach (ManagementObject mgmtobj in searcher.Get())
    {
        comboBoxPrinterName.Items.Add(mgmtobj["Name"].ToString()); return;
    }
}

private void buttonPrint_Click(object sender, EventArgs e)
{
    PrinterThread(comboBoxPrinterName.Text, textBoxDocumentPath.Text, true);
}

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
    textBoxDocumentPath.Text = openFileDialog1.FileName;
}

private void textBoxDocumentPath_MouseDoubleClick(object sender, MouseEventArgs e)
{
    openFileDialog1.ShowDialog();
}

public void PrinterThread(string printerName, string fileName, bool portrait)
{
     string gsArguments, gsLocation;
     ProcessStartInfo gsProcessInfo;
     Process gsProcess;
 
     if (portrait)
     {
         gsArguments = string.Format("-noquery -portrait -printer \"{0}\" \"{1}\"",
             printerName, fileName);
         gsLocation = @"C:\Program Files\Ghostgum\gsview\gsprint.exe";
     }
     else
     {
         gsArguments = string.Format("-noquery -landscape -printer \"{0}\" \"{1}\"",
              printerName, fileName);
         gsLocation = @"C:\Program Files\Ghostgum\gsview\gsprint.exe";
     }
     gsProcessInfo = new ProcessStartInfo();
     gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
     gsProcessInfo.FileName = gsLocation;
     gsProcessInfo.Arguments = gsArguments;
     gsProcess = Process.Start(gsProcessInfo);
     gsProcess.WaitForExit();
}

Conclusion

Many third party libraries still use Adobe Reader so here you get to do a clean job.

License

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