Print Pdf in C# [closed]
Asked Answered
D

16

52

I'm new to c#. I was looking all over the net for tutorials on how to print pdf, but couldn't find one.

Then I thought, is it possible to read it using itextpdf, like mentioned here

Reading PDF content with itextsharp dll in VB.NET or C#

then print it. If so, how?

Diatropism answered 6/4, 2011 at 12:17 Comment(0)
M
77

A very straight forward approach is to use an installed Adobe Reader or any other PDF viewer capable of printing:

Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
    CreateNoWindow = true,
    Verb = "print",
    FileName = path //put the correct path here
};
p.Start( );

Another way is to use a third party component, e.g. PDFView4NET

Mathur answered 6/4, 2011 at 12:21 Comment(4)
Great answer, but note that Process inherits from component which implements IDisposable, so it is of course recommended to dispose it or use a using statement, especially if one uses it many timesSellars
Ohh, you're using shellexecute, with the "print" verb. Right. Do note Adobe Reader's latest versions don't seem to properly close the window after printing. Also, this will probably not be a silent print command; it'll show a popup for print options.Overline
I print by commandline using sumatra.exe (just 1 exe and no bloatware necessary) and btw you have some options to configure printing: sumatrapdfreader.org/docs/Command-line-arguments.htmlSpeculator
Please note PDFview4NET is (now) not free. Their solutions run in the hundreds of $.Ejectment
U
30

I wrote a little helper method around the adobereader to bulk-print pdf from c#...:

  public static bool Print(string file, string printer) {
     try {
        Process.Start(
           Registry.LocalMachine.OpenSubKey(
                @"SOFTWARE\Microsoft\Windows\CurrentVersion" +
                @"\App Paths\AcroRd32.exe").GetValue("").ToString(),
           string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
        return true;
     } catch { }
     return false;
  }

One cannot rely on the return-value of the method btw...

Ursine answered 29/6, 2011 at 14:15 Comment(2)
@ColtonMilne afair it's the same name that shows up in the control panel... from code: give the system.drawing.printing.printersettings.installedprinters property a shot!Ursine
afaik as soon as you threw your job into the spooler it's "his thing" - so you'd have to talk to the print spooler: codeproject.com/Articles/51085/…Ursine
G
18

Another approach, if you simply wish to print a PDF file programmatically, is to use the LPR command: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/lpr

LPR is available on newer versions of Windows too (e.g. Vista/7), but you need to enable it in the Optional Windows Components.

For example:

Process.Start("LPR -S printerdnsalias -P raw C:\files\file.pdf");

You can also use the printer IP address instead of the alias.

This assumes that your printer supports PDF Direct Printing otherwise this will only work for PostScript and ASCII files. Also, the printer needs to have a network interface installed and you need to know it's IP address or alias.

Gnu answered 6/7, 2011 at 12:15 Comment(0)
A
16

Use PDFiumViewer. I searched for a long time till I came up with a similar solution, then I found this clean piece of code that does not rely on sending raw files to the printer (which is bad if they get interpreted as text files..) or using Acrobat or Ghostscript as a helper (both would need to be installed, which is a hassle):

https://mcmap.net/q/224729/-how-can-i-send-a-file-document-to-the-printer-and-have-it-print

PDFiumViewer comes via nuget, the code example above is complete. Pass in null values for using the default printer.

Aman answered 8/9, 2017 at 12:10 Comment(3)
PdfiumViewer enabled me printing pdfs. don't waste your time on spire.pdf (outdated examples/documentation and no valid license provided even after registering with email)Sheep
Another +1 for PDFiumViewer. In .NET Core there's also the package PdfiumViewer.Updated. You still need the pdfium.dll in the x64 and x86 folders (see: github.com/pvginkel/PdfiumBuild). PDFiumViewer also makes it easy to control the page orientation and layout.Oxblood
as stated in its Git repository, the owner abandoned/archived this project.Iata
B
8

I had the same problem on printing a PDF file. There's a nuget package called Spire.Pdf that's very simple to use. The free version has a limit of 10 pages although, however, in my case it was the best solution once I don't want to depend on Adobe Reader and I don't want to install any other components.

https://www.nuget.org/packages/Spire.PDF/

PdfDocument pdfdocument = new PdfDocument();
pdfdocument.LoadFromFile(pdfPathAndFileName);
pdfdocument.PrinterName = "My Printer";
pdfdocument.PrintDocument.PrinterSettings.Copies = 2;
pdfdocument.PrintDocument.Print();
pdfdocument.Dispose();
Burrstone answered 27/7, 2015 at 20:39 Comment(2)
Spire PDF is commercial software that needs a paid license. Comments that recommend packages should be clear on the difference between open source and commercial purchases. The free version prints a banner in the PDF so even if you are printing small files, it will show up.Glairy
This answer is quite old. At that time the only limitation was the page number. So now it has a banner as you said. Good to know to alert new users.Burrstone
H
6

The best way to print pdf automatically from C# is using printer's "direct pdf". You just need to copy the pdf file to printer's network sharename. The rest will be taken care by printer itself.

The speed is 10 times faster than any other methods. However, the requirements are the printer model supporting for direct pdf printing and having at least 128 MB Dram which is easy for any modern printer.

Hermaphroditism answered 13/6, 2019 at 8:42 Comment(0)
V
5

You can create the PDF document using PdfSharp. It is an open source .NET library.

When trying to print the document it get worse. I have looked allover for a open source way of doing it. There are some ways do do it using AcroRd32.exe but it all depends on the version, and it cannot be done without acrobat reader staying open.

I finally ended up using VintaSoftImaging.NET SDK. It costs some money but is much cheaper than the alternative and it solves the problem really easy.

var doc = new Vintasoft.Imaging.Print.ImagePrintDocument { DocumentName = @"C:\Test.pdf" };
doc.Print();

That just prints to the default printer without showing. There are several alternatives and options.

Vulvitis answered 12/7, 2013 at 17:1 Comment(2)
See PDFsharp on Github for the latest version source code.Encephalomyelitis
PDFsharp uses Adobe acrord32.exe to print. See source code.Encephalomyelitis
N
2

It is possible to use Ghostscript to read PDF files and print them to a named printer.

Nitrogenous answered 7/4, 2011 at 20:2 Comment(0)
M
2

The easiest way is to create C# Process and launch external tool to print your PDF file

private static void ExecuteRawFilePrinter() {
    Process process = new Process();
    process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
    process.Start();
    process.WaitForExit();
}

Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter

Mortal answered 15/6, 2016 at 10:30 Comment(2)
But if you don´t mind a bit additional programming work (in Java) then you could replace RawFilePrinter.exe by a custom program using the open source Apache PDFBox link.Edwardedwardian
+1 for RawFilePrinter which has a portable version that doesn't need an installation. Unfortunately it seems to scale the PDF a bit which leads to some lines at the bottom not being printed. Same behavior like when using "copy <file> <printer>. Why is that? We have the problem only on our HP printers. The PDF prints fine with Adobe Reader e.g.Paternal
U
2

I wrote and released a small Nuget Package which can be used to print a PDF file to a printerdriver. It can also print to a XPS file or PDF file. Here is a link to it.

Urnfield answered 10/2, 2020 at 8:13 Comment(1)
You haven't provided any "how-to" and dependencies, would you be kind enough to do so? Also, would it work with .Net Core?Bothwell
A
1

Looks like the usual suspects like pdfsharp and migradoc are not able to do that (pdfsharp only if you have Acrobat (Reader) installed).

I found here

https://vishalsbsinha.wordpress.com/2014/05/06/how-to-programmatically-c-net-print-a-pdf-file-directly-to-the-printer/

code ready for copy/paste. It uses the default printer and from what I can see it doesn't even use any libraries, directly sending the pdf bytes to the printer. So I assume the printer also needs to support it, on one 10 year old printer I tested this it worked flawlessly.

Most other approaches - without commercial libraries or applications - require you to draw yourself in the printing device context. Doable but will take a while to figure it out and make it work across printers.

Aman answered 5/8, 2017 at 14:29 Comment(0)
C
0

It depends on what you are trying to print. You need a third party pdf printer application or if you are printing data of your own you can use report viewer in visual studio. It can output reports to excel and pdf -files.

Card answered 6/4, 2011 at 12:30 Comment(0)
S
0

It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.

Here is the code for the approach I worked out on a win form web browser control:

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"path\to\file");
    }  

    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {   
        //Progress Changed fires multiple times, however after the Navigated event it is fired only once,
        //and at this point it is ready to print
        webBrowser1.ProgressChanged += (o, args) => 
        {
            webBrowser1.Print();//Note this does not print only brings up the print preview dialog
            //Should be on a separate task to ensure the main thread 
            //can fully initialize the print dialog 
            Task.Factory.StartNew(() => 
            {
                Thread.Sleep(1000);//We need to wait before we can send enter
                //This assumes that the print preview is still in focus
                Action g = () =>
                {
                    SendKeys.SendWait("{ENTER}");
                };
                this.Invoke(g);
            });
        };
    }
