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

18,530

Solution 1

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();

Solution 2

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);
    }
}

Solution 3

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.

Solution 4

Here is a class that prints a Word doc without opening Word and showing the document. While I usually code in C#, I long ago learned that to code any Office automation with anything but VB.NET is downright silly (some of the upcoming features in C# 4.0 may change this).

This is only for Word, but Excel docs would be done in a similar fashion. For text documents, you can use the System.Drawing.Printing stuff pretty easily.

Imports System.IO 
Imports System.Windows.Forms 
Imports System.Drawing

Namespace rp.OfficeHelpers

    Public Enum PrintStatus
        Success
        FileNotFound
        FailedToOpenDocument
        FailedToPrintDocument
    End Enum

    Public Class Word

        Public Shared Function PrintDocument( DocumentName As String,_ 
                               PrinterName As String ) As PrintStatus 
            Dim wordApp As Microsoft.Office.Interop.Word.Application = _ 
                           new Microsoft.Office.Interop.Word.Application()
            Dim wordDoc As Microsoft.Office.Interop.Word.Document
            Dim copies  As Object = 1
            Dim CurrentPrinter As String = wordApp.ActivePrinter

            If ( Not File.Exists( DocumentName ) )
                Return PrintStatus.FileNotFound    
            End If

            wordApp.Visible = false

            wordApp.ActivePrinter = PrinterName

            ' Document name must be provided as an object, not a string.
            Try 
                wordDoc = wordApp.Documents.Open( CType( DocumentName, Object ) )
            Catch WordError as System.Exception 
                Return PrintStatus.FailedToOpenDocument
            End Try  

            Try 
                wordDoc.PrintOut( Copies := copies, Background:= false )
            Catch WordError as System.Exception 
                Return PrintStatus.FailedToPrintDocument
            End Try  

            wordApp.ActivePrinter = CurrentPrinter

            wordApp.Quit( SaveChanges := false )

            Return PrintStatus.Success        
        End Function

    End Class

End Namespace

Solution 5

I have to agree with other answers in that you can't print it without opening it.

The only way I think you may be able to get around this is if you had a straight-up postscript file, and a directly-attached postscript-compatible printer.

In that case you could just dump the .ps file to the LPT port and the printer would process it correctly.

Share:
18,530
Tobias
Author by

Tobias

Updated on June 15, 2022

Comments

  • Tobias
    Tobias about 2 years

    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

  • jerryjvl
    jerryjvl about 15 years
    I think you will need some libraries to help you out and implement your own printing code for each format... txt and jpg won't be too bad with the .NET Framework itself, but at the least you are going to need libraries for PDF and doc(x?)
  • Tobias
    Tobias about 15 years
    Das sieht gut aus. Jedenfalls für jpegs.
  • Nathan Koop
    Nathan Koop about 15 years
    Babelfish translation of Tobias's comment: "That looks good. Anyhow for jpegs"
  • John Saunders
    John Saunders about 15 years
    This may not show the document, but it certainly opens it. It also won't work in a multithreaded environment, as the Office APIs are meant for desktop automation (let alone licensing issues). Don't know if that matters to the OP, but just to get it on the record.
  • rp.
    rp. about 15 years
    That's a good distinction, John. My use of the word "open" was sloppy.
  • joshua.ewer
    joshua.ewer about 15 years
    If you look at the link, you will see several examples of how to print other types of documents, all using the same class. Which, per your question, is exactly what you wanted, no?
  • Luciano
    Luciano over 9 years
    Easy for "JPEG". But sorry, no so easy for PDF or more complex types of documents.
  • h0cc0i
    h0cc0i almost 8 years
    That's a good distinction but, in Excel file case, how I can do something same like that.