Przejdź do treści stopki
KORZYSTANIE Z IRONPRINT

C# Wysyłanie pliku PDF do drukarki (samouczek krok po kroku)

PDF means "Portable Document Format". There are many scenarios where a developer needs to print PDF files programmatically in an application. In C#, this can be a very tedious task, but thanks to IronPDF, it has become very easy to do with just a few lines of code. This tool allows us to print PDF documents with default printer settings as well as with custom printing options. In this tutorial, you will learn how to print PDFs using the C# language.

Topics Covered In This Tutorial

The following topics will be covered here:

  • The IronPDF Library
  • Creating a C# Console Project
  • Installing IronPDF
    1. NuGet Menedżer pakietów
    2. NuGet Konsola menedżera pakietów
    3. Using DLL files
  • Adding the IronPDF Namespace
  • Printing PDF documents
    1. Create a PDF document and print PDFs
    2. Create a PDF document from URLs and print
    3. Advanced printing
  • Podsumowanie

IronPDF

IronPDF is a PDF Library for the .NET Framework that allows developers to create PDF files easily. IronPDF's rendering is "pixel-perfect" for desktop versions of Google Chrome. IronPDF easily creates PDF documents using a single line of code. It can process PDF documents without Acrobat Reader or other PDF viewers.

IronPDF can be used for creating PDF files from HTML strings, from HTML files, or from URLs. Afterward, it can send these files to a default printer for printing.

A free trial of IronPDF is available.

Some important features of the IronPDF library

  • Create PDF documents from HTML 4 and 5, CSS, and JavaScript
  • Generate PDF documents from URLs
  • Print a PDF to a default, physical printer
  • Set print job settings (for printing specific pages, etc.)
  • Load URLs with custom-network login credentials, user agents, proxies, cookies, HTTP headers, and form fields or variables, thereby allowing access to web pages behind HTML login forms
  • Read and fill PDF (Portable Document Format) form-field data
  • Extract images and texts from PDF files
  • Digitally sign PDF documents
  • No third-party library required

1. Utwórz projekt w języku C

This tutorial will use Visual Studio 2022, but you may also use earlier versions.

  • Open Visual Studio 2022.
  • Create a new C# .NET console project. Select the .NET Core console application.
How to Send PDFs to Printer Using C#, Figure 1: Aplikacja konsolowa

Aplikacja konsolowa

  • Give a name to the project, e.g., DemoApp.
  • The .NET Framework 6.0 is the latest and most stable version that we are going to use. Click the "Create" button.
How to Send PDFs to Printer Using C#, Figure 2: .NET Framework

.NET Framework

2. Zainstaluj bibliotekę IronPDF

To install the IronPDF Library we can use any of the methods listed below:

2.1. NuGet Menedżer pakietów

We can install the IronPDF C# .NET Core Library from the NuGet Menedżer pakietów.

Open the Menedżer pakietów by clicking on Tools > NuGet Menedżer pakietów > Manage NuGet Packages for Solution.

How to Send PDFs to Printer Using C#, Figure 3: Menedżer pakietów

Menedżer pakietów

Or, right-click on the project in Solution Explorer and click Manage NuGet Packages.

How to Send PDFs to Printer Using C#, Figure 4: NuGet Menedżer pakietów - Solution Explorer

NuGet Menedżer pakietów - Solution Explorer

Search for IronPDF. Wybierz IronPDF i kliknij Instaluj. Rozpocznie się instalacja biblioteki.

How to Send PDFs to Printer Using C#, Figure 5: Zainstaluj IronPDF

Zainstaluj IronPDF

2.2. NuGet Konsola menedżera pakietów

Open the NuGet Konsola menedżera pakietów by clicking on Tools > NuGet Menedżer pakietów > Konsola menedżera pakietów.

Type the following command in the command line:

Install-Package IronPrint
How to Send PDFs to PRinter Using C#, Figure 6: NuGet Konsola menedżera pakietów

Konsola menedżera pakietów

2.3. Using a DLL File

