Print PDF files in C# and VB.NET

With PDF .Net you can do silent printing or provide a print dialog and print preview as shown in examples for printing in WPF and printing in Windows Forms.

PDF documents can be printed on the default printer or you can specify other local or network printers connected to the machine.

Printing PDF files is currently supported on .NET Framework (and in future on .NET Core for Windows).

The following example shows how to print a PDF file silently in C# and VB.NET without user interaction.

Complete code

using System;
using SautinSoft.Pdf;
using System.IO;

class Program
{
	static void Main()
	{
		// This property is necessary only for licensed version.
		//SautinSoft.Pdf.Serial = "XXXXXXXXXXX";

		using (PDF .Net document = PdfDocument.Load("Potato Beetle.pdf"))
		{
			// Print PDF document to default printer (e.g. 'Microsoft Print to Pdf').
			string printerName = null;
			document.Print(printerName);
		}
	}
}

            

Download.

PDF .Net uses System.Printing namespace for managing print queues and print jobs. To leverage advance printing capabilities, like specifying printer's paper source (tray), specifying two-sided (duplex) printing, etc. you can use the PrintTicket class.

You would create PrintTicket object and define or configure desired printer's features with it. You would provide that configuration in a form of an XML stream (by calling PrintTicket.GetXmlStream method) to PDF Focus's PrintOptions.


Print PDF documents in a WPF application

In WPF applications you would commonly use PrintDialog to enable users to select a printer, configure it, and perform a print job. For example, your user may specify to print only certain pages of Word document, or to print multiple pages on one sheet of paper, or something else.

The following example shows how you can use PrintDialog to define PDF Focus's print options. Also, the example shows how you can use the DocumentViewer control for print previewing.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;
using SautinSoft.Pdf;
using Microsoft.Win32;

public partial class MainWindow : Window
{
	private PdfDocument document;

	public MainWindow()
	{
		// This property is necessary only for licensed version.
		//SautinSoft.Pdf.Serial = "XXXXXXXXXXX";

	}

	private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
	{
		if (this.document != null)
		this.document.Close();
	}

	private void LoadFileBtn_Click(object sender, RoutedEventArgs e)
	{
		OpenFileDialog openFileDialog = new OpenFileDialog();
		openFileDialog.Filter =
		"PDF files (*.pdf)|*.pdf";

		if (openFileDialog.ShowDialog() == true)
		{
			if (this.document != null)
			this.document.Close();

			this.document = PDF .Net.Load(openFileDialog.FileName);
			this.ShowPrintPreview();
		}
	}

	private void PrintFileBtn_Click(object sender, RoutedEventArgs e)
	{
		if (this.document == null)
		return;

		PrintDialog printDialog = new PrintDialog() { UserPageRangeEnabled = true };
		if (printDialog.ShowDialog() == true)
		{
			PrintOptions printOptions = new PrintOptions(printDialog.PrintTicket.GetXmlStream());

			printOptions.FromPage = printDialog.PageRange.PageFrom - 1;
			printOptions.ToPage = printDialog.PageRange.PageTo == 0 ? int.MaxValue : printDialog.PageRange.PageTo - 1;

			this.document.Print(printDialog.PrintQueue.FullName, printOptions);
		}
	}

	private void ShowPrintPreview()
	{
		XpsDocument xpsDocument = this.document.ConvertToXpsDocument(SaveOptions.Xps);

		// Note, XpsDocument must stay referenced so that DocumentViewer can access additional resources from it.
		// Otherwise, GC will collect/dispose XpsDocument and DocumentViewer will no longer work.
		this.DocViewer.Tag = xpsDocument;
		this.DocViewer.Document = xpsDocument.GetFixedDocumentSequence();
	}
}

            

Download.


Print PDF documents in a Windows Forms application

You can use the same DocumentViewer WPF control from the above example to create a print preview in Windows Forms applications as well. You can accomplish this by hosting the WPF control inside the ElementHost Windows Forms control.

Or as an alternative, you can use PrintPreviewControl and preview the Word document by providing the PrintDocument object to the control. The following example shows how you can you can render document's pages as images and draw does images on PrintDocument.PrintPage event for print previewing.


using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using SautinSoft.Pdf;

public partial class Form1 : Form
{
	private PdfDocument document;

	public Form1()
	{
		// This property is necessary only for licensed version.
		//SautinSoft.Pdf.Serial = "XXXXXXXXXXX";
	}

	private void Form1_FormClosing(object sender, FormClosingEventArgs e)
	{
		if (this.document != null)
		this.document.Close();
	}

	private void LoadFileMenuItem_Click(object sender, EventArgs e)
	{
		OpenFileDialog openFileDialog = new OpenFileDialog();
		openFileDialog.Filter =
		"PDF files (*.pdf)|*.pdf";

		if (openFileDialog.ShowDialog() == DialogResult.OK)
		{
			if (this.document != null)
			this.document.Close();

			this.document = PDF .Net.Load(openFileDialog.FileName);
			this.ShowPrintPreview();
		}
	}

	private void PrintFileMenuItem_Click(object sender, EventArgs e)
	{
		if (this.document == null)
		return;

		PrintDialog printDialog = new PrintDialog() { AllowSomePages = true };
		if (printDialog.ShowDialog() == DialogResult.OK)
		{
			PrinterSettings printerSettings = printDialog.PrinterSettings;
			PrintOptions printOptions = new PrintOptions();

			// Set PrintOptions properties based on PrinterSettings properties.
			printOptions.CopyCount = printerSettings.Copies;
			printOptions.FromPage = printerSettings.FromPage - 1;
			printOptions.ToPage = printerSettings.ToPage == 0 ? int.MaxValue : printerSettings.ToPage - 1;

			this.document.Print(printerSettings.PrinterName, printOptions);
		}
	}

	private void ShowPrintPreview()
	{
		// Create image for each Word document's page.
		Image[] images = this.CreatePrintPreviewImages();
		int imageIndex = 0;

		// Draw each page's image on PrintDocument for print preview.
		var printDocument = new PrintDocument();
		printDocument.PrintPage += (sender, e) =>
		{
			using (Image image = images[imageIndex])
			{
				var graphics = e.Graphics;
				var region = graphics.VisibleClipBounds;

				// Rotate image if it has landscape orientation.
				if (image.Width > image.Height)
				image.RotateFlip(RotateFlipType.Rotate270FlipNone);

				graphics.DrawImage(image, 0, 0, region.Width, region.Height);
			}

			++imageIndex;
			e.HasMorePages = imageIndex < images.Length;
		};

		this.PageUpDown.Value = 1;
		this.PageUpDown.Maximum = images.Length;
		this.PrintPreviewControl.Document = printDocument;
	}

	private Image[] CreatePrintPreviewImages()
	{
		int pageCount = this.document.Pages.Count;
		var images = new Image[pageCount];

		for (int pageIndex = 0; pageIndex < pageCount; ++pageIndex)
		{
			var imageStream = new MemoryStream();
			var imageOptions = new ImageSaveOptions(ImageSaveFormat.Png) { PageNumber = pageIndex };

			this.document.Save(imageStream, imageOptions);
			images[pageIndex] = Image.FromStream(imageStream);
		}

		return images;
	}

	private void PageUpDown_ValueChanged(object sender, EventArgs e)
	{
		this.PrintPreviewControl.StartPage = (int)this.PageUpDown.Value - 1;
	}
}

            

Download.


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.