Printing a PDF File to a (Network) Printer With C#

Could it really be this simple?

For all you developers out there wondering how to print a PDF file, here is my story and the idiotically siple solution to this problem. After pulling my hair for days, researching printing with the System.Printing and System.Drawing.Printing namespaces in C#, I was ready to jump out of the tallest building in my area!!! The deadline was comming closer by the minute, yet the project's last component (printing) was not even finished.

Out of desperation I decided to try something that I haven't tested before. I had realised that the (network) printer is just another folder in Windows, and decided to give it a shot. The following code describes the discovery process via WMI:

1. Windows Form with a Button (cmdGetPrinters) and a ListView (lstPrinters). The list view has two columns defined - "Property" and "Value" which would describe the printers installed on the local machine. The following code does the magic.

using System;                                                              using System.Collections.Generic;                                          
using System.ComponentModel;                                               using System.Data; System.Drawing;                                         using System.Text; System.Windows.Forms;                                   using System.Management;                                                   using System.Management.Instrumentation;                                                                                                               public partial class frmPrintDisplay : Form                                
{                                                                                public frmPrintDisplay()                                               
     {                                                                      
          InitializeComponent();                                            
     }                                                                                                                                                       private void cmdGetPrinters_Click(object sender, EventArgs e)          
     {                                                                               ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Printer");                                                                                     ManagementObjectSearcher mo = new ManagementObjectSearcher(query);                                                                                      ManagementObjectCollection printers = mo.Get();                                                                                                        foreach (ManagementObject printer in printers)                     
        {                                                                              PropertyDataCollection printerProperties = printer.Properties;             string printerPath = printer.Path.ToString() ;                             PropertyDataCollection.PropertyDataEnumerator test =            
                printer.Properties.GetEnumerator();                                                                                                                 while(! (test.MoveNext()== false ))                            
            {                                                               
                lstPrinters.Items.Add(                                                          new ListViewItem( new string[]                          
                    {                                                       
                        test.Current.Name,                                  
                        (                                                  
                            (test.Current.Value == null) ?                  
                            "n/a" : test.Current.Value.ToString()          
                        )                                                   
                    })                                                      
                );                                                         
            }                                                               
        }                                                                       }                                                                       
}                                                                          

This image shows the result of this small windows app. Note the "Name" property, this will be used to send the pdf file to the printer. Because in my case, I had to deal with network priners, I decided to go to the printer properties and share the printer with my workgroup / (domain for AD). This is shown under the "ShareName" property of the printer. On a test machine, which is also in the same domain/workgroup, I installed a new network printer, and pointed the installation to look at the shared printer on the first computer. This in effect made the first computer a printer server, and i was able to closelly replicate the setup for the client. The print server name (machine name) in this scenario we can call "XYZ", and the printer "ShareName" is Phaser77, as it is shown in the picture above.

Now onto the test machine... The application that I was building saves the PDF files into a temporary directory called C:\Program Files\[Application Name]\Temp\

using System;                                                              
using System.Collections.Generic;                                          
using System.ComponentModel;                                               using System.Data; System.Drawing;                                         using System.IO;                                                           
using System.Text; System.Windows.Forms;                                   using System.Management;                                                   using System.Management.Instrumentation;                                                                                                               /* the stuff in between is not relevant that's why its not included  */     
                                                                            
private void print(ref DirectoryInfo tempDir)                              
{                                                                          
    try                                                                    
    {                                                                       
        foreach(FileInfo file in tempDir.GetFiles("*.pdf"))                         {                                                                   
            file.CopyTo("\\\\XYZ\\Phaser77\\" + file.Name);                 
        }                                                                   
    }                                                                      
    catch(Exception ee){ }                                                 
}                                                           

Ok, so now that the file is actually placed in the directory, it will print with a fiew exceptions. First, the testing machine that runs the application has to have adobe pdf installed on it, otherwise the printer doesn't know how to interpret the file if it is an extension not native to windows (such as *.pdf ). Second, there might be some permissions issues that need to be worked out for the copy process.... The application itself might have to run under a domain admin account.

That's it!

bleepzter
http://www.commercegeneration.com
http://www.maxit.biz
http://www.3plconnect.com

This article is part of the GWB Archives. Original Author: bleepzter

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.