Another way to use IronPDF in your project is to add a DLL file from the IronPDF library. You can download the DLL file from this link.

  • Pobierz plik ZIP z biblioteką DLL. Rozpakuj go do wybranego folderu.
  • Otwórz projekt w Visual Studio. In the Solution Explorer, right-click on "References" and browse for the IronPDF DLL file.

2.4. Add the IronPDF Namespace

Once the installation is done, add the IronPDF and System.Drawing namespace to your program file.

using IronPdf;
using System.Drawing;
using IronPdf;
using System.Drawing;
Imports IronPdf
Imports System.Drawing
$vbLabelText   $csharpLabel

Note: You must add these references to every file where you wish to use IronPDF's features.

IronPDF is installed and ready! We can now create our first PDF document for our .NET Core applications and send it to the default printer for printing. Przyjrzyjmy się niektórym z nich poniżej, korzystając z przykładów kodu.

3. Printing PDF Documents

3.1. Create and Print a PDF Document from HTML

It is very easy to process HTML strings and convert them to PDF format. This newly created file can be then printed using IronPDF. Here is the code that easily creates PDFs.

// Create an instance of ChromePdfRenderer
var chromePdfRenderer = new IronPdf.ChromePdfRenderer();

// Render any HTML fragment to a PDF document
using var pdfDocument = chromePdfRenderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1><p>This tutorial will help to print this text to a PDF file.</p>");

// Send the PDF to the default printer
pdfDocument.Print();

// Create a PrintDocument object that can be used for further configurations
System.Drawing.Printing.PrintDocument printDocument = pdfDocument.GetPrintDocument();
// Create an instance of ChromePdfRenderer
var chromePdfRenderer = new IronPdf.ChromePdfRenderer();

// Render any HTML fragment to a PDF document
using var pdfDocument = chromePdfRenderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1><p>This tutorial will help to print this text to a PDF file.</p>");

// Send the PDF to the default printer
pdfDocument.Print();

// Create a PrintDocument object that can be used for further configurations
System.Drawing.Printing.PrintDocument printDocument = pdfDocument.GetPrintDocument();
' Create an instance of ChromePdfRenderer
Dim chromePdfRenderer = New IronPdf.ChromePdfRenderer()

' Render any HTML fragment to a PDF document
Dim pdfDocument = chromePdfRenderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1><p>This tutorial will help to print this text to a PDF file.</p>")

' Send the PDF to the default printer
pdfDocument.Print()

' Create a PrintDocument object that can be used for further configurations
Dim printDocument As System.Drawing.Printing.PrintDocument = pdfDocument.GetPrintDocument()
$vbLabelText   $csharpLabel

This code will create a PDF file with the HTML content passed in the RenderHtmlAsPdf function. This function performs the conversion of HTML fragments to a PDF document.

You must be familiar with HTML tags to generate PDF files or PDF pages using the IronPDF library. We use the Print function to send the output of the PDF file to the printer. The printer dialog will appear, allowing you to confirm the print job.

3.2. Create and Print a PDF Document from URL

You can also create PDF documents using a URL:

// Create an instance of ChromePdfRenderer
var chromePdfRenderer = new IronPdf.ChromePdfRenderer();

// Render a PDF from a URL
var pdfDocument = chromePdfRenderer.RenderUrlAsPdf("https://ironpdf.com/");

// Send the PDF to the default printer
pdfDocument.Print();

// Create a PrintDocument object that can be used for further configurations
System.Drawing.Printing.PrintDocument printDocument = pdfDocument.GetPrintDocument();
// Create an instance of ChromePdfRenderer
var chromePdfRenderer = new IronPdf.ChromePdfRenderer();

// Render a PDF from a URL
var pdfDocument = chromePdfRenderer.RenderUrlAsPdf("https://ironpdf.com/");

// Send the PDF to the default printer
pdfDocument.Print();

// Create a PrintDocument object that can be used for further configurations
System.Drawing.Printing.PrintDocument printDocument = pdfDocument.GetPrintDocument();
' Create an instance of ChromePdfRenderer
Dim chromePdfRenderer = New IronPdf.ChromePdfRenderer()

