Kris Krause .NET Meister

"If it is fast and ugly, they will use it and curse you; if it is slow, they will not use it."
- David Cheriton, The Art of Computer Systems Performance Analysis

Tuesday, February 08, 2005

Printing a Remote Document or Url Using C#

The following code enables a local machine to print a remote document or Url. One example would be a desktop application that needs to print a remote PDF or a Html producing web page.

The simple example downloads the file locally in order to print using the default printer. Sure there might be a better way to do this... and the code needs to be modified to handle "file not found", "url not found", and "unable to connect" exceptions in case a cable is loose. Cable? Who uses cable? It's all wireless nowadays!

using System;
using System.Diagnostics;
using System.Net;

namespace ShellPrint
{
class CMain
{
[STAThread]
static void Main(string[] args)
{
string lfile, file, ext;
Process proc = null;
WebClient client = null;

try
{
if (args.Length < 2) throw new ArgumentException("Invalid arguments passed.");

file = args[1].Trim();
ext = args[0].Trim();

client = new WebClient();

lfile = @"c:\" + DateTime.Now.Ticks + "." + ext;

Console.WriteLine("Downloading: {0}", file);

client.DownloadFile(file, lfile);

Console.WriteLine("Saving: {0}", file);

proc = new Process();

proc.StartInfo.FileName = lfile; 
proc.StartInfo.Verb = "Print";
proc.StartInfo.CreateNoWindow = true;

Console.WriteLine("Printing: {0}", lfile);

proc.Start();
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("Done and done.");
Console.ReadLine();
}
}
}
}

Labels:

1 Comments:

Post a Comment

<< Home