Setting Up the Free Spire.PDF Library
Before writing any extraction logic, add the Free Spire.PDF library to your project. The simplest way is through the NuGet Package Manager:
- Right-click your project in Visual Studio and choose Manage NuGet Packages.
- Search for
Free Spire.PDFand install the official package. - Once the installation finishes, the required assemblies are automatically referenced.
The free edition imposes limits on the number of pages per document.
Extracting Images from All Pages
To retrieve every image embedded across an entire PDF, iterate over all pages, collect the image information, and persist each one to disk.
The PdfImageHelper class provides a GetImagesInfo() method that returns metadata and the image data for every picture on a page. The image content can then be saved via PdfImageInfo.Image.Save().
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;
namespace ImageExtractor
{
public static class FullDocumentExtractor
{
public static void SaveAllImages(string sourcePath, string outputFolder)
{
PdfDocument document = new PdfDocument();
document.LoadFromFile(sourcePath);
PdfImageHelper helper = new PdfImageHelper();
int counter = 0;
foreach (PdfPageBase page in document.Pages)
{
PdfImageInfo[] images = helper.GetImagesInfo(page);
foreach (PdfImageInfo info in images)
{
using (Image img = info.Image)
{
string fileName = System.IO.Path.Combine(outputFolder, $"img_{counter}.png");
img.Save(fileName);
counter++;
}
}
}
document.Dispose();
}
}
}
Extracting Images from a Specific Page
When you only need images from a chosen page—such as a cover illustration or a chart on a particular page—target that page directly using its zero-based index.
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;
namespace ImageExtractor
{
public static class SinglePageExtractor
{
public static void SaveImagesFromPage(string sourcePath, int pageNumber, string outputFolder)
{
PdfDocument document = new PdfDocument();
document.LoadFromFile(sourcePath);
// Page indexing starts at 0, so page 1 is index 0.
PdfPageBase target = document.Pages[pageNumber];
PdfImageHelper helper = new PdfImageHelper();
PdfImageInfo[] entries = helper.GetImagesInfo(target);
for (int i = 0; i < entries.Length; i++)
{
using (Image img = entries[i].Image)
{
string fileName = System.IO.Path.Combine(outputFolder, $"page_{pageNumber + 1}_item_{i}.png");
img.Save(fileName);
}
}
document.Dispose();
}
}
}
Choosing Output Formats
You can control the image format by changing the file extension in the Save() call. For example, use .jpg to save as JPEG:
img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
Practical Considerations
- The library operates purely on the managed .NET stack; no external PDF tools are required.
- The
PdfImageHelperworks with images embedded in the PDF content stream, not with vector graphics. - Manage resources carefully by disposing the
PdfDocumentobject, especially when processing large files in bulk.