Sellars answered 15/1, 2014 at 22:2 Comment(0)
G
0

I advice you to try 2Printer command line tool from: http://www.doc2prn.com/

Command line example to print all PDF files from folder "C:\Input" is below. You can simple call it from your C# code.

2Printer.exe -s "C:\Input*.PDF" -prn "Canon MP610 series Printer"

Gobert answered 8/9, 2015 at 9:10 Comment(0)
I
-1

If you have Adobe Reader installed, then you should be able to just set it as the default printer. And VOILA! You can print to PDF!

printDocument1.PrinterSettings.PrinterName = "Adobe PDF";
printDocument1.Print();

Just as simple as that!!!

Impulse answered 6/11, 2018 at 3:30 Comment(0)
D
-2

Open, import, edit, merge, convert Acrobat PDF documents with a few lines of code using the intuitive API of Ultimate PDF. By using 100% managed code written in C#, the component takes advantage of the numerous built-in features of the .NET Framework to enhance performance. Moreover, the library is CLS compliant, and it does not use any unsafe blocks for minimal permission requirements. The classes are fully documented with detailed example code which helps shorten your learning curve. If your development environment is Visual Studio, enjoy the full integration of the online documentation. Just mark or select a keyword and press F1 in your Visual Studio IDE, and the online documentation is represented instantly. A high-performance and reliable PDF library which lets you add PDF functionality to your .NET applications easily with a few lines of code.

PDF Component for NET

Dantedanton answered 23/6, 2018 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.