• 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

    • There is a default resolution setting in Settings > Display that can be changed with a click. You can also change the settings on a per-game basis. No CLI needed. Also, Steam has countless games that are not "[perpetual] alpha/beta games", so no need for the straw man. Plus you can use other stores as well. And console games (e.g. PS5) cost a fortune, which itself more than negates the price subsidy on the system, unless you plan on exclusively playing 1 or 2 games. It's true that you shouldn't buy a system that doesn't support the game(s) you want to play, but I think that's kinda obvious, and applies to every console as well as PC. I don't game in the living room and have no need of a Steam Machine, but there is a clear market segment that would find it useful.
    • RSS Guard 5.2.0 by Razvan Serea RSS Guard is a simple (yet powerful) feed reader. It is able to fetch the most known feed formats, including RSS/RDF and ATOM. It's free, it's open-source. RSS Guard currently supports Czech, Dutch, English, French, German, Italian. RSS Guard will never depend on other services - this includes online news aggregators like Feedly, The Old Reader and others. RSS Guard is developed on top of the Qt library and it supports these operating systems: Windows GNU/Linux OS/2 (eComStation) Mac OS X xBSD (possibly) Android (possibly) other platforms supported by Qt The core features of RSS Guard are: support for online feed synchronization via plugins, Tiny Tiny RSS (from RSS Guard 3.0.0). multiplatform, support for all feed formats, simplicity, import/export of feeds to/from OPML 2.0, downloader with own tab and support for up to 6 parallel downloads, message filter with regular expressions, feed metadata fetching including icons, simple Adblock functionality, customized popup notifications, Google-based auto-completion for internal web browser location bar, ability to cleanup internal message database with various options, enhanced feed auto-updating with separate time intervals, multiple data backend support, SQLite (in-memory DBs too), MySQL. is able to specify target database by its name (MySQL backend), “portable” mode support with clever auto-detection, feed categorization, drap-n-drop for feed list, automatic checking for updates, ability to discover existing feeds on websites, full support of podcasts (both RSS & ATOM), ability to backup/restore database or settings, fully-featured recycle bin, printing of messages and any web pages, can be fully controlled via keyboard, feed authentication (Digest-MD5, BASIC, NTLM-2), handles tons of messages & feeds, sweet look & feel, fully adjustable toolbars (changeable buttons and style), ability to check for updates on all platforms + self-updating on Windows, hideable main menu, toolbars and list headers, KFeanza-based default icon theme + ability to create your own icon themes, fully skinnable user interface + ability to create your own skins, “newspaper” view, plenty of skins, support for "feed://" URI scheme, ability to hide list of feeds/categories, open-source development model based on GNU GPL license, version 3, tabbed interface, integrated web browser with adjustable behavior + external browser support, internal web browser mouse gestures support, desktop integration via tray icon, localizations to some languages, Qt library is the only dependency, open-source development model and friendly author waiting for your feedback, no ads, no hidden costs. RSS Guard 5.2.0 changelog: Added: Feed auto-fetch can now also be delayed while Feral GameMode is active on Linux and startup auto-fetch is skipped when GameMode is already active. (#2265) WebEngine builds can now use RSS Guard generated proxy auto-config (PAC) rules so article/web browsing follows per-account and per-feed proxy settings more closely. (#2273) Generated PAC rules now also cover related subdomains and use Public Suffix List data, so feeds such as feeds.bbc.co.uk can also proxy resources from images.bbc.co.uk. (#2273) Standard feeds can now define extra proxy domains, useful when article images, stylesheets or other page resources are loaded from a CDN or another domain that should use the same feed proxy. (#2273) RSS Guard now asks for proxy credentials when a WebEngine page needs proxy authentication and can fill credentials from the current feed proxy when available. (#2273) Network settings again include an option to ignore all cookies, which clears stored cookies and prevents new cookies from being accepted. Standard RSS/ATOM feeds can now individually ignore cookies while downloading feed data. Stored cookies can now be deleted from the Tools menu. Custom skin colors can now override the feed list article count color separately from feed titles, including a separate highlighted color. (#2275) Settings dialog can now search across available settings and highlight matching controls. (#1754) Standard RSS/ATOM feeds can now optionally be reported as broken when they are valid but contain no articles. (#2039) Standard RSS/ATOM feeds can now override the application-wide feed connection timeout per feed. (#1023) Tray icon can now use a custom background color and unread-count text color, with an option to reuse the generated icon as the application icon. (#1973) Support for more benevolent parsing of Gemlog entries (#2295). Article list can now show when an article was received by RSS Guard. (#947) Feed deep discovery now actually scrapes all links found in the website and checks if they are feeds or not. This greatly enhances usability of the deep discovery mode and discovers many more feeds than before. (#2306) Search boxes now show a small dot when the feed or article list is hiding some items because of active filtering. (#873) Articles now have a shortcut-assignable action to open the homepage of the feed they belong to. (#2060) Fixed: Parallel feed updates no longer crash when multiple update results are processed at the same time. (64cf521) Links in WebEngine articles opened from feeds such as Kill the Newsletter now open correctly instead of being swallowed by the embedded page. (#2272) Relative article URLs resolution was kinda broken. (#2282) Clicking article URL did not work when the URL had "fragment" set. (#2293) The default proxy setting now uses Qt/system default proxy behavior instead of forcing no proxy. (e0263ad) WebEngine article loading now keeps the current feed context, so feed-specific proxy credentials remain available while the article page loads. (fdd0f00) Download: RSS Guard 5.2.0 (64-bit) | Portable | ~ 130.0 MB (Open Source) Link: RSS Guard Home Page | Other Operating Systems | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • This is gonna separate the creeps from the rest of the crowd.
    • "Claude, is our CEO a compete and utter fool by wasting money on AI in this already worthless Teams chat?"
  • Recent Achievements

    • Rookie
      DaviKar went up a rank
      Rookie
    • Dedicated
      HidekoYamamoto94 earned a badge
      Dedicated
    • 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
  • Popular Contributors

    1. 1
      +primortal
      462
    2. 2
      +Edouard
      161
    3. 3
      PsYcHoKiLLa
      110
    4. 4
      Michael Scrip
      83
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!