• 0

Printing across a network using C#


Question

Hi all

I am currently writing a service that will run once per day, retrieve data from a SQL database, and print some reports.

Here is the problem:

I have an xml config file which contains a report code (eg RPT001) and the printer it is to print to. This means that in future if I want to, I can simply change the printer name without too much disruption and the reports will be redirected elsewhere.

However, I am unable to set the printer name so that the report gets printed out. When I use :

// If we have specified a printer name print to this one otherwise the

// default printer will be used

if (_printerName != "")

{

pd.PrinterSettings.PrinterName = String.Format("{0}", _printerName);

}

A call to pd.PrinterSettings.IsValid, always returns false.

I have been looking into the PrintingPermissions topic, however I am unable to find a proper clear sample of how to use it so that I can grant access to my code to be able to print across the network.

The printers are connected to a central print server, however specifying "\\servername\printer" doesnt seem to work either.

To complete the picture, the code which performs the printing is in its own DLL and the service references this DLL.

What changes need to be made and where to get this to work?

Any and all help is very much appreciated :D

Link to comment
https://www.neowin.net/forum/topic/613622-printing-across-a-network-using-c/
Share on other sites

16 answers to this question

Recommended Posts

  • 0

Hi,

Printing permissions work like so:

PrintingPermission perm = new PrintingPermission(System.Security.Permissions.PermissionState.Unrestricted);
perm.Level = PrintingPermissionLevel.AllPrinting;

Setting PrinterSettings.PrinterName should accept the sting network printer name, however, it might be easier to create a server side local printer that points to the network printer, and print to the local printer instead.

I haven't done much printing in .NET yet, but I will keep looking into it for you.

  • 0

Ahh thanks for the reply, but where do I put this code?

Does it go into my service, or into the printing DLL.

Ultimately the service I am writing will sit on a server somewhere and just poll every day, so I need it to be as hassle free as possible

  • 0

Thanks Antaris for your help.

I actually got it working without the code permissions part. Turned out the printer names had been renamed to all caps and that was throwing the code off.

So when I changed these in my config file it worked fine.

  • 0

Ok, I'm back again with a similar issue and this one has me stumped.

After running fine for months, I added a new printer name to the xml file, in the same format ... \\server\printername

However, when the code runs normally, I get an error back saying the printer name is invalid:

// If we have specified a printer name print to this one otherwise the 
// default printer will be used
if (_printerName != "")
{
pd.PrinterSettings.PrinterName = String.Format("{0}", _printerName);
}


if (pd.PrinterSettings.IsValid != false)
{
			//  Print stuff here
}

However, when I step through the code in debug mode, IsValid becomes true and the reports print fine.

I figured it had something to do with how long it was taking me to step to the next line of code (some sort of network delay possibly on name resolution), so I added a Sleep statement on the current thread to see if that would fix it - no such luck.

I know the printer name is valid, as I can print to it when I step through the code in debug mode, however this has to be deployed and just work so this cant be an option.

Any ideas would be appreciated.

Thanks

  • 0

Yeah the versions are the exact same, the only thing that was different is the name of the printer being passed in.

I've actually now got this working:

1) Tried the source code on a colleagues machine ---> worked flawlessly, not a problem (!)

2) Removed the network printer from my machine (again) and it now works no problem (!)

So thats that little bit sorted out.

Now if only I could make the pages print properly in landscape mode, I'd be done.

I've tried setting

e.PageSettings.Landscape = true

in the PrintPage event handler, but it doesnt work the way I want it to.

Back to the drawing board. . . . . . . .

  • 0

Qwerky windows flaws eh?

Now if only I could make the pages print properly in landscape mode, I'd be done.

I've tried setting

e.PageSettings.Landscape = true

in the PrintPage event handler, but it doesnt work the way I want it to.

Back to the drawing board. . . . . . . .

You would have thought that would be the answer, but alas no, you have to apply that setting earlier:

public void DoPrint(string printerName) {
   PrintDocument document = new PrintDocument();
   document.PrinterSettings.PrinterName = printerName;
   document.DefaultPageSettings.Landscape = true;
   document.PrintPage += new PrintPageEventHandler(this.PrintPage);
   document.Print();
}

protected void PrintPage(object sender, PrintPageEventArgs e) {
   // do work
}

Hope that helps!

  • 0

Hi Antaris, thanks for your help, I tried that but that doesnt work either :(

I am working with custom written print code and I need to make it physically rotate the output on the page (like landscape, only every control and text box etc... has to be rotated by 90 degrees).

So its the mapping of one set of co-ordinates to another thats kind of got me a little stumped.

  • 0

Any gurus want to offer an explanation to this little doozey ?

I have some very simple test code to test whether or not the network printer I am printing to is valid or not (based on its name)

When I have it for printer 1 (example) I get True before and after I change the printer name

PrintDocument pd = new PrintDocument();

Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());
pd.PrinterSettings.PrinterName = @"\\printserver\printer1"
Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());

