Category / Section
How to print a PDF using the PdfToImageConverter library
2 mins read
The Syncfusion Essential® PDF is a feature-rich and high-performance .NET PDF library used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, we can print a PDF using the PdfToImageConverter in C#.
Steps to print a PDF using the PdfToImageConverter programmatically:
- Create a new console application project.
- Install the Syncfusion.PdfToImageConverter.Net NuGet package as a reference to your console application from Nuget.org.
- Include the following namespaces in the Program.cs file.
C#
using Syncfusion.PdfToImageConverter;
using System.Drawing;
using System.Drawing.Printing;
- Use the following code sample in Program.cs to print a PDF using the PdfToImageConverter.
C#
public class Program
{
static int itr = 0;
static Bitmap[] bitmaps;
static void Main(string[] args)
{
// Initialize PDF to Image converter.
PdfToImageConverter imageConverter = new PdfToImageConverter();
// Load the PDF document as a stream
FileStream inputStream = new FileStream("../../../Input.pdf", FileMode.Open, FileAccess.ReadWrite);
imageConverter.Load(inputStream);
bitmaps = new Bitmap[imageConverter.PageCount - 1];
// Convert PDF to Image.
Stream[] outputStream = imageConverter.Convert(0, imageConverter.PageCount - 1, false, false);
bitmaps = BitmapConverter.ConvertStreamsToBitmaps(outputStream);
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += PrintDocument_PrintPage;
printDocument.Print();
}
private static void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawImage(bitmaps[itr], 0, 0, e.PageBounds.Width, e.PageBounds.Height);
e.HasMorePages = itr < bitmaps.Length - 1;
itr = itr + 1;
}
}
public class BitmapConverter
{
public static Bitmap[] ConvertStreamsToBitmaps(Stream[] streams)
{
Bitmap[] bitmaps = new Bitmap[streams.Length];
for (int i = 0; i < streams.Length; i++)
{
bitmaps[i] = new Bitmap(streams[i]);
}
return bitmaps;
}
}
A complete working sample can be downloaded from Print_PDF_in_PdfToImageConverter.zip
By executing the program, you will get the PDF document as follows.
Take a moment to peruse the documentation for working with images, where you will find other options like inserting, replacing image in PDF document, image pagination, and image masking.
Refer here to explore the rich set of Syncfusion Essential® PDF features.