PDF: direct printing with .NET

Martin Zeller .net 46 Comments

>> Download Example project (VS 2005)

In this article I will show you the results of my search to find a way to print a pdf with .NET.

My task was to find a simple solution for an intranet web application where the user gets pdf reports (ActiveReports). Depending on configuration settings these pdf files should be displayed in the browser and be printed immediately or just be printed immediatly – to the default printer or to a known network printer.
The existing solution was based on the pdf browser plugins. But it was not satisfactory because the user had to do the following steps: view the pdf file in the browser (pdf browser plugin), click the print button, handle the printer dialog popup, click the OK button to send the document to the printer. And some users had to do this more then one hundred times a day. And some users had to do this more than a hundred times a day!
My (more than revolutionary 😉 idea was, that I may need the pdf browser plugin for viewing pdf files, but not for printing them! So I tried different ways, which I wanted you to show now – I did not bring all of them to an end, as some turned out to be inappropriate for  my intentions very soon.
Important: these solutions are only making sense if you want to print to a known printer (like in intranets) – they will not work on normal, „public“ web sites.

You can download the sample project and do your own experiments. Here is a screenshot of the sample project:

PrintingPDF WebApp Screenshot

My results:

  1. Printing a pdf with Ghostscript
  2. Printing a pdf with windows shell command
  3. Printing a pdf with PrintDocument object
  4. Printing a pdf with PDFsharp
  5. Printing a pdf with Acrobat Reader command line

1. Printing a pdf with Ghostscript

First you have to install Ghostscript, an interpreter for the PostScript language and for PDF. Code:

ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.Arguments = String.Format(" -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=1 -sDEVICE=ljet4 -sOutputFile=\"\\\\spool\\{0}\" \"{1}\"", printerName, pdfFileName);
psInfo.FileName = @"C:\Program Files\gs\gs8.70\bin\gswin32c.exe";
psInfo.UseShellExecute = false;
Process process = Process.Start(psInfo);

2. Printing a pdf with windows shell command

This is another version I found on the web. The code uses the print/printto command of the DOS shell. In the example project, which you can download above, there are two versions of parameters in the code. I never got it work, but I think, it cannot be done: you cannot print a pdf file via shell – but it will work with raw text files. Please tell me your results!
Try this in your DOS prompt:

print /D:"\\COMPUTERNAME\PRINTERNAME" "PDFFILEPATH"

For those who want to try it themselves

ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.Verb = "Print"; // or "PrintTo"
psInfo.FileName = pdfFileName;
psInfo.Arguments = String.Format("/p /h \"{0}\" \"{1}\"", pdfFileName, printerName);
psInfo.WindowStyle = ProcessWindowStyle.Hidden;
psInfo.CreateNoWindow = true;
psInfo.UseShellExecute = true;
Process process = Process.Start(psInfo);

3. Printing a pdf with PrintDocument object

Using the .NET object PrintDocument is another possible way, but you will need third party components to raster the pdf. More information: >>Component for rendering pdf documents

PrintDocument pd = new PrintDocument();
pd.DocumentName = pdfName;
pd.PrinterSettings.PrinterName =printerName;
pd.PrinterSettings.PrintFileName = fileName;
pd.PrintController = new StandardPrintController();
pd.OriginAtMargins = false;
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print();

4. Printing a pdf with PDFsharp

PDFsharp is an open source .NET library for processing PDF. You can use it for printing too. Simple usage, but the problem here: the AdobeReader application window appears (not suitable for my intentions). But I found out that you do not need PDFsharp to print out a pdf – see chapter 5

PdfFilePrinter.AdobeReaderPath = @"C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe"
PdfFilePrinter printer = new PdfFilePrinter(pdfFileName, printerName);
printer.Print();

5. Printing a pdf with Acrobat Reader command line

This was the best way for me! Although I’ve read that this only works with old versions of Acrobat Reader, it works with version 9.0!
A word to the arguments:
print it to the default printer: /s /o /h /p „pdfFileName“
print it to a defined printer: /s /o /h /t „pdfFileName“ „printername“ „drivername“ „portname“
More information at the Adobe Acrobat Developer FAQ on page 27!
To download the free acrobat reader use this link: Acrobat Reader

ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.FileName = @"C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe";
psInfo.Arguments = String.Format("/s /o /h /p{0}", pdfFileName);
psInfo.WindowStyle = ProcessWindowStyle.Hidden;
psInfo.CreateNoWindow = true;
psInfo.UseShellExecute = true;
Process process = Process.Start(psInfo);

Comments 46

  1. Very informative text. I’ve found your blog via Bing and I’m really happy about the information you provide in your posts. Btw your sites layout is really messed up on the Chrome browser. Would be great if you could fix that. Anyhow keep up the good work!

  2. 5. Printing a pdf with Acrobat Reader command line

    what i should download inorder to be able to use it?

  3. Post
    Author
  4. hi martin
    thank u about ur answer

    in fact i have visual studio 2008 and its give me error

    can u help me?
    my q2- i should get license for ur article or any files … DLL ..etc that included in ur project ? or all of them are open source?

  5. Post
    Author
  6. hi martin
    thank u alot about ur reply
    i have download PDFSharp

    but i dont know how to use it in asp.net ( ididnt see any PDFSharp.DLL)

    if u can help me i will be happy , and if u cant thank u alot 🙂

  7. hi,
    thank u alot about answering

    i have download pdfsharp,

    but when i want to add this to my asp.net application , ididnt any PDFSharp.DLL

    can u tell me the steps in order to be able to use it in asp.net ?

    thx

  8. Post
    Author
  9. I got error using Javscript function.How to solve below error

    ERROR: Automation server can’t create object

  10. Frohe Weihnachten und ein gutes neues Jahr verbunden mit Dank fuer die vertrauensvolle Zusammenarbeit. Merry Christmas and a Happy New Year with thanks for your faithful cooperation. Mit besten Wuenschen zu Weihnachten und das neue Jahr. With best wishes for Christmas and the New Year.

  11. Hi ,
    i want to use 5th step but the problem here is you have mentioned this is version specific. used only below versions less than Acrobat reader 9.0 . what command I have to use for greater than 9.0 versions . Any help would be great thanks in advance

  12. Post
    Author

    Hi ansar,

    my way works with versions less than or equal 9.0 – I never tried other versions. Maybe it still works!
    If it works, ansar, please, let me know.

    Kind regards
    Martin

  13. Hi ,
    I have tried the 5 th step but a popup of acrobat reader is blinked on and off. is there any solution for this thing because for one document if it will raise one popup for hundred documents what can happen.

    Thanks in advance

  14. Thanks for the reply I have tried with 9.0 version only. For my company requirement it should be configurable kind of stuff it should not be effected with the versions which client has .

  15. Post
    Author

    Ansar,
    in my case it was an intranet where it was clear which version would be on the clients.
    I think there isn’t any clean solution for direct printing if you cannot control the clients.

  16. Terrific! I have to agree this is speaking the truth. Keep it up.

  17. Hi i’m trying to use the number 2: Printing a pdf with windows shell command.. on a asp .net application.

    It works perfectly when i execute it on the Dev Server for debbugin of Visual Studio. But when i try the same code in the release version from another computer outside the server it doesn’t works.

    Any clue?

  18. Post
    Author

    Mauricio,
    I don’t know your requirements, but for sure, if the you want to print the pdf on the client, it won’t work this way, because you are calling the shell on the server!

  19. Hi Martin,

    No, i understand how it works! I know it will run on the server, the thing is that in my ASP application, when i run it from the visual studio(with the debugger) it prints my document just as you said.

    But when i publish my app in the IIS server and try to print the same doc it doesn’t do anything!

    I guess what is happening is that the default printer of my server is the Windows XPS document writer, but i have tried changing my default printer to the lexmark i have, and it doesn’t work!

    Thanks!!

  20. Post
    Author
  21. Hi i am trying to use the ghostscript implementation so does it have any prerequisites like installing Acrobat Reader on all machines ..i am new to programming so if you could explain help me understand the code where we pass the argument …

  22. Post
    Author

    Hi shalini,
    you need two things:
    1. ghostscript (see the link above)
    2. a printer

    Install ghostscript and put the appropriate path to psInfo.FileName
    Then look at the arguments: you need your printer name and the path to the pdf file (take the screenshot above as reference)

    Kind regards
    Martin

  23. Really Cool Work,

    Helped me a lot. Was gng through a lot of sites to get this soluiton.

    Thanks a lot buddy, keep up the good work. Cheers 🙂

  24. Pingback: Advanced

  25. Thanx alot !!

    Reallt kewl 🙂

    I want ur guidance Mr.Freelancer 😛

    hope yew’ll provide me wen ever I ask for 🙂 Thanx again 🙂

  26. Any way to print just one page without the Reader or Print Dialog popping up?

  27. good article, but i need to print a pdf file and not to open adobe’s windows (client machine). Can you help me in this job?. Thanks

  28. I’m really impressed together with your writing skills as smartly as with the layout to your weblog. Is that this a paid topic or did you customize it your self? Either way keep up the excellent quality writing, it is uncommon to see a nice blog like this one today..

  29. Amazing! Thanks Martin.
    After three years your same codes still works like a champ!

    I am using VS 2010, .Net 4.0, and IIS 7. I have tested using Adobe (used to be Acrobat) Reader (the latest) and Ghostscript (latest 9.06). The codes just work. I would choose Ghostscript for three reasons:

    1. Adobe Reader requires frequent security updates these dates, I don’t want that on my web server.
    2. Adobe Reader pops up automatically although laid minimized. This is a minor issue as I don’t mind it stays on the task bar. However, Ghostscript is totally clean. It pops up the commandline prompt to run but closes itself when finished.
    3. Adobe Reader is bloated and you never know what changes they would make after say, one year. Ghostscript has been always a minimalist in all this years.

  30. 5. Printing a pdf with Acrobat Reader command line
    Here the exception : The system cannot find the file specified

  31. Amazing article ….
    5. Printing a pdf with Acrobat Reader command line
    Dim strDelemiter =“@“
    Dim PrintPDF As New ProcessStartInfo

    Dim adobeOtherWay = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(„Software“).OpenSubKey(„Classes“).OpenSubKey(„acrobat“).OpenSubKey(„shell“).OpenSubKey(„open“).OpenSubKey(„command“)
    Dim pathOtherWay As String
    pathOtherWay = adobeOtherWay.GetValue(„“).ToString()
    PrintPDF.FileName = strDelemiter & pathOtherWay
    PrintPDF.Arguments = String.Format(„/s /o /h /p{0}“, BatchFile)
    PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
    PrintPDF.CreateNoWindow = True
    PrintPDF.UseShellExecute = True
    Process.Start(PrintPDF)

  32. I have a strange problem – I created a code such as this that works on my development system just fine (I use VS2012).
    When I deploy the same system to the server – the process starts an instance of Adobe reader, but I can just see the „process“ of Adobe listed in the task manager window – it doesn’t actually open Adobe nor does it print anything.
    Here is the code that I am using:
    ProcessStartInfo psInfo = new ProcessStartInfo();
    psInfo.FileName = string.Format(@“{0}“, executable);
    psInfo.Arguments = String.Format(@“{0}“, arguments);
    psInfo.WindowStyle = ProcessWindowStyle.Maximized;
    psInfo.CreateNoWindow = false;
    psInfo.UseShellExecute = true;
    Process process = Process.Start(psInfo);

    Any idea would be greatly appreciated.

  33. I am using GS example, but when print out comes it showing blank page. no print.

    however if i use Adobe example, its prints.

    Using VS2008, Window 7, ghost script ver 9.

    any help/comment appreciated.

  34. hi,
    I want to print all the images in a folder. i added all the files to list. but in processstartinfo everytime only one filename is accepting.and opening printwindow. but i want only one printwindow and all files in the list should preview in only one window. is it possible using processstartinfo…
    please explain

  35. sir,i am a beginner in development field. i need help from you. i am building a payroll system for my school project.in which i am stuck on pdf printing. my aim is to print the salary slip in pdf format just after clicking the button,no preview of pdf.is it possible?
    sir, please help me over this. this project is very important for me to get graduated.

  36. Hello Sir,
    I am using Bartender Application in asp.net for label printing. But while printing of the label I don’t want to be it printed where as we want it to generate PDF which is also get generated by using 3rd party printer driver software like BullZip.My Question is simple I want to get PDF without using of this printer driver software.I want to get the conversion of the file from .btw to .pdf. Please help me.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.