Print existing PDF (or other files) in C#

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!

Leave a Comment