Print existing PDF (or other files) in C#
Solution 1
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!
Solution 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
Solution 3
You will need Acrobat or some other application that can print the PDF. From there you P/Invoke to ShellExecute to print the document.
Solution 4
You could also use PDFsharp - it's an open source library for creating and manipulating PDFs. http://www.pdfsharp.net/
Solution 5
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
Related videos on Youtube
Raymond
I minimise the biggest liability in any system: Code, mostly by talking to customers so we achieve what they mean. I've been working hard on only writing it when in the Red and keeping it composable since 2006, but I have a few decades left to perfect the art... Mail: my first name at my second name dot com Work: Jet, ProductFitter, InishTech linkedin / +rbartelink / facebook
Updated on August 14, 2020Comments
-
Raymond almost 4 years
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.
-
Tobias about 15 yearsAnyone here who knows how to print random files, not just pdfs? Tobi
-
Raymond over 13 years@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.
-
yms over 11 yearsRelated question: stackoverflow.com/questions/11579624/…
-
-
Aaron Fischer over 15 yearsCan you pass printer selection and other parameters with that call?
-
jmmr over 13 yearsNote 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. pdfsharp.codeplex.com/SourceControl/changeset/view/51421#707803
-
jmmr over 13 yearsSumatra PDF also has silent print command line args if gsview isn't your thing. blog.kowalczyk.info/software/sumatrapdf/manual.html
-
Aaron over 12 yearsThis 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!
-
Box almost 9 yearsIt works on some printers. The printer needs to be able to process PDF files itself. If it doesn't, the PDF file prints as if it was a text file.
-
HK1 about 7 yearsMaybe Adobe printed silenty at one time but it doesn't any more. Downvoting because of this!
-
Syed Irfan Ahmad about 3 yearsThe above link is redirected to support.microsoft.com/?kbid=322091 and there is nothing