PDF format, beyond all doubt, provides great convenience for people in daily work. But sometimes, the character of requiring an external application like Acrobat Reader makes things more complex. For example, images can be easily and quickly presented on browsers as long as you have image addresses or load them from your system. While for PDF document, it has to be presented by an external application. Besides, loading images can save much time compared with loading a PDF file since images can be loaded one by one, while PDF file is only available after the complete PDF document is downloaded. Furthermore, images are more likely to handle by Office applications. That is why people need to export PDF document pages to images.
Why choose Spire.PDF Viewer to export PDF file pages to images?
When it comes to the conversion or transformation from this document format to another, people subconsciously think about conversion software. But for Spire.PDF Viewer, you do not need any PDF converter and can realize the PDF to image task in two ways. Moreover, you can export the PDF pages to any image format such as png, jpg, bmp and so on. Finally, except exporting PDF pages to images, Spire.PDFViewer is a totally independent .NET library and has other functions such as open and read encrypted PDF files, view embedded PDF file with hyperlinks and so on.
Two solutions will be displayed to finish this task. The first solution is more complicated than the second one but it has more functions. So both methods have their own advantages. You can choose any one according to your own need.
First Method to export PDF pages to images
This method requires two forms. One is to load PDF document and the other is to display images which are exported from PDF file. You can export any page or pages to save as images. Details can be shown in the below procedure.
Step1. Create a new project.
- Create a new project in Windows Forms Application
- Set the target Framework in this project Properties to be .NET Framework 2.0 or above
Step2. Design two Forms.
- Add a toolScript and PdfDocumentViewer in Form1.
- Add three Buttons, two Labels and two ComboBoxes in Form1 from the toolScript dropdown list.
- Set the Properties of the Buttons, Labels, ComboBoxes and PdfDocumentViewer as below table
5. In FormImages, I add a FlowLayoutPanel to it and set its Name to be panelImages1, the Dock property to be Fill.
Step3. Export PDF file pages to images
- Click Form1, add Spire.PDFViewer Forms dll as reference from your downloaded Spire.PDFViewer. Then, add namespaces to the top of the method.
using System.IO;
using Spire.PdfViewer.Forms;
2. Load a PDF file from system and open it. This step also enables you to open another PDF from your system by clicking the “Open” button in Form1.
private void Form1_Load(object sender, EventArgs e)
{
string pdfDoc = @"D:\michelle\e-iceblue\Spire.PDFViewer\Demos\Data\PDFViewer.pdf";
if (File.Exists(pdfDoc))
{
this.pdfDocumentViewer1.LoadFromFile(pdfDoc);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "PDF document (*.pdf)|*.pdf";
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
try
{
string pdfFile = dialog.FileName;
this.pdfDocumentViewer1.LoadFromFile(pdfFile);
}
catch (Exception exe)
{
MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
3. Load the PDF document and use the “this.pdfDocumentViewer1.SaveAsImage(currentPage - 1)”to save the current PDF page as image.
private void pdfDocumentViewer1_PdfLoaded(object sender, EventArgs args)
{
this.comBoxFrom.Items.Clear();
this.comboxTo.Items.Clear();
int totalPage = this.pdfDocumentViewer1.PageCount;
for (int i = 1; i <= totalPage; i++)
{
this.comBoxFrom.Items.Add(i.ToString());
this.comboxTo.Items.Add(i.ToString());
}
this.comBoxFrom.SelectedIndex = 0;
this.comboxTo.SelectedIndex = 0;
}
private void btnExport_Click(object sender, EventArgs e)
{
if (this.pdfDocumentViewer1.PageCount > 0)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "JPG Format(*.jpg)|*.jpg|BMP Format(*.bmp)|*.bmp|PNG Format(*.png)|*.png|GIF Format(*.gif)|*.gif";
DialogResult result = dialog.ShowDialog();
string fileName = dialog.FileName;
if (result == DialogResult.OK)
{
int currentPage = this.pdfDocumentViewer1.CurrentPageNumber;
Bitmap image = this.pdfDocumentViewer1.SaveAsImage(currentPage - 1);
image.Save(fileName);
MessageBox.Show("You have exported current page to an image:\n" + fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
Dictionary<string, Image> dictionaryImages = new Dictionary<string, Image>();
dictionaryImages.Add(fileName, image);
this._formImages = new FormImages();
this._formImages.DictionaryImages = dictionaryImages;
this._formImages.Show();
}
}
}
4. Save multiple pages as images by selecting the PDF export range from the start page to the end page. And use the “this.pdfDocumentViewer1.SaveAsImage(fromPage, toPage)” method to save the images.
private void btnMultiExport_Click(object sender, EventArgs e)
{
if (this.pdfDocumentViewer1.PageCount <= 0)
{
return;
}
int fromPage = this.comBoxFrom.SelectedIndex;
int toPage = this.comboxTo.SelectedIndex;
if (fromPage > toPage)
{
MessageBox.Show("End page number must be not less than started page number!", "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
else
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
string path = dialog.SelectedPath;
Bitmap[] images = this.pdfDocumentViewer1.SaveAsImage(fromPage, toPage);
Dictionary<String, Image> dictionaryImages = new Dictionary<string, Image>();
for (int i = 0; i < images.Length; i++)
{
string name = "image" + (i + 1 + fromPage).ToString() + ".bmp";
string fileName = path + "\\" + name;
images[i].Save(fileName);
dictionaryImages.Add(fileName, images[i]);
}
string message = "You have exported " + (fromPage + 1).ToString() + "-" + (toPage + 1).ToString() + " pages as images to:\n"
+ path;
MessageBox.Show(message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
this._formImages = new FormImages();
this._formImages.DictionaryImages = dictionaryImages;
this._formImages.Show();
}
}
}
5. Display the images in the second Form: FormImages.
C# Code:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Spire.PdfViewer.Forms;
namespace pdf2images1
{
public partial class FormImages : Form
{
private Dictionary<String, Image> _dictionaryImags;
public Dictionary<String, Image> DictionaryImages
{
get { return this._dictionaryImags; }
set
{
this._dictionaryImags = value;
this.ViewImages();
}
}
public FormImages()
{
InitializeComponent();
}
public void ViewImages()
{
if (this.DictionaryImages != null && this.DictionaryImages.Count > 0)
{
this.panelImages1.Controls.Clear();
String image_name = "";
int panelHeight = 0;
int panelWidth = 0;
foreach (KeyValuePair<String, Image> pair in this.DictionaryImages)
{
image_name = pair.Key;
Panel panelImage = new Panel();
panelImage.AutoSize = true;
PictureBox ptrBox = new PictureBox();
ptrBox.Height = 150;
ptrBox.Width = 200;
ptrBox.SizeMode = PictureBoxSizeMode.Zoom;
ptrBox.Image = pair.Value;
ptrBox.Cursor = Cursors.Hand;
panelImage.Controls.Add(ptrBox);
LinkLabel lbl = new LinkLabel();
String imageName = Path.GetFileName(pair.Key);
lbl.Text = imageName;
int x = (Int32)(ptrBox.Width / 2 - lbl.Width / 2);
int y = ptrBox.Height;
lbl.Left = x;
lbl.Top = y;
panelImage.Controls.Add(lbl);
this.panelImages1.Controls.Add(panelImage);
this.SetClickEventHandler(ptrBox, lbl, image_name);
panelHeight = panelImage.Height;
panelWidth = panelImage.Width;
}
int nimages = this._dictionaryImags.Count;
if (nimages >= 4)
{
int n = (Int32)Math.Ceiling(Math.Sqrt(nimages));
this.Width = panelWidth * n + 20 * (n - 1) + 40;
this.Height = panelHeight * n + 20 * (n - 1) + 40;
}
}
}
private void SetClickEventHandler(PictureBox ptrBox, LinkLabel lbl, string imageName)
{
ptrBox.Click += new EventHandler(delegate(Object sender, EventArgs args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(imageName)
process.StartInfo = info;
process.Start();
});
lbl.Click += new EventHandler(delegate(Object sender, EventArgs args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(imageName)
process.StartInfo = info;
process.Start();
});
}
}
}
Step4. Debug the project.
Click the Debug or Press F5 to launch the project. You can preview as below.
This method is much simple and it needs a Form generated dynamically. Two buttons are provided. One is for exporting the current PDF page, the other is for exporting multiple pages. The difference between the first method and the second lies in you can choose any export range in the first method. For example, you can choose page 4-7 to save as images, but when you use method two, you have to save all the pages from 1-7 since it only support to save page from 1 to current page as images. Please look at the procedure.
Step1. Create a new project.
- Create a new project in Console Application.
- Set the target Framework to be .NET Framework 2 or above.
- Add System. Drawing and Spire.PdfViewer.Forms. dll as references and add the below namespaces at the top of the method.
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Spire.PdfViewer.Forms;
- Load a PDF file from system
viewer = new PdfDocumentViewer();
viewer.LoadFromFile(@"D:\michelle\e-iceblue\Spire.PDFViewer\Demos\Data\PDFViewer.pdf");
2. Create a new Form and design it. Except setting the properties of this Form, two buttons are added also. One is for exporting one page, and the other multiple pages.
//form and child components
Form mainForm = new Form();
mainForm.Text = "Spire.PdfView Demo - Export";
mainForm.Size = new System.Drawing.Size(800, 600);
mainForm.StartPosition = FormStartPosition.CenterScreen;
TableLayoutPanel table = new TableLayoutPanel();
table.ColumnCount = 3;
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 20));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
table.RowCount = 2;
table.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
table.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
table.Controls.Add(viewer, 0, 0);
table.SetColumnSpan(viewer, 3);
viewer.Dock = DockStyle.Fill;
//Export current page to one image
Button button = new Button();
button.Text = "Export to one image";
button.Size = new Size(180, 24);
button.TextAlign = ContentAlignment.MiddleCenter;
table.Controls.Add(button, 0, 1);
button.Dock = DockStyle.Right;
button.Click += ExportToOneImage;
//Export current pdf document to multiple images
button = new Button();
button.Text = "Export to multiple images";
button.Size = new Size(180, 24);
button.TextAlign = ContentAlignment.MiddleCenter;
table.Controls.Add(button, 2, 1);
button.Dock = DockStyle.Left;
button.Click += ExportToMultipleImages;
mainForm.Controls.Add(table);
table.Dock = DockStyle.Fill;
Application.Run(mainForm);
C# Code:
private static void ExportToOneImage(object sender, EventArgs e)
{
if (viewer.PageCount > 0)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "PNG Format(*.png)|*.png";
if (dialog.ShowDialog() == DialogResult.OK)
{
int currentPage = viewer.CurrentPageNumber;
Bitmap image = viewer.SaveAsImage(currentPage - 1);
image.Save(dialog.FileName);
MessageBox.Show("You have exported current page to an image:\n" + dialog.FileName, "Spire.PdfViewer Demo", MssageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
4. Save multiple PDF pages to images.
C# Code:
private static void ExportToMultipleImages(object sender, EventArgs e)
{
if (viewer.PageCount > 0)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
int currentPage = viewer.CurrentPageNumber;
Bitmap[] images = viewer.SaveAsImage(0, currentPage - 1);
for (int i = 0; i < images.Length; i++)
{
String fileName = Path.Combine(dialog.SelectedPath, String.Format("PDFViewer-{0}.png", i));
images[i].Save(fileName);
}
string message = "You have exported 1" + "-" + currentPage.ToString() + " pages as images to:\n" + dialog.SelectedPath;
MessageBox.Show(message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
Press F5 or click Debug to launch the project. Then, preview the effect.
More About Spire.PDFViewer
Spire.PDFViewer is a powerful PDF Viewer component performed on .NET and WPF. It enables developers to load PDF document from stream, file and byte array. Also it is available on viewing PDF/A-1B, PDF/X1A and enables to open and read encrypted PDF files.
Spire.PDFViewer for WPF