How to print a PDF file in C#

By FoxLearn 7/8/2024 8:57:53 AM   380
Printing a PDF file in C# can be accomplished using libraries like RawPrint or Adobe Acrobat.

Here’s a basic example of how to print a PDF file in C#

1. Using Adobe Acrobat

If you want to use Adobe Acrobat Reader for printing PDF files in C# assumes that the user already has Acrobat Reader installed on their computer.

public void PrintPdf(string fileName)
{
    using (PrintDialog printDialog = new PrintDialog())
    {
        if (printDialog.ShowDialog() == DialogResult.OK)
        {
            ProcessStartInfo printProcessInfo = new ProcessStartInfo()
            {
                Verb = "print",
                CreateNoWindow = true,
                FileName = fileName,
                WindowStyle = ProcessWindowStyle.Hidden
            };

            Process printProcess = new Process();
            printProcess.StartInfo = printProcessInfo;
            printProcess.Start();

            printProcess.WaitForInputIdle();
            Thread.Sleep(1000);
            if (false == printProcess.CloseMainWindow())
            {
                printProcess.Kill();
            }
        }
    }
}

2. Using the RawPrint package

If you prefer not to use Acrobat Reader for printing PDF files in C#, you can utilize the RawPrint library. RawPrint allows you to send files directly to a Windows printer without relying on the printer driver.

First, you need to install the RawPrint library from NuGet.

Open your project in Visual Studio, then right-click on your project in Solution Explorer, select "Manage NuGet Packages...", search for RawPrint, and install it.

print pdf c# rawprint

Printing a PDF file in C# using the RawPrint library involves sending raw commands directly to the printer.

// c# print a PDF using its RAW data directly to the printer
public void PrintPdf(string fileName, string printerName)
{
    FileInfo fileInfo = new FileInfo(fileName);
    // Create an instance of the Printer
    IPrinter printer = new Printer();
    // Send the PDF file to the printer
    printer.PrintRawFile(printer, fileName, fileInfo.Name);
}

To get all printers in your computer, you can use the following c# code.

foreach (string printerName in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
    Console.WriteLine(printerName);
}

To print a PDF file using the RawPrint library in C#, you can utilize the PrintRawFile method from an instance of RawPrint.

Related