[c#] Print Pdf in C#

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?

This question is related to c# .net pdf printing

The answer is


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.


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


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.


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();

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"


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


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.


Another approach, if you simply wish to print a PDF file programmatically, is to use the LPR command: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/lpr.mspx?mfr=true

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.


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);
            });
        };
    }

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!!!


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.


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


i wrote a very(!) 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...


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://stackoverflow.com/a/41751184/586754

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


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to pdf

ImageMagick security policy 'PDF' blocking conversion How to extract table as text from the PDF using Python? Extract a page from a pdf as a jpeg How can I read pdf in python? Generating a PDF file from React Components Extract Data from PDF and Add to Worksheet How to extract text from a PDF file? How to download PDF automatically using js? Download pdf file using jquery ajax Generate PDF from HTML using pdfMake in Angularjs

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application