Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: How to print files w/o opening them

We have an application that basically archives files and we give the user the possibility to print these files. They can be .txt, .doc, .pdf, .jpg nothing fancy. Is there a .NET way to send these files to the printer without handling them further, ie opening them?

I already tried creating a process with the StartInfo.Verb = "print"

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = fileName;
p.StartInfo.Verb = "print"
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

p.Start();

It still opens the file which I don't want. Can someone help?

Any help would be appreciated. Tobi

like image 641
Tobias Avatar asked Jun 19 '09 14:06

Tobias


3 Answers

My understanding is that most apps will open (even briefly) when you print. Try right-clicking a MS Word document and hitting print. You'll see Word open, print, and close.

However, you might want to add this to your code to keep the process hidden and to close when finished:

p.Start();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (p.HasExited == false)
{
   p.WaitForExit(10000);
}

p.EnableRaisingEvents = true;
p.CloseMainWindow();
p.Close();
like image 130
C-Pound Guru Avatar answered Oct 07 '22 17:10

C-Pound Guru


It's actually very, very easy.

Use System.Drawing.Printing.PrintDocument.

Follow the example in that link, or just use the code here (which I excerpted from something doing print automation I'm using every day).

for example, to print off a .jpg (BTW, this won't open any editing application; it spools to the printer in the background)

public void SetupPrintHandler()
{
    PrintDocument printDoc = new PrintDocument();
    printDoc.PrintPage += new PrintPageEventHandler(OnPrintPage);

    printDoc.Print();
}

private void OnPrintPage(object sender, PrintPageEventArgs args)
{
    using (Image image = Image.FromFile(@"C:\file.jpg"))
    {
        Graphics g = args.Graphics;
        g.DrawImage(image, 0, 0);
    }
}
like image 41
joshua.ewer Avatar answered Oct 07 '22 18:10

joshua.ewer


How do you suggest Windows manage to print a file without sending it to an application that knows how to handle it?

I don't think there is a way to do this, simply because Windows does not know what a pdf is (or a doc, or even a jpg).

I'm afraid you're stuck with either what you have, or including a library into your application for each format that you wish to print.

like image 2
jerryjvl Avatar answered Oct 07 '22 17:10

jerryjvl