The PDF Images Extractor component of the library allows you to extract images from PDF documents in PNG format. This component is distributed as part of the Winnovative.Pdf.Next.PdfProcessor.Windows NuGet package when targeting Windows and as part of the Winnovative.Pdf.Next.PdfProcessor.Linux package when targeting Linux. The package for Windows is referenced by the Winnovative.Pdf.Next.Windows meta package and the package for Linux is referenced by the Winnovative.Pdf.Next.Linux meta package.
You can specify the page range in the PDF document from which to extract images. The extracted images preserve the transparency information from the PDF document. Extraction of password protected PDF documents is also supported and you can provide both user and owner passwords.
The Winnovative.Pdf.NextPdfImagesExtractor class allows you to load a PDF file and extract images from its pages in PNG format.
The Winnovative.Pdf.NextPdfImagesExtractor class is used to extract images from PDF documents. You can create an instance using the default constructor, which initializes the extractor with standard settings.
// Create the PDF Images Extractor instance with default options
PdfImagesExtractor pdfImagesExtractor = new PdfImagesExtractor();Note that PdfImagesExtractor instances are not reusable. You must create a new instance for each extraction. Reusing an instance after a completed extraction will result in an exception.
If the PDF document from which you extract images is password protected you have to specify the user or owner password to be used to decrypt the PDF document before extraction. You can set the user password in the PdfImagesExtractorUserPassword property and the owner password in the PdfImagesExtractorOwnerPassword property.
pdfImagesExtractor.UserPassword = userPasswordString;
pdfImagesExtractor.OwnerPassword = ownerPasswordString;The PdfImagesExtractorMaxPageCount property controls the upper limit for the number of PDF pages to process. The PDF page range from which to extract images can be set in the extraction methods. The default is 0 which means there is no upper limit.
pdfImagesExtractor.MaxPageCount = 0;pdfImagesExtractor.MaxPageCount = 10;To extract images from all pages in a PDF document from a memory buffer, use the PdfImagesExtractorExtractImages(Byte) method. The parameter is the PDF document read into a memory buffer.
The function returns an array of arrays of ExtractedImage objects. Each element in the outer array represents a page in the PDF document, and each inner array contains the images extracted from that page. For example, images[1] returns all images extracted from the second page, and images[1][2] is the third image from the second page.
The ExtractedImage object contains information such as the page number in ExtractedImagePageNumber and the extracted image data in PNG format in ExtractedImageImageData.
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfBytes);To extract images from a PDF document from a memory buffer starting at the given page number through the end of the document, use the PdfImagesExtractorExtractImages(Byte, Int32) method. The first parameter is the PDF document read into a memory buffer, and the second parameter is the 1-based start page number.
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfBytes, startPageNumber);To extract images from a PDF document from a memory buffer starting at the given page number up to the end page number inclusive, use the PdfImagesExtractorExtractImages(Byte, Int32, Int32) method. The first parameter is the PDF document read into a memory buffer, and the second and third parameters are the 1-based start and end page numbers. If the end page number is 0, the extraction continues to the end of the document.
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfBytes, startPageNumber, endPageNumber);There are also similar methods to extract images from PDF pages that accept a PDF stream or a PDF file path.
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfStream);
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfFile);ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfStream, startPageNumber);
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfFile, startPageNumber);ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfStream, startPageNumber, endPageNumber);
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfFile, startPageNumber, endPageNumber);The extraction methods above create the images in memory. There are similar methods to extract images from PDF pages to image files on disk in a specified folder. The parameters of these methods are the same as above with two additional parameters specifying the output folder path and the output file name without extension, which will be used as a base name for the generated image files. The final image file names will be formed by appending the page number and the image number in the page to the base name. The output folder is created if it does not exist.
pdfImagesExtractor.ExtractImagesToFile(inputPdfBytes, outputDirectory, imageFileName);
pdfImagesExtractor.ExtractImagesToFile(inputPdfStream, outputDirectory, imageFileName);
pdfImagesExtractor.ExtractImagesToFile(inputPdfFile, outputDirectory, imageFileName);pdfImagesExtractor.ExtractImagesToFile(inputPdfBytes, startPageNumber, outputDirectory, imageFileName);
pdfImagesExtractor.ExtractImagesToFile(inputPdfStream, startPageNumber, outputDirectory, imageFileName);
pdfImagesExtractor.ExtractImagesToFile(inputPdfFile, startPageNumber, outputDirectory, imageFileName);pdfImagesExtractor.ExtractImagesToFile(inputPdfBytes, startPageNumber, endPageNumber, outputDirectory, imageFileName);
pdfImagesExtractor.ExtractImagesToFile(inputPdfStream, startPageNumber, endPageNumber, outputDirectory, imageFileName);
pdfImagesExtractor.ExtractImagesToFile(inputPdfFile, startPageNumber, endPageNumber, outputDirectory, imageFileName);There are also asynchronous variants of these methods that follow the Task-based Asynchronous Pattern (TAP) in .NET, allowing image extraction from PDF to run in parallel using async and await. These methods share the same names as their synchronous counterparts and include the "Async" suffix. They also accept an optional System.ThreadingCancellationToken parameter that can be used to cancel the extraction operation where applicable.
To extract images from all pages in a PDF document from a memory buffer, use the PdfImagesExtractorExtractImagesAsync(Byte, CancellationToken) method. The parameter is the PDF document read into a memory buffer.
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfBytes);To extract images from a PDF document from a memory buffer starting at the given page number through the end of the document, use the PdfImagesExtractorExtractImagesAsync(Byte, Int32, CancellationToken) method. The first parameter is the PDF document read into a memory buffer, and the second parameter is the 1-based start page number.
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfBytes, startPageNumber);To extract images from a PDF document from a memory buffer starting at the given page number up to the end page number inclusive, use the PdfImagesExtractorExtractImagesAsync(Byte, Int32, Int32, CancellationToken) method. The first parameter is the PDF document read into a memory buffer, and the second and third parameters are the 1-based start and end page numbers. If the end page number is 0, the extraction continues to the end of the document.
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfBytes, startPageNumber, endPageNumber);There are also similar methods to extract images from PDF pages that accept a PDF stream or a PDF file path.
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfStream);
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfFile);ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfStream, startPageNumber);
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfFile, startPageNumber);ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfStream, startPageNumber, endPageNumber);
ExtractedImage[][] extractedImages = await pdfImagesExtractor.ExtractImagesAsync(inputPdfFile, startPageNumber, endPageNumber);The extraction methods above create the images in memory. There are similar methods to extract images from PDF pages to image files on disk in a specified folder. The parameters of these methods are the same as above with two additional parameters specifying the output folder path and the output file name without extension, which will be used as a base name for the generated image files. The final image file names will be formed by appending the page number and the image number in the page to the base name. The output folder is created if it does not exist.
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfBytes, outputDirectory, imageFileName);
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfStream, outputDirectory, imageFileName);
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfFile, outputDirectory, imageFileName);await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfBytes, startPageNumber, outputDirectory, imageFileName);
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfStream, startPageNumber, outputDirectory, imageFileName);
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfFile, startPageNumber, outputDirectory, imageFileName);await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfBytes, startPageNumber, endPageNumber, outputDirectory, imageFileName);
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfStream, startPageNumber, endPageNumber, outputDirectory, imageFileName);
await pdfImagesExtractor.ExtractImagesToFileAsync(inputPdfFile, startPageNumber, endPageNumber, outputDirectory, imageFileName);The PdfImagesExtractorExtractionInfo property exposes an object of Winnovative.Pdf.NextPdfImagesExtractionInfo type which is populated after the extraction completes successfully with information about the extraction process such as the number of PDF pages within the specified range from which images were extracted.
int numberOfPagesExtracted = pdfImagesExtractor.ExtractionInfo.PageCount;using System;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Winnovative_Next_AspNetDemo.Models;
using Winnovative_Next_AspNetDemo.Models.PDF_Images_Extractor;
// Use Winnovative Namespace
using Winnovative.Pdf.Next;
namespace Winnovative_Next_AspNetDemo.Controllers.PDF_Images_Extractor
{
public class Extract_PDF_ImagesController : Controller
{
private readonly IWebHostEnvironment m_hostingEnvironment;
public Extract_PDF_ImagesController(IWebHostEnvironment hostingEnvironment)
{
m_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
var model = SetViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> ExtractPdfImages(Extract_PDF_Images_ViewModel model)
{
if (!ModelState.IsValid)
{
var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
throw new ValidationException(errorMessage);
}
// Set license key received after purchase to use the extractor in licensed mode
// Leave it not set to use the library in demo mode
Licensing.LicenseKey = "3FJDU0ZDU0NTQkddQ1NAQl1CQV1KSkpKU0M=";
// Create the PDF Images Extractor instance with default options
PdfImagesExtractor pdfImagesExtractor = new PdfImagesExtractor();
// Optionally set the user password to open a password-protected PDF
if (!string.IsNullOrEmpty(model.UserPassword))
pdfImagesExtractor.UserPassword = model.UserPassword;
// Optionally set the owner password to open a password-protected PDF
if (!string.IsNullOrEmpty(model.OwnerPassword))
pdfImagesExtractor.OwnerPassword = model.OwnerPassword;
// PDF page number to start extraction from
int startPageNumber = model.StartPageNumber;
// PDF page number to end extraction at
// If 0, extraction continues to the end of the document
int endPageNumber = 0;
if (model.EndPageNumber.HasValue)
endPageNumber = model.EndPageNumber.Value;
byte[] inputPdfBytes = null;
string outputFileName = null;
// If an uploaded file exists, use it with priority
if (model.PdfFile != null && model.PdfFile.Length > 0)
{
try
{
using var ms = new MemoryStream();
await model.PdfFile.CopyToAsync(ms);
inputPdfBytes = ms.ToArray();
}
catch (Exception ex)
{
throw new Exception("Failed to read the uploaded PDF file", ex);
}
outputFileName = Path.GetFileNameWithoutExtension(model.PdfFile.FileName);
}
else
{
// Otherwise, fall back to the URL
string pdfUrl = model.PdfFileUrl?.Trim();
if (string.IsNullOrWhiteSpace(pdfUrl))
throw new Exception("No PDF file provided: upload a file or specify a URL");
try
{
if (pdfUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
string localPath = new Uri(pdfUrl).LocalPath;
inputPdfBytes = await System.IO.File.ReadAllBytesAsync(localPath);
}
else
{
using var httpClient = new System.Net.Http.HttpClient();
inputPdfBytes = await httpClient.GetByteArrayAsync(pdfUrl);
}
}
catch (Exception ex)
{
throw new Exception("Could not download the PDF file from URL", ex);
}
outputFileName = Path.GetFileNameWithoutExtension(model.PdfFileUrl);
}
// Extract the images from the specified PDF page range, grouped by page
ExtractedImage[][] extractedImages = pdfImagesExtractor.ExtractImages(inputPdfBytes, startPageNumber, endPageNumber);
int nPdfPages = extractedImages.Length;
if (nPdfPages == 1 && extractedImages[0].Length > 0 && model.ExtractLargest)
{
// If only one page was processed and only the largest image is requested, return that image directly
// Return the largest image as a downloadable file
outputFileName += "-largest.png";
ExtractedImage largestImage = GetLargestImage(extractedImages[0]);
return File(largestImage.ImageData, "image/png", outputFileName);
}
else
{
// Build an in-memory ZIP with all page images and return it
using var zipMs = new MemoryStream();
using (var zip = new System.IO.Compression.ZipArchive(zipMs, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true))
{
for (int pageIdx = 0; pageIdx < extractedImages.Length; pageIdx++)
{
var pageImages = extractedImages[pageIdx];
if (model.ExtractLargest)
{
// Add only the largest image from the page to the ZIP
ExtractedImage largestImage = GetLargestImage(pageImages);
if (largestImage != null)
{
var entry = zip.CreateEntry($"page-{largestImage.PageNumber:000000}-largest.png", System.IO.Compression.CompressionLevel.Fastest);
// Write the image bytes into the ZIP entry
using var entryStream = entry.Open();
entryStream.Write(largestImage.ImageData, 0, largestImage.ImageData.Length);
}
}
else
{
// Add all images from the PDF page to the ZIP
for (int imgIdx = 0; imgIdx < pageImages.Length; imgIdx++)
{
ExtractedImage extractedImage = pageImages[imgIdx];
var entry = zip.CreateEntry($"page-{extractedImage.PageNumber:000000}-{imgIdx:000000}.png", System.IO.Compression.CompressionLevel.Fastest);
// Write the image bytes into the ZIP entry
using var entryStream = entry.Open();
entryStream.Write(extractedImage.ImageData, 0, extractedImage.ImageData.Length);
}
}
}
}
outputFileName += ".zip";
// Copy ZIP memory stream to a byte array
byte[] outputZipBytes = zipMs.ToArray();
// Return the ZIP as a downloadable file
return File(outputZipBytes, "application/zip", outputFileName);
}
}
private ExtractedImage GetLargestImage(ExtractedImage[] extractedImages)
{
ExtractedImage largestImage = null;
int largestSize = 0;
foreach (var image in extractedImages)
{
if (image.ImageData.Length > largestSize)
{
largestImage = image;
largestSize = image.ImageData.Length;
}
}
return largestImage;
}
private Extract_PDF_Images_ViewModel SetViewModel()
{
var model = new Extract_PDF_Images_ViewModel();
HttpRequest request = ControllerContext.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
if (request.Host.Port != null)
uriBuilder.Port = (int)request.Host.Port;
uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Extract_PDF_Images".Length);
model.PdfFileUrl = rootUrl + "/DemoAppFiles/Input/PdfProcessor_Files/PDF_Document.pdf";
return model;
}
}
}