Extract all images from a PDF in C#
Save the images every page draws, as JPEG or PNG files.
Short answer
Section titled “Short answer”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.
#:package PdfNetStack@1.2.0using 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.
HorizontalResolutionandVerticalResolutiongive the dots per inch at which it is drawn. Decodehandles raw samples, JPEG, JPEG 2000, CCITT fax and JBIG2. Soft masks are not applied, andDecodereturns null for an unsupported color space.