Best practices for optimizing PDF processing in .NET

This guide outlines best practices for working with Nutrient .NET SDK (formerly GdPicture.NET).

Error handling

Errors in Nutrient .NET SDK are handled using status checks, and Nutrient .NET SDK doesn’t throw exceptions. This is to ensure code compatibility across different programming languages, some of which don’t support exceptions.

The status codes are the members of the GdPictureStatus enumeration. Many Nutrient .NET SDK methods return a member of the GdPictureStatus enumeration that displays the status of the performed operation.

The following code converts a PDF to a TIFF image. The example uses a status check to ensure the source PDF file is correctly loaded before continuing the process:

using GdPictureDocumentConverter gdpictureDocumentConverter = new GdPictureDocumentConverter();
GdPictureStatus status = gdpictureDocumentConverter.LoadFromFile(@"C:\temp\source.pdf",
GdPicture14.DocumentFormat.DocumentFormatPDF);
if (status == GdPictureStatus.OK)
{
Console.WriteLine("The PDF file has been loaded successfully.");
status = gdpictureDocumentConverter.SaveAsTIFF(@"C:\temp\output.tif",
TiffCompression.TiffCompressionAUTO);
if (status == GdPictureStatus.OK)
Console.WriteLine("The file has been saved successfully.");
else
Console.WriteLine($"The file has failed to save. Status: {status}");
}
else
Console.WriteLine($"The file has failed to load. Status: {status}");

Used methods

Releasing used images

After working with an image, release it from memory by passing the image ID to the DisposeImage method of the GdPictureDocumentUtilities class. As DisposeImage is a static method of a static class, you can use it without instantiating the GdPictureDocumentUtilities class. You can call this method on any image, irrespective of how you loaded it:

using GdPicturePDF gdpictureSourcePDF = new GdPicturePDF();
using GdPicturePDF gdpictureDestPDF = new GdPicturePDF();
gdpictureSourcePDF.LoadFromFile(@"C:\temp\source.pdf");
gdpictureDestPDF.NewPDF();
int pageCount = gdpictureSourcePDF.GetPageCount();
int imageCount = gdpictureSourcePDF.GetPageImageCount();
int imageID = 0;
for (int i = 1; i < pageCount; i++)
{
// Select the next PDF page.
gdpictureSourcePDF.SelectPage(i);
imageCount = gdpictureSourcePDF.GetPageImageCount();
for (int j = 1; j < imageCount; j++)
{
// Extract the image from the selected PDF page.
imageID = gdpictureSourcePDF.ExtractPageImage(j);
// Add the image to the destination PDF.
gdpictureDestPDF.AddImageFromGdPictureImage(imageID,
PdfAdvancedImageCompression.PdfAdvancedImageCompressionMRC);
// Release the image from memory.
GdPictureDocumentUtilities.DisposeImage(imageID);
}
}
gdpictureDestPDF.SaveToFile(@"C:\temp\output.pdf");