' Render a PDF from a URL
Dim pdfDocument = chromePdfRenderer.RenderUrlAsPdf("https://ironpdf.com/")

' Send the PDF to the default printer
pdfDocument.Print()

' Create a PrintDocument object that can be used for further configurations
Dim printDocument As System.Drawing.Printing.PrintDocument = pdfDocument.GetPrintDocument()
$vbLabelText   $csharpLabel

Here, a PDF file is created from a specified URL and then printed.

How to Send PDFs to PRinter Using C#, Figure 7: Print PDF Generated from URL

Print PDF Generated from URL

4. Advanced Printing Options

IronPDF is versatile and quite capable of handling printing features such as finding a printer and setting print resolution.

4.1 Specify the Printer

To specify the printer, all you need to do is to get the current printing document object (using the GetPrintDocument method), then use the PrinterSettings.PrinterName property. You can choose any available printer.

using (var printDocument = pdfDocument.GetPrintDocument())
{
    // Specify the printer name
    printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";

    // Print the document
    printDocument.Print();
}
using (var printDocument = pdfDocument.GetPrintDocument())
{
    // Specify the printer name
    printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";

    // Print the document
    printDocument.Print();
}
Using printDocument = pdfDocument.GetPrintDocument()
	' Specify the printer name
	printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF"

	' Print the document
	printDocument.Print()
End Using
$vbLabelText   $csharpLabel

In the code sample above, "Microsoft Print to PDF" is chosen as a printer. More information about setting specific print settings can be found in the documentation pages.

4.2 Set Printer Resolution

You can also set the resolution for printing a PDF. The resolution refers to the quality of print in terms of the number of pixels. You can set the resolution of your printing document using the DefaultPageSettings.PrinterResolution property of the PDF document.

// Set custom printer resolution
printDocument.DefaultPageSettings.PrinterResolution = new System.Drawing.Printing.PrinterResolution
{
    Kind = System.Drawing.Printing.PrinterResolutionKind.Custom,
    X = 1200,
    Y = 1200
};
// Set custom printer resolution
printDocument.DefaultPageSettings.PrinterResolution = new System.Drawing.Printing.PrinterResolution
{
    Kind = System.Drawing.Printing.PrinterResolutionKind.Custom,
    X = 1200,
    Y = 1200
};
' Set custom printer resolution
printDocument.DefaultPageSettings.PrinterResolution = New System.Drawing.Printing.PrinterResolution With {
	.Kind = System.Drawing.Printing.PrinterResolutionKind.Custom,
	.X = 1200,
	.Y = 1200
}
$vbLabelText   $csharpLabel

4.3 Tracing Printing Processes Using C

In the following code example, you will see how to change the printer name, set the resolution, and get a count of the pages that were printed.

int printedPages;

using (var printDocument = pdfDocument.GetPrintDocument())
{
    // Specify the printer name
    printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";

    // Set custom printer resolution
    printDocument.DefaultPageSettings.PrinterResolution = new System.Drawing.Printing.PrinterResolution
    {
        Kind = System.Drawing.Printing.PrinterResolutionKind.Custom,
        X = 1200,
        Y = 1200
    };

    // Track number of printed pages
    printedPages = 0;
    printDocument.PrintPage += (sender, args) => printedPages++;

    // Print the document
    printDocument.Print();
}
int printedPages;

using (var printDocument = pdfDocument.GetPrintDocument())
{
    // Specify the printer name
    printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";

    // Set custom printer resolution
    printDocument.DefaultPageSettings.PrinterResolution = new System.Drawing.Printing.PrinterResolution
    {
        Kind = System.Drawing.Printing.PrinterResolutionKind.Custom,
        X = 1200,
        Y = 1200
    };

    // Track number of printed pages
    printedPages = 0;
    printDocument.PrintPage += (sender, args) => printedPages++;

    // Print the document
    printDocument.Print();
}
Dim printedPages As Integer

