• 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?

  ramesees said:
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 set since XP - Best performance in the Performance settings. 11 included. I enable only the show shadows after that, so I can see better fonts and mouse.. But hardly I can say I can see a difference today.
    • Yeah this kinda means nothing to me if it's going to be the same mess as HDMI 2.1 where it was difficult to know what features you were getting. It was way too confusing, designed to fool us into thinking we was getting something better with the higher number when a lot of the times we didn't get anything better because companies can add and remove features at will, which if that is the case for 2.2, then who cares lol.
    • Someone wrote a script to block 'brainrot' content online using an $8 smart plug by Usama Jawad Original image via Neil Chen Many people use smart plugs nowadays due to the various advantages they offer, including automation, integration with mobile software, increased home security, better energy efficiency, and compatibility with other smart products. However, a smart plug customer has gone a step further by enhancing their hardware in a way that it blocks them from viewing "brainrot" content online, or any website, for that matter. As seen in a popular thread over on Hacker News, a person known as "NWChen" has written a script that connects to the $8 Kasa Smart Wi-Fi Plug Mini and utilizes it to restrict access to websites of your choice. In essence, this plug then acts as a physical switch that you can toggle to visit certain websites. NWChen's main motivation behind this initiative was to avoid brainrot, with examples listed as X (formerly known as Twitter), Instagram, YouTube, and Reddit in their blog post. In terms of technical functionality, the smart plug connects to Wi-Fi (obviously) and hosts a physical switch that can be used to turn it on and off. NWChen's script connects to the smart plug via an API and then polls its state. If it's on, websites of your choice get restricted and you can't open them anymore, until you physically get up and turn off the plug, or remove the website from you blocklist. NWChen has recommended plugging in the hardware far away from you so there is sufficient resistance in turning off the plug. In the thread, many have praised this invention, believing that the nature of this mechanism provides enough hurdles where you'd rather just not visit the problematic websites anymore. However, some have noted that "those without self control cannot be trusted if they hold the switch". Some have also highlighted a problem where a user can simply stop the script's execution without much friction. Overall, it's a fairly interesting setup, even if it's fairly rudimentary in nature. Configuring this physical block with a Kasa smart plug is fairly easy. You can simply download the script from the laptop-brick GitHub project here, install it, get the IP address of your smart plug, and then use it when you're executing the script. You can modify the blocklist using a dedicated file present inside the GitHub project.
    • We'll probably mirror the EU rule, we've done that in many other areas, but if we don't, well we can add this as another reason why Brexit shouldn't have happened. Personally, if I started to get ads in WhatsApp, that would be a big incentive for me to want to switch to an alternative, and I doubt it will be difficult for me to get my contacts to change as well.
    • It reminds me of fossil fuels, as they try to push the price up and renewable energy continues to get better and cheaper, it's putting the squeeze on the fossil fuel industry. In this case, bringing jobs back to modern countries with higher wages would be a big incentive for corporations to remove humans from the workforce and replace them with AI and robotics, and the funny thing is about that, consumers will demand it because they want things cheaper not more expensive, also corporations will be forced to do it if they want to survive against others that go that route. At the end of the day, they didn't pick cheap labour because they wanted to do so, they did so because competition forced companies to do so, bringing jobs back to western countries would make these companies less competitive on the world stage, unless they use a lot more AI and robotics to remove a lot of humans from the workforce. With that said, bringing jobs back to more stable regions and using AI and robotics does have the benefit of reducing the risk of political trade wars and tariffs, but let's forget this idea of jobs coming back home to higher paying wages, that idea is dead in the water with the advancement of AI and robotics, and with humans, it would only end up making a lot more things more expensive.
  • Recent Achievements

    • Conversation Starter
      Brett76 earned a badge
      Conversation Starter
    • One Month Later
      Miguel Batista earned a badge
      One Month Later
    • Dedicated
      moojay67 earned a badge
      Dedicated
    • One Month Later
      Jim Dugan earned a badge
      One Month Later
    • First Post
      Johnny Mrkvička earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      653
    2. 2
      Michael Scrip
      229
    3. 3
      ATLien_0
      220
    4. 4
      Steven P.
      151
    5. 5
      Xenon
      144
  • Tell a friend

    Love Neowin? Tell a friend!