25

From an application I'm building I need to print existing PDFs (created by another app). How can I do this in C# and provide a mechanism so the user can select a different printer or other properties.

I've looked at the PrintDialog but not sure what file it is attempting to print, if any, b/c the output is always a blank page. Maybe I'm just missing something there.

Do I need to use "iTextSharp" (as suggested else where)? That seems odd to me since I can "send the the file to the printer" I just don't have any nice dialog before hand to set the printer etc. and I don't really want to write a printing dialog from the ground up but it seems like a lot of examples I found by searching did just that.

Any advice, examples or sample code would be great!

Also if PDF is the issue the files could be created by the other app in a diff format such as bitmap or png if that makes things easier.

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
  • Anyone here who knows how to print random files, not just pdfs? Tobi – Tobias Jun 19 '09 at 13:55
  • 3
    @Tobias: Random files are associated with random apps. Even .doc can be associated with WordPad, Word or OpenOffice. Each app will have its own rendering. Therefore the only useful approach is something that leverages Windows' file associations for the file types involved. – Ruben Bartelink Feb 13 '11 at 21:29
  • Related question: http://stackoverflow.com/questions/11579624/how-to-print-a-pdf-with-c-sharp – yms Mar 22 '13 at 16:15

6 Answers6

23

Display a little dialog with a combobox that has its Items set to the string collection returned by PrinterSettings.InstalledPrinters.

If you can make it a requirement that GSView be installed on the machine, you can then silently print the PDF. It's a little slow and roundabout but at least you don't have to pop up Acrobat.

Here's some code I use to print out some PDFs that I get back from a UPS Web service:

    private void PrintFormPdfData(byte[] formPdfData)
    {
        string tempFile;

        tempFile = Path.GetTempFileName();

        using (FileStream fs = new FileStream(tempFile, FileMode.Create))
        {
            fs.Write(formPdfData, 0, formPdfData.Length);
            fs.Flush();
        }

        try
        {
            string gsArguments;
            string gsLocation;
            ProcessStartInfo gsProcessInfo;
            Process gsProcess;

            gsArguments = string.Format("-grey -noquery -printer \"HP LaserJet 5M\" \"{0}\"", tempFile);
            gsLocation = @"C:\Program Files\Ghostgum\gsview\gsprint.exe";

            gsProcessInfo = new ProcessStartInfo();
            gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
            gsProcessInfo.FileName = gsLocation;
            gsProcessInfo.Arguments = gsArguments;

            gsProcess = Process.Start(gsProcessInfo);
            gsProcess.WaitForExit();
        }
        finally
        {
            File.Delete(tempFile);
        }
    }

As you can see, it takes the PDF data as a byte array, writes it to a temp file, and launches gsprint.exe to print the file silently to the named printer ("HP Laserjet 5M"). You could replace the printer name with whatever the user chose in your dialog box.

Printing a PNG or GIF would be much easier -- just extend the PrintDocument class and use the normal print dialog provided by Windows Forms.

Good luck!

Nicholas Piasecki
  • 25,203
  • 5
  • 80
  • 91
  • This helped me greatly. I have an intranet web application that has a requirement to print documents to a network printer unattended. All other methods have failed, but this one works! – Aaron Nov 01 '11 at 20:36
2

Although this is VB you can easily translate it. By the way Adobe does not pop up, it only prints the pdf and then goes away.

''' <summary>
''' Start Adobe Process to print document
''' </summary>
''' <param name="p"></param>
''' <remarks></remarks>
Private Function printDoc(ByVal p As PrintObj) As PrintObj
    Dim myProcess As New Process()
    Dim myProcessStartInfo As New ProcessStartInfo(adobePath)
    Dim errMsg As String = String.Empty
    Dim outFile As String = String.Empty
    myProcessStartInfo.UseShellExecute = False
    myProcessStartInfo.RedirectStandardOutput = True
    myProcessStartInfo.RedirectStandardError = True

    Try

        If canIprintFile(p.sourceFolder & p.sourceFileName) Then
            isAdobeRunning(p)'Make sure Adobe is not running; wait till it's done
            Try
                myProcessStartInfo.Arguments = " /t " & """" & p.sourceFolder & p.sourceFileName & """" & " " & """" & p.destination & """"
                myProcess.StartInfo = myProcessStartInfo
                myProcess.Start()
                myProcess.CloseMainWindow()
                isAdobeRunning(p)
                myProcess.Dispose()
            Catch ex As Exception
            End Try
            p.result = "OK"
        Else
            p.result = "The file that the Document Printer is tryng to print is missing."
            sendMailNotification("The file that the Document Printer is tryng to print" & vbCrLf & _
            "is missing. The file in question is: " & vbCrLf & _
            p.sourceFolder & p.sourceFileName, p)
        End If
    Catch ex As Exception
        p.result = ex.Message
        sendMailNotification(ex.Message, p)
    Finally
        myProcess.Dispose()
    End Try
    Return p
End Function
  • Sumatra PDF also has silent print command line args if gsview isn't your thing. http://blog.kowalczyk.info/software/sumatrapdf/manual.html – jmmr Mar 19 '11 at 17:04
  • Maybe Adobe printed silenty at one time but it doesn't any more. Downvoting because of this! – HK1 May 01 '17 at 19:27
1

I'm doing the same thing for my project and it worked for me

See if it can help you...

Process p = new Process();
p.EnableRaisingEvents = true; //Important line of code
p.StartInfo = new ProcessStartInfo()
{
    CreateNoWindow = true,
    Verb = "print",
    FileName = file,
    Arguments = "/d:"+printDialog1.PrinterSettings.PrinterName
};   
try
{
    p.Start();
} 
catch 
{ 
    /* your fallback code */ 
}

You can also play with different options of windows

PRINT command to get desired output...Reference link

Edwin de Koning
  • 14,209
  • 7
  • 56
  • 74
1

You could also use PDFsharp - it's an open source library for creating and manipulating PDFs. http://www.pdfsharp.net/

David Duffett
  • 3,145
  • 2
  • 26
  • 27
  • 7
    Note that PDFSharp uses Adobe Reader to print. Silent printing with Adobe Reader is unsupported by Adobe and a bit hacky. The authors even note this in the source. http://pdfsharp.codeplex.com/SourceControl/changeset/view/51421#707803 – jmmr Mar 19 '11 at 17:01
1

You will need Acrobat or some other application that can print the PDF. From there you P/Invoke to ShellExecute to print the document.

plinth
  • 48,267
  • 11
  • 78
  • 120
1

After much research and googling about this task Microsoft has released a great KB to print a pdf without any other applications necessary. No need to call adobe or ghostprint. It can print without saving a file to the disk makes life very easy.

http://support2.microsoft.com/?kbid=322091

Marko
  • 2,734
  • 24
  • 24