Skip to content

Extract all images from a PDF in C#

Since 1.1View as Markdown

Save the images every page draws, as JPEG or PNG files.

GetImages lists the images a page draws, with their placement and resolution. A JPEG (DCTDecode) is written as stored with GetEncodedData, so nothing is recompressed. Other images are decoded to 8 bit gray or RGB pixels with Decode and saved as PNG.

recipe-extract-images-from-pdf.cs
#:package PdfNetStack@1.2.0
using PdfNetStack;
PdfDocument doc = PdfDocument.Open("manual.pdf");
for (int p = 0; p < doc.Pages.Count; p++)
{
IReadOnlyList<PdfPageImage> images = doc.Pages[p].GetImages();
for (int i = 0; i < images.Count; i++)
{
PdfPageImage image = images[i];
string name = $"page{p + 1}-image{i + 1}";
if (image.Encoding == "DCTDecode")
{
File.WriteAllBytes(name + ".jpg", image.GetEncodedData()); // the JPEG as stored
}
else if (image.Decode() is PdfBitmap bitmap)
{
bitmap.SavePng(name + ".png"); // 8 bit gray or RGB pixels
}
Console.WriteLine($"{name}: {image.Width}x{image.Height}, {image.Encoding ?? "raw"}, {image.HorizontalResolution:0} dpi");
}
}
  • An image drawn on several pages is listed on each of them. HorizontalResolution and VerticalResolution give the dots per inch at which it is drawn.
  • Decode handles raw samples, JPEG, JPEG 2000, CCITT fax and JBIG2. Soft masks are not applied, and Decode returns null for an unsupported color space.