However when I have it for printer 2 (example) I get True before and False after I change the printer name.

Although when I delete printer 2 from Printers and Faxes and add it again, I get True, True, but any change to the printer preferences of this printer gives True, False again.

PrintDocument pd = new PrintDocument();

Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());
pd.PrinterSettings.PrinterName = @"\\printserver\printer2"
Console.WriteLine("PrinterSettings: {0}", pd.PrinterSettings.IsValid.ToString());

I am absolutely tearing my hair out over this now, and am about to throw it in the bin (figuratively of course).

Does anyone have any advice to offer me, network related, or hardware, or anything, it would be so much appreciated.

Thanks :D

By the way, printer 2 is a lexmark t644 printer, if that helps anything.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I've owned nothing but ATi/AMD GPUs since 2002, after my last nVidia GPU in 2001 (3dfx before that), IIRC, and in all of that time I recall getting this error maybe once, certainly no more than twice. Despite all the scuttlebutt as to how poor AMD drivers are supposed to be that has certainly not been my experience at all... Usually it has been a configuration problem of some kind. Then again, since we're dealing with OS versions that are EOL, it could easily be an OS version discrepancy. It's still weird to think that Win11 has been officially out for more than five years!
    • AI will never be the jobs panacea some companies fantasize about today. Oracle is likely using it as an excuse, which we will see a lot of companies doing, I'm certain. They love their "plausible" excuses for their downturns. A couple of weeks ago my wife asked me to call Krogers about some discrepancy in a online grocery order, and it will be the last time either of us does that. I'll just do emails with humans from now on... The AI experience was horrible--the obviously recorded voice started asking a bunch of questions about our orders six months prior(!) and saying, "Is this in reference to your order on January 6, for $****?" You say "No!" and immediately the next question is "Is this in reference to your order on January 29th, for $****?" again, I answered "No!"--and it was incredible--on and on it went like that for fully 20 minutes until we finally got to the present, and only then was I put through to a human with authentic intelligence... I wondered why on Earth the idiot AI didn't start with the most recent orders and work back from there, as it was something anyone with a functioning brain would have done. And why didn't the AI have enough sense to ask me what the problem was in the first place? It didn't take too much deduction to understand that the goal of this "AI" was to cause the person on the phone to hang up in disgust, with no resolution of the problem. That begs another question: why pay for a tool-free problem line if the goal is to avoid solving your customer's problems?... Fortunately, Krogers does have real humans capable of reading an email and understanding it, and if she sees another situation in the future that's route she or I will take. The online grocery delivery service from Krogers has been great, over all, but their AI truly sucks.
    • AI is the justification that company administrators use to lay people off; it is not the end all, be all touted in the media (many of whom can't tell a microchip from a potato chip). Greed is main driving factor behind its adoption; the other is remaining relevant in the face of competition from other entities.
    • Firefox 152.0.2 is out with fixes for performance, translation, and cloud storage services by Taras Buria A new bug-fixing update is now rolling out to Firefox users in the Release Channel. Less than a week ago, Mozilla fixed crashes on Intel Raptor Lake processors with version 152.0.1. Now, Mozilla has prepared yet another set of fixes that address problems with localization, playback issues of certain MP4 files, and performance issues on website that perform various encryption operations at once. Here is the full changelog: Firefox 152.0.2 is now available for download from Mozilla's FTP. Existing installations will get the update over the next several hours. The latest version will also be available soon on the official website, the Microsoft Store, and Neowin's Software page. You can find Firefox 152.0.2 release notes in the official documentation. In case you missed it, Mozilla released Firefox 152 earlier this month. The latest feature update brought reworked settings with a more streamlined user interface, JPEG XL support, new features for Private mode, a new way to mute a tab (just type "mute" in the address bar), and many more. You can find the complete changelog here. In other Firefox news, Mozilla recently published its roadmap, where the company detailed the upcoming Nova redesign and other features it plans to implement. Mozilla wants to make the new user interface easier to navigate and more modern, with a heavy focus on its privacy tools, such as its built-in VPN. If you are curious, you can already enable the new UI as described here.
  • Recent Achievements

    • One Month Later
      timbobit earned a badge
      One Month Later
    • One Month Later
      nates earned a badge
      One Month Later
    • Week One Done
      Almohandis earned a badge
      Week One Done
    • Rookie
      dorf went up a rank
      Rookie
    • First Post
      mike_rumble earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      481
    2. 2
      +Edouard
      172
    3. 3
      PsYcHoKiLLa
      103
    4. 4
      Michael Scrip
      88
    5. 5
      neufuse
      70
  • Tell a friend

    Love Neowin? Tell a friend!