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

前端 未结 6 801
长情又很酷
长情又很酷 2021-01-05 07:53

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

6条回答
  •  执笔经年
    2021-01-05 08:48

    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
    

提交回复
热议问题