Using printDocument = pdfDocument.GetPrintDocument()
	' Specify the printer name
	printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF"

	' Set custom printer resolution
	printDocument.DefaultPageSettings.PrinterResolution = New System.Drawing.Printing.PrinterResolution With {
		.Kind = System.Drawing.Printing.PrinterResolutionKind.Custom,
		.X = 1200,
		.Y = 1200
	}

	' Track number of printed pages
	printedPages = 0
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: printDocument.PrintPage += (sender, args) => printedPages++;
	AddHandler printDocument.PrintPage, Sub(sender, args) printedPages
	printedPages += 1

	' Print the document
	printDocument.Print()
End Using
$vbLabelText   $csharpLabel

5. Podsumowanie

IronPDF is a complete solution for working with PDF documents. It provides the ability to convert from different formats to PDF. The manipulation and formatting of PDF files become very easy with the IronPDF library functions. All that is required are just a few lines of code to create and format the PDF file. It can also print PDFs programmatically. It does this by sending a PDF to the computer's default printer. We can either display print dialog windows to the users, or we can print silently using the overloads of the Print method.

A free trial of IronPDF is also available to test its full potential to generate and print PDF documents in your applications. More information about licensing can be found at this link.

Additionally, the current special offer allows you to obtain five Iron Software products for the price of just two.

Często Zadawane Pytania

Jak mogę wydrukować dokument PDF programowo w języku C#?

Możesz użyć IronPDF do programowego drukowania dokumentów PDF w języku C#. Korzystając z metod takich jak PRINT, możesz wysyłać pliki PDF do domyślnej lub określonej drukarki z możliwością dostosowania opcji drukowania.

Jakie są kroki instalacji biblioteki PDF do drukowania w języku C#?

Aby zainstalować bibliotekę IronPDF, można użyć menedżera pakietów NuGet w Visual Studio, konsoli menedżera pakietów NuGet lub dodać bibliotekę za pomocą plików DLL.

Czy za pomocą tej biblioteki mogę utworzyć plik PDF z kodu HTML?

Tak, IronPDF umożliwia tworzenie plików PDF z HTML przy użyciu metody RenderHtmlAsPdf. Umożliwia to konwersję HTML, CSS i JavaScript na dokumenty PDF.

Jak wysłać plik PDF do konkretnej drukarki za pomocą tej biblioteki?

Aby wysłać plik PDF do określonej drukarki, można ustawić właściwość PrinterSettings.PrinterName obiektu PrintDocument w IronPDF na nazwę żądanej drukarki.

Jakie zaawansowane opcje drukowania obsługuje ta biblioteka?

IronPDF obsługuje zaawansowane opcje drukowania, takie jak określanie ustawień drukarki, dostosowywanie rozdzielczości wydruku oraz śledzenie liczby wydrukowanych stron.

Czy za pomocą tej biblioteki PDF można ustawić niestandardowe rozdzielczości drukowania?

Tak, można ustawić niestandardowe rozdzielczości drukowania za pomocą właściwości DefaultPageSettings.PrinterResolution obiektu PrintDocument w IronPDF.

Jak za pomocą tej biblioteki mogę przekształcić adres URL w plik PDF?

Możesz renderować adres URL jako plik PDF za pomocą metody RenderUrlAsPdf biblioteki IronPDF, która pozwala konwertować strony internetowe na dokumenty PDF.

Czy ta biblioteka oferuje bezpłatną wersję próbną?

Tak, IronPDF oferuje bezpłatną wersję próbną, która pozwala użytkownikom zapoznać się z jego możliwościami w zakresie generowania i drukowania dokumentów PDF.

Czy mogę śledzić liczbę stron wydrukowanych przy użyciu tej biblioteki?

Tak, IronPDF umożliwia śledzenie liczby wydrukowanych stron poprzez dostęp do właściwości obiektu PrintDocument podczas zadania drukowania.

Z jakimi platformami jest kompatybilna ta biblioteka do drukowania plików PDF?

IronPDF jest kompatybilny z różnymi platformami, w tym Windows, macOS, Android i iOS, co sprawia, że jest wszechstronny w różnych środowiskach programistycznych.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie