Why we convert PDF to image?
- PDF requires an external application like Adobe Acrobat Reader while image does not.
- Browsers have the built-in capability to display images while handling PDF documents requires an external application or plug-in.
So, in some specific cases converting your PDF documents to an image format like PNG or JPEG could be the solution we are looking for.
How to convert PDF to image in WPF?
For developers, we can easily render PDF pages to images with high quality by using Spire.PDF for WPF, which is a professional PDF component providing tons of useful methods to manipulate PDF document in your WPF applications. Now, follow the below steps to achieve this purpose.
Detailed steps:
Step 1: Create a new project by choosing WPF Application in Visual Studio, add a button in MainWindow, double click the button to write code.
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { } }
Step 2: Create a new instance of Spire.Pdf.Document and load the sample PDF file.
PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("sample.pdf");
Step 3: To convert PDF to image, we need firstly save PDF pages as BitmapSource by calling the method pdf.SaveAsImage, then convert BitmapSource to Bitmap, then save the Bitmap as image with a specified format using Image.Save().
BitmapSource source; Bitmap bmp; for(int i=0;i<pdf.Pages.Count;i++) { source = pdf.SaveAsImage(i); bmp = SourceToBitmap(source); bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png); } } private Bitmap SourceToBitmap(BitmapSource source) { Bitmap bmp; using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(ms); bmp = new Bitmap(ms); } return bmp; }
Output of the first page:
Full code:
using Spire.Pdf; namespace ConvertPdfToImage { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("1.pdf"); BitmapSource source; Bitmap bmp; for(int i=0;i<pdf.Pages.Count;i++) { source = pdf.SaveAsImage(i); bmp = SourceToBitmap(source); bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png); } } private Bitmap SourceToBitmap(BitmapSource source) { Bitmap bmp; using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(ms); bmp = new Bitmap(ms); } return bmp; } } }