Geeks With Blogs
Martin Stefanov
| Home |

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


Posted on Thursday, October 9, 2008 8:35 PM C# - General , C# - Printing | Back to top


Comments on this post: Printing a PDF File to a (Network) Printer With C#

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Good workaround. Will give it a try :)
Left by Pooran on Jun 04, 2009 12:31 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Hi

tried this however it didn't work. Printer just spewed out plain text
Left by Sean on Jul 24, 2009 4:34 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Hi - this also spewed plain text for me

I am doing this directly:

File.Copy("C:\\" + ThePDFName, "\\\\localhost\\" + ThePrinter + "\\printing.pdf");

Do you need Acrobat propper or can you get away with the reader?

I'd really appreciate any advice
Left by Dan on Oct 12, 2009 7:55 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
The problem with this approach is that it seems the printer then does not print out international / scandinavian characters. (Like æ, ø and å)..

Left by Trond on May 19, 2010 5:42 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
I too needed to print PDF files. I found that Adobe Reader didn't close automatically after printing. I wound up using FoxIt reader to print PDF files. Foxit closes itself after printing if you use the command line options for printing. I also had to shell out to Foxit, and also with Adobe, to make them print but I was printing from another folder...
Left by George on Jul 01, 2010 12:49 PM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Did anyone get file.CopyTo or File.Copy to work on a local, non-shared printer?



Left by Mike on Feb 28, 2011 9:58 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
You are a genius. I have spent weeks on this problem.
Left by JackDogstar on Jun 30, 2011 3:21 PM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Amazing!
Well done!
So actually all needed is to set a network path for the shared printer...!
Left by DrNektar on Nov 08, 2011 8:58 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Hi,

We tried it and it does not work. R U Sure that it will print pdf file properly?

PDF file is printed as text file.

Rakesh
Left by Rakesh on Nov 16, 2011 11:14 PM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Absolutely brilliant! works perfectly in very few lines of code.
Left by kjward on Jan 11, 2012 3:20 PM

# Printing a .txt to a (Network) Printer for web application
Requesting Gravatar...
I am making a Web Part for a sharepoint site with .NET (visual studio 2010).

How can I add a button in my web part, clicking on which will print a .text file stored on my server's c: drive to a printer on the client side without prompting for a 'print' dialogue box?

The file to be printed is in the server's c: drive where the sharepoint site is hosted.

The printer will be a network printer.

I have used the code at http://www.dotnetspider.com/resources/43366-Printing-Datatable-Data-In-C.aspx for creating the .text file.

Please suggest.

Thanks in advance.
Left by nagen on Jul 26, 2012 4:03 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Brilliant! worked well for me... just whipped a small test application together, allowing me to select printer and file to send.. and there we go!
Left by Hans-Henrik on Feb 12, 2013 4:08 AM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
I tried above code to print a PDF file on a shared network printer. However, it printed all garbage characters instead of the actual contents.
The acrobat reader is installed on both the machines... machine where my program is running as well as the machine where the printer is connected.

Any idea what could be the reason for printing garbage?

Thanks.

Left by Vikram on Mar 28, 2014 3:12 PM

# re: Printing a PDF File to a (Network) Printer With C#
Requesting Gravatar...
Vikram, this approach of copying the pdf to the network share location of the printer does not make use of either system's installation of Adobe or anything else. The printer needs to natively support the PDF format. If it does, it will know what to do with the PDF. Try it with a text file and I bet you'll see it works.

The result you're having is the same I had trying a word doc, because my printer had no idea how to interpret a word doc, so it printed nonsense. The approach mentioned in this blog worked for me on a few printers I tried because they do support PDF. Otherwise, you'll need something client side to manually run the PDF through adobe. The network approach is great, though if the printer supports it, because it is very fast, there is no UI involved, and it even lets a server do printing (e.g. you could have an intranet site that allows users to print within a web app, something otherwise not possible).
Left by Jillian on May 15, 2014 7:34 PM

Your comment:
 (will show your gravatar)
 


Copyright © bleepzter | Powered by: GeeksWithBlogs.net | Join free